java.util.Collections.synchronizedSet()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(180)

本文整理了Java中java.util.Collections.synchronizedSet()方法的一些代码示例,展示了Collections.synchronizedSet()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collections.synchronizedSet()方法的具体详情如下:
包路径:java.util.Collections
类名称:Collections
方法名:synchronizedSet

Collections.synchronizedSet介绍

[英]Returns a wrapper on the specified set which synchronizes all access to the set.
[中]返回指定集合上的包装器,该包装器同步对集合的所有访问。

代码示例

代码示例来源:origin: glyptodon/guacamole-client

/**
 * Stores the given connection record in the list of active connections
 * associated with the object having the given identifier.
 *
 * @param identifier
 *     The identifier of the object being connected to.
 *
 * @param record
 *     The record associated with the active connection.
 */
public void put(String identifier, ActiveConnectionRecord record) {
  synchronized (records) {
    // Get set of active connection records, creating if necessary
    Set<ActiveConnectionRecord> connections = records.get(identifier);
    if (connections == null) {
      connections = Collections.synchronizedSet(Collections.newSetFromMap(new LinkedHashMap<ActiveConnectionRecord, Boolean>()));
      records.put(identifier, connections);
    }
    // Add active connection
    connections.add(record);
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

stopWords.add(CandidatePhrase.createOrGet(word.trim()));
 commonEngWords = Collections.synchronizedSet(new HashSet<>());
 for (String file : commonWordsPatternFiles.split("[;,]"))
  commonEngWords.addAll(IOUtils.linesFromFile(file));
 if (otherSemanticClassesWords == null)
  otherSemanticClassesWords = Collections
    .synchronizedSet(new HashSet<>());
 for (String file : otherSemanticClassesFiles.split("[;,]")) {
  for (File f : listFileIncludingItself(file)) {
    String[] t = w.split("\\s+");
    if (t.length <= PatternFactory.numWordsCompoundMax)
     otherSemanticClassesWords.add(CandidatePhrase.createOrGet(w));
  + otherSemanticClassesWords.size());
} else {
 otherSemanticClassesWords = Collections.synchronizedSet(new HashSet<>());
 System.out.println("Size of othersemantic class variables is " + 0);
  Set<String> st = new HashSet<>();
  for(int j = 1; j < t.length; j++)
   st.add(t[j]);
  allowedTagsInitials.put(t[0], st);

代码示例来源:origin: kiegroup/jbpm

protected List<TaskSummary> collectTasksByPotentialOwners(List<Object[]> tasksByGroups) {
  Set<Long> tasksIds = Collections.synchronizedSet(new HashSet<Long>());
  Map<Long, List<String>> potentialOwners = Collections.synchronizedMap(new HashMap<Long, List<String>>());
  for (Object o : tasksByGroups) {
    Object[] get = (Object[]) o;
    tasksIds.add((Long) get[0]);
    if (potentialOwners.get((Long) get[0]) == null) {
      potentialOwners.put((Long) get[0], new ArrayList<String>());
    }
    potentialOwners.get((Long) get[0]).add((String) get[1]);
  }
  if (!tasksIds.isEmpty()) {
    List<TaskSummary> tasks = (List<TaskSummary>)persistenceContext.queryWithParametersInTransaction("TaskSummariesByIds", 
        persistenceContext.addParametersToMap("taskIds", tasksIds),
        ClassUtil.<List<TaskSummary>>castClass(List.class));
        
    for (TaskSummary ts : tasks) {
      ((InternalTaskSummary) ts).setPotentialOwners(potentialOwners.get(ts.getId()));
    }
    return tasks;
  }
  return new ArrayList<TaskSummary>();
}

代码示例来源:origin: apache/accumulo

final Set<String> filesToLoad = Collections.synchronizedSet(new HashSet<>());
for (FileStatus f : files)
 filesToLoad.add(f.getPath().toString());

代码示例来源:origin: kiegroup/jbpm

public List<TaskSummary> getTasksAssignedByGroups(List<String> groupIds) {
  if(groupIds == null || groupIds.isEmpty()){
   return Collections.EMPTY_LIST;
  }
  List<Object[]> tasksByGroups = (List<Object[]>) persistenceContext.queryWithParametersInTransaction("TasksAssignedAsPotentialOwnerByGroups", 
      persistenceContext.addParametersToMap("groupIds", groupIds),
      ClassUtil.<List<Object[]>>castClass(List.class));
      
  Set<Long> tasksIds = Collections.synchronizedSet(new HashSet<Long>());
  Map<Long, List<String>> potentialOwners = Collections.synchronizedMap(new HashMap<Long, List<String>>());
  for (Object o : tasksByGroups) {
    Object[] get = (Object[]) o;
    tasksIds.add((Long) get[0]);
    if (potentialOwners.get((Long) get[0]) == null) {
      potentialOwners.put((Long) get[0], new ArrayList<String>());
    }
    potentialOwners.get((Long) get[0]).add((String) get[1]);
  }
  if (!tasksIds.isEmpty()) {
    List<TaskSummary> tasks = (List<TaskSummary>) persistenceContext.queryWithParametersInTransaction("TaskSummariesByIds", 
          persistenceContext.addParametersToMap("taskIds", tasksIds),
          ClassUtil.<List<TaskSummary>>castClass(List.class));
    for (TaskSummary ts : tasks) {
      ((InternalTaskSummary) ts).setPotentialOwners(potentialOwners.get(ts.getId()));
    }
    return tasks;
  }
  return new ArrayList<TaskSummary>();
}

代码示例来源:origin: apache/activemq

@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
  // don't track selectors for advisory topics or temp destinations
  if (!AdvisorySupport.isAdvisoryTopic(info.getDestination()) && !info.getDestination().isTemporary()) {
    String destinationName = info.getDestination().getQualifiedName();
    LOG.debug("Caching consumer selector [{}] on  '{}'", info.getSelector(), destinationName);
    String selector = info.getSelector() == null ? MATCH_EVERYTHING : info.getSelector();
    if (!(ignoreWildcardSelectors && hasWildcards(selector))) {
      Set<String> selectors = subSelectorCache.get(destinationName);
      if (selectors == null) {
        selectors = Collections.synchronizedSet(new HashSet<String>());
      } else if (singleSelectorPerDestination && !MATCH_EVERYTHING.equals(selector)) {
        // in this case, we allow only ONE selector. But we don't count the catch-all "null/TRUE" selector
        // here, we always allow that one. But only one true selector.
        boolean containsMatchEverything = selectors.contains(MATCH_EVERYTHING);
        selectors.clear();
        // put back the MATCH_EVERYTHING selector
        if (containsMatchEverything) {
          selectors.add(MATCH_EVERYTHING);
        }
      }
      LOG.debug("adding new selector: into cache " + selector);
      selectors.add(selector);
      LOG.debug("current selectors in cache: " + selectors);
      subSelectorCache.put(destinationName, selectors);
    }
  }
  return super.addConsumer(context, info);
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testPoolSize() throws Exception {
 String poolName = "vert.x-" + TestUtils.randomAlphaString(10);
 int poolSize = 5;
 waitFor(poolSize);
 WorkerExecutor worker = vertx.createSharedWorkerExecutor(poolName, poolSize);
 CountDownLatch latch1 = new CountDownLatch(poolSize * 100);
 Set<String> names = Collections.synchronizedSet(new HashSet<>());
 for (int i = 0;i < poolSize * 100;i++) {
  worker.executeBlocking(fut -> {
   names.add(Thread.currentThread().getName());
   latch1.countDown();
  }, false, ar -> {
  });
 }
 awaitLatch(latch1);
 assertEquals(5, names.size());
}

代码示例来源:origin: Atmosphere/atmosphere

Set<Cookie> hs = Collections.synchronizedSet(new HashSet());
if (cs != null) {
  for (Cookie c : cs) {
    hs.add(c);

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testRandomPorts() throws Exception {
 int numServers = 10;
 Set<Integer> ports = Collections.synchronizedSet(new HashSet<>());
 AtomicInteger count = new AtomicInteger();
 for (int i = 0;i < numServers;i++) {
  vertx.createHttpServer().requestHandler(req -> {
   req.response().end();
  }).listen(0, DEFAULT_HTTP_HOST, onSuccess(s -> {
   int port = s.actualPort();
   ports.add(port);
   client.getNow(port, DEFAULT_HTTP_HOST, "/somepath", resp -> {
    if (count.incrementAndGet() == numServers) {
     assertEquals(numServers, ports.size());
     testComplete();
    }
   });
  }));
 }
 await();
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
public void testConcurrentLogging() throws Throwable {
  final Logger log = context.getLogger(ConcurrentLoggingWithJsonLayoutTest.class);
  final Set<Thread> threads = Collections.synchronizedSet(new HashSet<Thread>());
  final List<Throwable> thrown = Collections.synchronizedList(new ArrayList<Throwable>());
    threads.add(t);

代码示例来源:origin: org.apache.logging.log4j/log4j-core

@Test
public void testConcurrentLogging() throws Throwable {
  final Logger log = context.getLogger(ConcurrentLoggingWithGelfLayoutTest.class);
  final Set<Thread> threads = Collections.synchronizedSet(new HashSet<Thread>());
  final List<Throwable> thrown = Collections.synchronizedList(new ArrayList<Throwable>());
    threads.add(t);

代码示例来源:origin: web3j/web3j

Set<T> results = Collections.synchronizedSet(new HashSet<T>());
      results.add(result);
      transactionLatch.countDown();
    },

代码示例来源:origin: commons-collections/commons-collections

/**
 * Tests {@link BlockingBuffer#remove()} in combination with {@link BlockingBuffer#addAll(java.util.Collection)}
 * using multiple read threads.
 * <p/>
 * Two read threads should block on an empty buffer until a collection with two distinct objects is added then both
 * threads should complete. Each thread should have read a different object.
 */
public void testBlockedRemoveWithAddAll2() {
  Buffer blockingBuffer = BlockingBuffer.decorate( new MyBuffer() );
  Object obj1 = new Object();
  Object obj2 = new Object();
  Set objs = Collections.synchronizedSet( new HashSet() );
  objs.add( obj1 );
  objs.add( obj2 );
  // run methods will remove and compare -- must wait for addAll
  Thread thread1 = new ReadThread( blockingBuffer, objs, "remove" );
  Thread thread2 = new ReadThread( blockingBuffer, objs, "remove" );
  thread1.start();
  thread2.start();
  // give hungry read threads ample time to hang
  delay();
  blockingBuffer.addAll( objs );
  // allow notified threads to complete 
  delay();
  assertEquals( "Both objects were removed", 0, objs.size() );
  // There should not be any threads waiting.
  if( thread1.isAlive() || thread2.isAlive() ) {
    fail( "Live thread(s) when both should be dead." );
  }
}

代码示例来源:origin: reactor/reactor-core

@Test
public void testParallelism() throws Exception
{
  Flux<Integer> flux = Flux.just(1, 2, 3);
  Set<String> threadNames = Collections.synchronizedSet(new TreeSet<>());
  AtomicInteger count = new AtomicInteger();
  CountDownLatch latch = new CountDownLatch(3);
  flux
      // Uncomment line below for failure
      .cache(1)
      .parallel(3)
      .runOn(Schedulers.newElastic("TEST"))
      .subscribe(i ->
      {
        threadNames.add(Thread.currentThread()
                   .getName());
        count.incrementAndGet();
        latch.countDown();
        tryToSleep(1000);
      });
  latch.await();
  Assert.assertEquals("Multithreaded count", 3, count.get());
  Assert.assertEquals("Multithreaded threads", 3, threadNames.size());
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testDeploySupplier() throws Exception {
 JsonObject config = generateJSONObject();
 Set<MyVerticle> myVerticles = Collections.synchronizedSet(new HashSet<>());
 Supplier<Verticle> supplier = () -> {
  MyVerticle myVerticle = new MyVerticle();
  myVerticles.add(myVerticle);
  return myVerticle;
 };

代码示例来源:origin: eclipse-vertx/vert.x

Set<HttpConnection> serverConns = new HashSet<>();
server.connectionHandler(conn -> {
 serverConns.add(conn);
 assertTrue(serverConns.size() <= poolSize);
});
  setHttp2MultiplexingLimit(maxConcurrency));
AtomicInteger respCount = new AtomicInteger();
Set<HttpConnection> clientConnections = Collections.synchronizedSet(new HashSet<>());
for (int j = 0;j < rounds;j++) {
 for (int i = 0;i < maxConcurrency;i++) {

代码示例来源:origin: eclipse-vertx/vert.x

});
startServer();
Set<Context> contexts = Collections.synchronizedSet(new HashSet<>());
Set<HttpConnection> connections = Collections.synchronizedSet(new HashSet<>());
Handler<AsyncResult<HttpClientResponse>> checker = onSuccess(response -> {
 contexts.add(Vertx.currentContext());
 connections.add(response.request().connection());
});
HttpClientRequest req1 = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/2", checker)

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testReceivingGoAwayDiscardsTheConnection() throws Exception {
 AtomicInteger reqCount = new AtomicInteger();
 Set<HttpConnection> connections = Collections.synchronizedSet(new HashSet<>());
 server.requestHandler(req -> {
  connections.add(req.connection());
  switch (reqCount.getAndIncrement()) {
   case 0:

代码示例来源:origin: apache/ignite

final Set<Long> resSet = Collections.synchronizedSet(new HashSet<Long>());
  resSet.add(val);
  resSet.add(val);

代码示例来源:origin: wildfly/wildfly

ROOT_LOGGER.debugf(e, "Not installing optional component %s due to an exception", componentDescription.getComponentName());
      failed.add(componentDescription.getStartServiceName());
      failed.add(componentDescription.getCreateServiceName());
      failed.add(componentDescription.getServiceName());
      iterator.remove();
    } else {
deploymentUnit.putAttachment(Attachments.FAILED_COMPONENTS, Collections.synchronizedSet(failed));

相关文章

微信公众号

最新文章

更多

Collections类方法