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

The following are Jave code examples for showing how to use synchronizedSet() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: com.zsmartsystems.zigbee   File: ZigBeeNetworkMeshMonitor.java   View Source Code Vote up 6 votes
private void startScheduler(int initialPeriod) {
    if (futureTask != null) {
        futureTask.cancel(true);
    }

    Runnable meshUpdateThread = new Runnable() {
        @Override
        public void run() {
            // Reset the node list
            synchronized (nodesInProgress) {
                nodesInProgress = Collections.synchronizedSet(new HashSet<Integer>());
            }

            // Start discovery from root node.
            startMeshUpdate(0);
        }
    };

    futureTask = scheduler.scheduleAtFixedRate(meshUpdateThread, initialPeriod, updatePeriod, TimeUnit.SECONDS);
}
 
Example 2
Project: hadoop   File: DelegationTokenRenewer.java   View Source Code Vote up 6 votes
public DelegationTokenToRenew(Collection<ApplicationId> applicationIds,
    Token<?> token,
    Configuration conf, long expirationDate, boolean shouldCancelAtEnd,
    String user) {
  this.token = token;
  this.user = user;
  if (token.getKind().equals(new Text("HDFS_DELEGATION_TOKEN"))) {
    try {
      AbstractDelegationTokenIdentifier identifier =
          (AbstractDelegationTokenIdentifier) token.decodeIdentifier();
      maxDate = identifier.getMaxDate();
    } catch (IOException e) {
      throw new YarnRuntimeException(e);
    }
  }
  this.referringAppIds = Collections.synchronizedSet(
      new HashSet<ApplicationId>(applicationIds));
  this.conf = conf;
  this.expirationDate = expirationDate;
  this.timerTask = null;
  this.shouldCancelAtEnd = shouldCancelAtEnd;
}
 
Example 3
Project: elasticsearch_my   File: NodeDisconnectIT.java   View Source Code Vote up 6 votes
public void testNotifyOnDisconnectInSniffer() throws IOException {
    internalCluster().ensureAtLeastNumDataNodes(2);

    final Set<DiscoveryNode> disconnectedNodes = Collections.synchronizedSet(new HashSet<>());
    try (TransportClient client = new MockTransportClient(Settings.builder()
        .put("cluster.name", internalCluster().getClusterName()).build(), Collections.emptySet(), (n, e) -> disconnectedNodes.add(n))) {
        int numNodes = 0;
        for (TransportService service : internalCluster().getInstances(TransportService.class)) {
            numNodes++;
            client.addTransportAddress(service.boundAddress().publishAddress());
        }
        Set<TransportAddress> discoveryNodes = client.connectedNodes().stream().map(n -> n.getAddress()).collect(Collectors.toSet());
        assertEquals(numNodes, discoveryNodes.size());
        assertEquals(0, disconnectedNodes.size());
        internalCluster().stopRandomDataNode();
        client.getNodesService().doSample();
        assertEquals(1, disconnectedNodes.size());
        assertTrue(discoveryNodes.contains(disconnectedNodes.stream().findAny().get().getAddress()));
    }
    assertEquals(1, disconnectedNodes.size());
}
 
Example 4
Project: OpenJSharp   File: POAFactory.java   View Source Code Vote up 5 votes
/** 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 5
Project: bromium   File: ReplayingState.java   View Source Code Vote up 5 votes
/**
 * Creates new replaying state
 * @param baseUri the base uri for building the whitelisted http urls
 */
@Inject
public ReplayingState(@Named(BASE_URI) URI baseUri) {
    this.synchronizationEventOptional = Optional.empty();
    this.httpLock = false;
    this.httpRequestQueue = Collections.synchronizedSet(new HashSet<>());
    this.conditionsSatisfied = Collections.synchronizedSet(new HashSet<>());
    this.whiteListHttp = buildWhiteList(baseUri);
}
 
Example 6
Project: monarch   File: JCAManagedConnection.java   View Source Code Vote up 5 votes
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 7
Project: hadoop   File: TestFileSystem.java   View Source Code Vote up 5 votes
public void testFsShutdownHook() throws Exception {
  final Set<FileSystem> closed = Collections.synchronizedSet(new HashSet<FileSystem>());
  Configuration conf = new Configuration();
  Configuration confNoAuto = new Configuration();

  conf.setClass("fs.test.impl", TestShutdownFileSystem.class, FileSystem.class);
  confNoAuto.setClass("fs.test.impl", TestShutdownFileSystem.class, FileSystem.class);
  confNoAuto.setBoolean("fs.automatic.close", false);

  TestShutdownFileSystem fsWithAuto =
    (TestShutdownFileSystem)(new Path("test://a/").getFileSystem(conf));
  TestShutdownFileSystem fsWithoutAuto =
    (TestShutdownFileSystem)(new Path("test://b/").getFileSystem(confNoAuto));

  fsWithAuto.setClosedSet(closed);
  fsWithoutAuto.setClosedSet(closed);

  // Different URIs should result in different FS instances
  assertNotSame(fsWithAuto, fsWithoutAuto);

  FileSystem.CACHE.closeAll(true);
  assertEquals(1, closed.size());
  assertTrue(closed.contains(fsWithAuto));

  closed.clear();

  FileSystem.closeAll();
  assertEquals(1, closed.size());
  assertTrue(closed.contains(fsWithoutAuto));
}
 
Example 8
Project: EscapeLag   File: AzurePlayerList.java   View Source Code Vote up 5 votes
private AzurePlayerList() {
    names = Collections.synchronizedSet(AzureAPI.newCaseInsensitiveSet()); // access in AsyncPreLoginEvent
    players = Lists.newArrayListWithExpectedSize(Bukkit.getMaxPlayers());
    
    join = Lists.newArrayList();
    quit = Lists.newArrayList();
    
    for (World world : Bukkit.getWorlds()) {
        for (Player each : world.getPlayers()) {
            names.add(each.getName());
            players.add(each);
        }
    }
}
 
Example 9
Project: JRediClients   File: LRUCacheMap.java   View Source Code Vote up 5 votes
public LRUCacheMap(int size, long timeToLiveInMillis, long maxIdleInMillis) {
    super(size, timeToLiveInMillis, maxIdleInMillis);
    
    for (int i = 0; i < Runtime.getRuntime().availableProcessors()*2; i++) {
        Set<CachedValue<K, V>> instance = Collections.synchronizedSet(new LinkedHashSet<CachedValue<K, V>>());
        queues.add(instance);
    }
}
 
Example 10
Project: flume-release-1.7.0   File: FlumeConfiguration.java   View Source Code Vote up 5 votes
/**
 * Check availability of sinks for group
 *
 * @param sinkSet
 *          [in]Existing valid sinks
 * @param usedSinks
 *          [in/out]Sinks already in use by other groups
 * @param groupConf
 *          [in]sinkgroup configuration
 * @return List of sinks available and reserved for group
 */
private Set<String> validGroupSinks(Set<String> sinkSet,
                                    Map<String, String> usedSinks,
                                    SinkGroupConfiguration groupConf) {
  Set<String> groupSinks =
      Collections.synchronizedSet(new HashSet<String>(groupConf.getSinks()));

  if (groupSinks.isEmpty()) return null;
  Iterator<String> sinkIt = groupSinks.iterator();
  while (sinkIt.hasNext()) {
    String curSink = sinkIt.next();
    if (usedSinks.containsKey(curSink)) {
      logger.warn("Agent configuration for '" + agentName + "' sinkgroup '"
          + groupConf.getComponentName() + "' sink '" + curSink
          + "' in use by " + "another group: '" + usedSinks.get(curSink)
          + "', sink not added");
      errorList.add(new FlumeConfigurationError(agentName, groupConf
          .getComponentName(),
          FlumeConfigurationErrorType.PROPERTY_PART_OF_ANOTHER_GROUP,
          ErrorOrWarning.ERROR));
      sinkIt.remove();
      continue;
    } else if (!sinkSet.contains(curSink)) {
      logger.warn("Agent configuration for '" + agentName + "' sinkgroup '"
          + groupConf.getComponentName() + "' sink not found: '" + curSink
          + "',  sink not added");
      errorList.add(new FlumeConfigurationError(agentName, curSink,
          FlumeConfigurationErrorType.INVALID_PROPERTY,
          ErrorOrWarning.ERROR));
      sinkIt.remove();
      continue;
    } else {
      usedSinks.put(curSink, groupConf.getComponentName());
    }
  }
  return groupSinks;
}
 
Example 11
Project: azeroth   File: UniqueIDGeneratorThreadSafetyIT.java   View Source Code Vote up 5 votes
@Test
public void multipleInstancesTest() throws InterruptedException {
    final Set<String> ids = Collections.synchronizedSet(new HashSet<String>());
    final int threadCount = 20;
    final int iterationCount = 10000;
    final CountDownLatch latch = new CountDownLatch(threadCount);

    for (int i = 0; i < threadCount; i++) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                IDGenerator generator = LocalUniqueIDGeneratorFactory.generatorFor(1, 1);
                try {
                    for (int i = 0; i < iterationCount; i++) {
                        byte[] id = generator.generate();
                        String asHex = Hex.encodeHexString(id);
                        ids.add(asHex);
                    }
                } catch (GeneratorException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        t.start();
    }

    boolean successfullyUnlatched = latch.await(20, TimeUnit.SECONDS);
    assertThat(successfullyUnlatched, is(true));

    assertThat(ids.size(), is(threadCount * iterationCount));
}
 
Example 12
Project: openjdk-jdk10   File: POAFactory.java   View Source Code Vote up 5 votes
/** 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 13
Project: azeroth   File: UniqueIDGeneratorThreadSafetyIT.java   View Source Code Vote up 5 votes
@Test
public void moreThanOneGeneratorClusterIDTest() throws InterruptedException {
    final Set<String> ids = Collections.synchronizedSet(new HashSet<String>());
    final int[][] profiles = { { 0, 0 }, { 1, 1 }, { 1, 2 }, { 1, 3 }, { 1, 15 }, { 2, 0 },
                               { 3, 0 }, { 4, 0 }, { 5, 0 }, { 63, 0 } };
    final int iterationCount = 10000;
    final CountDownLatch latch = new CountDownLatch(profiles.length);

    for (final int[] profile : profiles) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                IDGenerator generator = LocalUniqueIDGeneratorFactory.generatorFor(profile[0],
                    profile[1]);
                try {
                    for (int i = 0; i < iterationCount; i++) {
                        byte[] id = generator.generate();
                        String asHex = Hex.encodeHexString(id);
                        ids.add(asHex);
                    }
                } catch (GeneratorException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        t.start();
    }

    boolean successfullyUnlatched = latch.await(20, TimeUnit.SECONDS);
    assertThat(successfullyUnlatched, is(true));

    assertThat(ids.size(), is(profiles.length * iterationCount));
}
 
Example 14
Project: GCSApp   File: ImageCache.java   View Source Code Vote up 4 votes
/**
 * Initialize the cache, providing all parameters.
 * 
 * @param cacheParams
 *            The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
	ImageCacheParams mCacheParams = cacheParams;

	// BEGIN_INCLUDE(init_memory_cache)
	// Set up memory cache
	if (mCacheParams.memoryCacheEnabled) {
		if (BuildConfig.DEBUG) {
			Log.d(TAG, "Memory cache created (size = "
					+ mCacheParams.memCacheSize + ")");
		}

		// If we're running on Honeycomb or newer, create a set of reusable
		// bitmaps that can be
		// populated into the inBitmap field of BitmapFactory.Options. Note
		// that the set is
		// of SoftReferences which will actually not be very effective due
		// to the garbage
		// collector being aggressive clearing Soft/WeakReferences. A better
		// approach
		// would be to use a strongly references bitmaps, however this would
		// require some
		// balancing of memory usage between this set and the bitmap
		// LruCache. It would also
		// require knowledge of the expected size of the bitmaps. From
		// Honeycomb to JellyBean
		// the size would need to be precise, from KitKat onward the size
		// would just need to
		// be the upper bound (due to changes in how inBitmap can re-use
		// bitmaps).
		if (Utils.hasHoneycomb()) {
			mReusableBitmaps = Collections
					.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
		}

		mMemoryCache = new LruCache<String, BitmapDrawable>(
				mCacheParams.memCacheSize) {

			/**
			 * Notify the removed entry that is no longer being cached
			 */
			@Override
			protected void entryRemoved(boolean evicted, String key,
					BitmapDrawable oldValue, BitmapDrawable newValue) {
				if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
					// The removed entry is a recycling drawable, so notify
					// it
					// that it has been removed from the memory cache
					((RecyclingBitmapDrawable) oldValue).setIsCached(false);
				} else {
					// The removed entry is a standard BitmapDrawable

					if (Utils.hasHoneycomb()) {
						// We're running on Honeycomb or later, so add the
						// bitmap
						// to a SoftReference set for possible use with
						// inBitmap later
						mReusableBitmaps.add(new SoftReference<Bitmap>(
								oldValue.getBitmap()));
					}
				}
			}

			/**
			 * Measure item size in kilobytes rather than units which is
			 * more practical for a bitmap cache
			 */
			@Override
			protected int sizeOf(String key, BitmapDrawable value) {
				final int bitmapSize = getBitmapSize(value) / 1024;
				return bitmapSize == 0 ? 1 : bitmapSize;
			}
		};
	}

}
 
Example 15
Project: openjdk-jdk10   File: Subject.java   View Source Code Vote up 4 votes
public Subject(Set<? extends Principal> principals) {
    this.principals = Collections.synchronizedSet(new SecureSet<Principal>
            (this, PRINCIPAL_SET, principals));
}
 
Example 16
Project: jdk8u-jdk   File: java_util_Collections_SynchronizedSet.java   View Source Code Vote up 4 votes
protected Set<String> getAnotherObject() {
    Set<String> set = Collections.emptySet();
    return Collections.synchronizedSet(set);
}
 
Example 17
Project: openjdk-jdk10   File: java_util_Collections_SynchronizedSet.java   View Source Code Vote up 4 votes
protected Set<String> getAnotherObject() {
    Set<String> set = Collections.emptySet();
    return Collections.synchronizedSet(set);
}
 
Example 18
Project: guava-mock   File: BenchmarkHelpers.java   View Source Code Vote up 4 votes
@Override
public <E extends Comparable<E>> Set<E> create(Collection<E> contents) {
  return Collections.synchronizedSet(new HashSet<E>(contents));
}
 
Example 19
Project: DisplayingBitmaps   File: ImageCache.java   View Source Code Vote up 4 votes
/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 */
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps =
                    Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key,
                    BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap
                        // to a SoftReference set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}
 
Example 20
Project: jdk8u-jdk   File: java_util_Collections_SynchronizedSet.java   View Source Code Vote up 4 votes
protected Set<String> getObject() {
    Set<String> set = Collections.singleton("string");
    return Collections.synchronizedSet(set);
}