Java Code Examples for java.util.Collections#synchronizedSet()

The following examples show how to use java.util.Collections#synchronizedSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassLoader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private ClassLoader(Void unused, ClassLoader parent) {
    this.parent = parent;
    if (ParallelLoaders.isRegistered(this.getClass())) {
        parallelLockMap = new ConcurrentHashMap<>();
        package2certs = new ConcurrentHashMap<>();
        domains =
            Collections.synchronizedSet(new HashSet<ProtectionDomain>());
        assertionLock = new Object();
    } else {
        // no finer-grained lock; lock on the classloader instance
        parallelLockMap = null;
        package2certs = new Hashtable<>();
        domains = new HashSet<>();
        assertionLock = this;
    }
}
 
Example 2
Source File: ReactorIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testToFunction() throws Exception {
    CamelContext camelctx = createWildFlyCamelContext();
    camelctx.start();
    try {
        CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);

        /* A TreeSet will order the messages alphabetically regardless of the insertion order
         * This is important because in the Flux returned by Flux.flatMap(Function<? super T, ? extends
         * Publisher<? extends R>>) the emissions may interleave */
        Set<String> values = Collections.synchronizedSet(new TreeSet<>());
        CountDownLatch latch = new CountDownLatch(3);
        Function<Object, Publisher<String>> fun = crs.to("bean:hello", String.class);

        Flux.just(1, 2, 3)
            .flatMap(fun)
            .doOnNext(res -> values.add(res))
            .doOnNext(res -> latch.countDown())
            .subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
        Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
    } finally {
        camelctx.close();
    }
}
 
Example 3
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
private VideoCastManager(Context context, String applicationId, Class<?> targetActivity,
                         String dataNamespace) {
    super(context, applicationId);
    LOGD(TAG, "VideoCastManager is instantiated");
    mVideoConsumers = Collections.synchronizedSet(new HashSet<IVideoCastConsumer>());
    mDataNamespace = dataNamespace;
    if (null == targetActivity) {
        targetActivity = VideoCastControllerActivity.class;
    }
    mTargetActivity = targetActivity;
    Utils.saveStringToPreference(mContext, PREFS_KEY_CAST_ACTIVITY_NAME,
            mTargetActivity.getName());
    if (null != mDataNamespace) {
        Utils.saveStringToPreference(mContext, PREFS_KEY_CAST_CUSTOM_DATA_NAMESPACE,
                dataNamespace);
    }

    mMiniControllers = Collections.synchronizedSet(new HashSet<IMiniController>());

    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(context, VideoIntentReceiver.class);

    mHandler = new Handler(new UpdateNotificationHandlerCallback());
}
 
Example 4
Source File: JCAManagedConnection.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public JCAManagedConnection(JCAManagedConnectionFactory fact) {
  this.factory = fact;
  this.listeners = Collections
      .<ConnectionEventListener> synchronizedList(new ArrayList<ConnectionEventListener>());
  this.localTran = new JCALocalTransaction();
  this.connections = Collections
      .<GFConnectionImpl> synchronizedSet(new HashSet<GFConnectionImpl>());
}
 
Example 5
Source File: LimitedSet.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a limited set of a initial size, maximum size, and eviction mode.
 *
 * @param initialCapacity The initial size to allocate for the set.
 * @param maxSize The maximum number of elements to keep in the set.
 * @param mode A mode that determines which element is evicted when the set exceeds its max size.
 * @param <T> The type of object held in the set.
 * @return A thread-safe set that will evict elements when the max size is exceeded.
 */
public static final <T> Set<T> create(
    final int initialCapacity, final int maxSize, final Mode mode) {
  final boolean useAccessOrder = mode.equals(Mode.DROP_LEAST_RECENTLY_ACCESSED);
  return Collections.synchronizedSet(
      Collections.newSetFromMap(
          new LinkedHashMap<T, Boolean>(initialCapacity, 0.75f, useAccessOrder) {
            @Override
            protected boolean removeEldestEntry(final Map.Entry<T, Boolean> eldest) {
              return size() > maxSize;
            }
          }));
}
 
Example 6
Source File: MemoryMetadataModule.java    From heroic with Apache License 2.0 5 votes vote down vote up
@MemoryScope
@Provides
@Named("storage")
public Set<Series> storage() {
    if (synchronizedStorage) {
        return Collections.synchronizedSet(new HashSet<>());
    } else {
        return new ConcurrentSkipListSet<>();
    }
}
 
Example 7
Source File: SingletonSynchronizationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Tests the thread-safety of {@link EarlyInitSingleton}.
 */
@Test
public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() {
	ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
	Set<EarlyInitSingleton> resultSet = Collections.synchronizedSet(new HashSet<>());

	// Submits the instantiation tasks.
	for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
		executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance()));
	}

	// Since the instance of the object we inserted into the set is always
	// the same, the size should be one.
	Assert.assertEquals(1, resultSet.size());
}
 
Example 8
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
ServerImpl(HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog) throws IOException {
   this.protocol = protocol;
   this.wrapper = wrapper;
   this.logger = Logger.getLogger("com.sun.net.httpserver");
   ServerConfig.checkLegacyProperties(this.logger);
   this.https = protocol.equalsIgnoreCase("https");
   this.address = addr;
   this.contexts = new ContextList();
   this.schan = ServerSocketChannel.open();
   if (addr != null) {
      ServerSocket socket = this.schan.socket();
      socket.bind(addr, backlog);
      this.bound = true;
   }

   this.selector = Selector.open();
   this.schan.configureBlocking(false);
   this.listenerKey = this.schan.register(this.selector, 16);
   this.dispatcher = new ServerImpl.Dispatcher();
   this.idleConnections = Collections.synchronizedSet(new HashSet());
   this.allConnections = Collections.synchronizedSet(new HashSet());
   this.reqConnections = Collections.synchronizedSet(new HashSet());
   this.rspConnections = Collections.synchronizedSet(new HashSet());
   this.time = System.currentTimeMillis();
   this.timer = new Timer("server-timer", true);
   this.timer.schedule(new ServerImpl.ServerTimerTask(), (long)CLOCK_TICK, (long)CLOCK_TICK);
   if (timer1Enabled) {
      this.timer1 = new Timer("server-timer1", true);
      this.timer1.schedule(new ServerImpl.ServerTimerTask1(), TIMER_MILLIS, TIMER_MILLIS);
      this.logger.config("HttpServer timer1 enabled period in ms:  " + TIMER_MILLIS);
      this.logger.config("MAX_REQ_TIME:  " + MAX_REQ_TIME);
      this.logger.config("MAX_RSP_TIME:  " + MAX_RSP_TIME);
   }

   this.events = new LinkedList();
   this.logger.config("HttpServer created " + protocol + " " + addr);
}
 
Example 9
Source File: AlgorithmSchema.java    From mr4c with Apache License 2.0 5 votes vote down vote up
public AlgorithmSchema() {
	m_inputDatasets = Collections.synchronizedSet( new HashSet<String>() );
	m_requiredInputDatasets = Collections.synchronizedSet( new HashSet<String>() );
	m_optionalInputDatasets = Collections.synchronizedSet( new HashSet<String>() );
	m_excludedInputDatasets = Collections.synchronizedSet( new HashSet<String>() );
	m_outputDatasets = Collections.synchronizedSet( new HashSet<String>() );
	m_expectedDimensions = Collections.synchronizedSet( new HashSet<DataKeyDimension>() );
}
 
Example 10
Source File: SelectableAdapter.java    From FlexibleAdapter with Apache License 2.0 5 votes vote down vote up
/**
 * @since 1.0.0
 */
public SelectableAdapter() {
    if (Log.customTag == null) {
        Log.useTag("FlexibleAdapter");
    }
    log = new Logger(Log.customTag);
    log.i("Running version %s", BuildConfig.VERSION_NAME);
    mSelectedPositions = Collections.synchronizedSet(new TreeSet<Integer>());
    mBoundViewHolders = new HashSet<>();
    mMode = IDLE;

    mFastScrollerDelegate = new FastScroller.Delegate();
}
 
Example 11
Source File: POAFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** All object adapter factories must have a no-arg constructor.
*/
public POAFactory()
{
    poaManagers = Collections.synchronizedSet(new HashSet(4));
    poaManagerId = 0 ;
    poaId = 0 ;
    rootPOA = null ;
    delegateImpl = null ;
    orb = null ;
}
 
Example 12
Source File: MapleMonster.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
public void addSummonedMob(MapleMonster mob) {
    Set<Integer> calledOids = this.calledMobOids;
    if (calledOids == null) {
        calledOids = Collections.synchronizedSet(new HashSet<Integer>());
        this.calledMobOids = calledOids;
    }
    
    calledOids.add(mob.getObjectId());
    mob.setSummonerMob(this);
}
 
Example 13
Source File: CassandraNode.java    From Doradus with Apache License 2.0 5 votes vote down vote up
/**
 * Creates new CassandraNode instance connected to Cassandra-node on
 * specified host via specified JMX-port.
 * 
 * @param host
 *            The host name or ip-address. Set to null or empty value to
 *            specify local host.
 * @param port
 *            The port number. Set to 0 or negative value to specify default
 *            port.
 */
public CassandraNode(String host, int port) {
	if (port <= 0) {
		port = DEFAULT_JMX_PORT;
	}

	this.host = host;
	this.port = port;
	isLocal = isLocalHost();
	lockedMessages =  Collections.synchronizedSet(new HashSet<String>());

	try {
		storageServiceName = new ObjectName(
				"org.apache.cassandra.db:type=StorageService");

		runtimeServiceName = new ObjectName("java.lang:type=Runtime");
		osServiceName = new ObjectName("java.lang:type=OperatingSystem");

	} catch (MalformedObjectNameException ex) {
		logger.error("Program error.", ex);
	}

	String osv = System.getProperty("os.version");
	logger.debug("OS version: " + osv);
	// If OS version is x.y.z, strip .z part(s)
	while (osv.lastIndexOf('.') > osv.indexOf('.')) {
	    osv = osv.substring(0, osv.lastIndexOf('.'));
	}
	osversion = Float.parseFloat(osv);

	setDbtoolProps();
}
 
Example 14
Source File: java_util_Collections_SynchronizedSet.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
protected Set<String> getObject() {
    Set<String> set = Collections.singleton("string");
    return Collections.synchronizedSet(set);
}
 
Example 15
Source File: java_util_Collections_SynchronizedSet.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
protected Set<String> getObject() {
    Set<String> set = Collections.singleton("string");
    return Collections.synchronizedSet(set);
}
 
Example 16
Source File: Subscription.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Constructor, initialises the HashSet.
 * 
 * @param objectId ID of the remote publishing object.
 */
public Subscription(String objectId, int QoS) {
	this.objectId = objectId;
	this.QoS = QoS;
	eventSubscriptions = Collections.synchronizedSet(new HashSet<String>());
}
 
Example 17
Source File: BitmapPool.java    From ZGDanmaku with Apache License 2.0 4 votes vote down vote up
private BitmapPool() {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
    }
}
 
Example 18
Source File: java_util_Collections_SynchronizedSet.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
protected Set<String> getAnotherObject() {
    Set<String> set = Collections.emptySet();
    return Collections.synchronizedSet(set);
}
 
Example 19
Source File: BKLogHandler.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
protected void readLogSegmentsFromStore(final Versioned<List<String>> logSegmentNames,
                                        final Comparator<LogSegmentMetadata> comparator,
                                        final LogSegmentFilter segmentFilter,
                                        final CompletableFuture<Versioned<List<LogSegmentMetadata>>> readResult) {
    Set<String> segmentsReceived = new HashSet<String>();
    segmentsReceived.addAll(segmentFilter.filter(logSegmentNames.getValue()));
    Set<String> segmentsAdded;
    final Set<String> removedSegments = Collections.synchronizedSet(new HashSet<String>());
    final Map<String, LogSegmentMetadata> addedSegments =
            Collections.synchronizedMap(new HashMap<String, LogSegmentMetadata>());
    Pair<Set<String>, Set<String>> segmentChanges = logSegmentCache.diff(segmentsReceived);
    segmentsAdded = segmentChanges.getLeft();
    removedSegments.addAll(segmentChanges.getRight());

    if (segmentsAdded.isEmpty()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("No segments added for {}.", getFullyQualifiedName());
        }

        // update the cache before #getCachedLogSegments to return
        updateLogSegmentCache(removedSegments, addedSegments);

        List<LogSegmentMetadata> segmentList;
        try {
            segmentList = getCachedLogSegments(comparator);
        } catch (UnexpectedException e) {
            readResult.completeExceptionally(e);
            return;
        }

        readResult.complete(new Versioned<List<LogSegmentMetadata>>(segmentList, logSegmentNames.getVersion()));
        return;
    }

    final AtomicInteger numChildren = new AtomicInteger(segmentsAdded.size());
    final AtomicInteger numFailures = new AtomicInteger(0);
    for (final String segment: segmentsAdded) {
        String logSegmentPath = logMetadata.getLogSegmentPath(segment);
        LogSegmentMetadata cachedSegment = metadataCache.get(logSegmentPath);
        if (null != cachedSegment) {
            addedSegments.put(segment, cachedSegment);
            completeReadLogSegmentsFromStore(
                    removedSegments,
                    addedSegments,
                    comparator,
                    readResult,
                    logSegmentNames.getVersion(),
                    numChildren,
                    numFailures);
            continue;
        }
        metadataStore.getLogSegment(logSegmentPath)
                .whenComplete(new FutureEventListener<LogSegmentMetadata>() {

                    @Override
                    public void onSuccess(LogSegmentMetadata result) {
                        addedSegments.put(segment, result);
                        complete();
                    }

                    @Override
                    public void onFailure(Throwable cause) {
                        // LogSegmentNotFoundException exception is possible in two cases
                        // 1. A log segment was deleted by truncation between the call to getChildren and read
                        // attempt on the znode corresponding to the segment
                        // 2. In progress segment has been completed => inprogress ZNode does not exist
                        if (cause instanceof LogSegmentNotFoundException) {
                            removedSegments.add(segment);
                            complete();
                        } else {
                            // fail fast
                            if (1 == numFailures.incrementAndGet()) {
                                readResult.completeExceptionally(cause);
                                return;
                            }
                        }
                    }

                    private void complete() {
                        completeReadLogSegmentsFromStore(
                                removedSegments,
                                addedSegments,
                                comparator,
                                readResult,
                                logSegmentNames.getVersion(),
                                numChildren,
                                numFailures);
                    }
                });
    }
}
 
Example 20
Source File: ParallelWorldClassLoader.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public ParallelWorldClassLoader(ClassLoader parent,String prefix) {
    super(parent);
    this.prefix = prefix;
    jars = Collections.synchronizedSet(new HashSet<JarFile>());
}