Example usage for java.util.concurrent CountDownLatch await

List of usage examples for java.util.concurrent CountDownLatch await

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch await.

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

From source file:com.mobius.software.mqtt.performance.runner.ScenarioRunner.java

public void start() throws InterruptedException {
    List<RequestWorker> workers = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(requests.size());
    for (ScenarioRequest request : requests)
        workers.add(new RequestWorker(request, latch));

    ExecutorService service = Executors.newFixedThreadPool(workers.size());
    for (RequestWorker worker : workers)
        service.submit(worker);/*from  w  w w .  j  a  va  2s.c  o  m*/
    latch.await();

    service.shutdownNow();
}

From source file:com.dianping.apistatic.Job.MovieShowDetailCrawlerJob.java

@Override
protected void execute() throws Exception {
    List<Integer> movieShowIds = readIntListFromFile(Constants.MOVIESHOWIDS_PATH);
    if (CollectionUtils.isEmpty(movieShowIds)) {
        log("movieShowIds?", new RuntimeException("movieShowIds "));
        return;/* ww  w.j  av a2  s  . co  m*/
    }

    int partitionSize = (movieShowIds.size() > 5 ? movieShowIds.size() / 5 : movieShowIds.size());
    List<List<Integer>> movieShowIdsList = Lists.partition(movieShowIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(movieShowIdsList.size());

    for (List<Integer> list : movieShowIdsList) {
        MovieShowCrawlerThread thread = new MovieShowCrawlerThread(list, countDownLatch);
        thread.start();
    }
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("CountDownLatch InterruptedException", e);
    }
}

From source file:com.dianping.apistatic.Job.SeatingplanCrawlerJob.java

@Override
protected void execute() throws Exception {
    List<Integer> movieShowIds = readIntListFromFile(Constants.MOVIESHOWIDS_PATH);
    if (CollectionUtils.isEmpty(movieShowIds)) {
        log("movieShowIds?", new RuntimeException("movieShowIds "));
        return;/*  w  ww.  j av  a2s . c om*/
    }

    int partitionSize = (movieShowIds.size() > 5 ? movieShowIds.size() / 5 : movieShowIds.size());
    List<List<Integer>> movieShowIdsList = Lists.partition(movieShowIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(movieShowIdsList.size());
    for (List<Integer> list : movieShowIdsList) {
        SeatingPlanCrawlerThread thread = new SeatingPlanCrawlerThread(list, countDownLatch);
        thread.start();
    }
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("CountDownLatch InterruptedException", e);
    }
}

From source file:com.alibaba.druid.DBCPTest.java

public void test_max() throws Exception {
    Class.forName("com.alibaba.druid.mock.MockDriver");

    final BasicDataSource dataSource = new BasicDataSource();
    //        final DruidDataSource dataSource = new DruidDataSource();
    dataSource.setInitialSize(3);/*from w  ww. ja  va  2 s .  co  m*/
    dataSource.setMaxActive(20);
    dataSource.setMaxIdle(20);
    dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver");
    dataSource.setUrl("jdbc:mock:xxx");

    final int THREAD_COUNT = 200;
    final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
    final CountDownLatch startLatch = new CountDownLatch(1);
    Thread[] threads = new Thread[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i) {
        threads[i] = new Thread() {

            public void run() {
                try {
                    startLatch.await();
                    for (int i = 0; i < 1000; ++i) {
                        Connection conn = dataSource.getConnection();
                        Thread.sleep(1);
                        conn.close();
                    }
                } catch (Exception e) {
                } finally {
                    endLatch.countDown();
                }
            }
        };
        threads[i].start();
    }

    startLatch.countDown();

    endLatch.await();

    //        System.out.println(dataSource.getNumIdle());
    System.out.println(MockDriver.instance.getConnections().size());
    System.out.println(MockDriver.instance.getConnectionCloseCount());
}

From source file:com.alibaba.simpleimage.ColorQuantPerfTest.java

public void start() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(times);
    File rootDir = new File(new File(appDir), "/src/test/resources/conf.test/simpleimage");

    for (int s = 0; s < threadsNum; s++) {
        Thread t = new Thread(new Worker(latch, rootDir, algName));
        t.start();//w w w  .  j  a va 2  s  .c  om
    }

    latch.await();
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException {
    firstStep = newPipelineWithResponseBody("{id:123}");

    // use a synchronized set to collect the pipeline output from multiple threads
    Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDown = new CountDownLatch(100);
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();
            distinctOutputs.add(firstStep.getOutput().toBlocking().single());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });/*from w  w w .j a  va  2 s. c om*/

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output
    assertEquals(1, distinctOutputs.size());
    JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(),
            JSONCompareMode.STRICT);
}

From source file:com.dianping.apistatic.Job.MovieShowBlockListCrawlerJob.java

@Override
protected void execute() throws Exception {
    movieShowIds.clear();/*from w  w  w  .  ja  v a 2 s. co  m*/
    shopIdMap = readMapFromFile(Constants.SHOPIDMAP_PATH); // key cityid
    movieIdMap = readMapFromFile(Constants.MOVIEIDMAP_PATH); // key cityid

    if (MapUtils.isEmpty(shopIdMap) || MapUtils.isEmpty(movieIdMap)) {
        log("shopIdMapmovieIdMap", new RuntimeException("shopIdMapmovieIdMap"));
        return;
    }

    List<Integer> cityIds = getCityIds();
    if (CollectionUtils.isEmpty(cityIds)) {
        return;
    }

    int partitionSize = (cityIds.size() > 4 ? cityIds.size() / 4 : cityIds.size());
    List<List<Integer>> cityIdsList = Lists.partition(cityIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(cityIdsList.size());

    for (List<Integer> list : cityIdsList) {
        MovieShowBlockCrawlerThread thread = new MovieShowBlockCrawlerThread(list, countDownLatch);
        thread.start();
    }

    try {
        countDownLatch.await();
    } catch (Exception e) {
        log("countDownLatch ", e);
        return;
    }

    if (CollectionUtils.isNotEmpty(movieShowIds)) {
        writeObjectAsJsonToFile(Constants.MOVIESHOWIDS_PATH, movieShowIds);
    }
}

From source file:hudson.plugins.mercurial.MercurialContainer.java

@SuppressWarnings("deprecation")
public Slave createSlave(JenkinsRule r) throws Exception {
    DumbSlave slave = new DumbSlave("slave" + r.jenkins.getNodes().size(), "dummy", "/home/test/slave", "1",
            Node.Mode.NORMAL, "mercurial", new SSHLauncher(ipBound(22), port(22), "test", "test", "", ""),
            RetentionStrategy.INSTANCE, Collections.<NodeProperty<?>>emptyList());
    r.jenkins.addNode(slave);//ww  w .  j  av  a  2  s .c o m
    // Copied from JenkinsRule:
    final CountDownLatch latch = new CountDownLatch(1);
    ComputerListener waiter = new ComputerListener() {
        @Override
        public void onOnline(Computer C, TaskListener t) {
            latch.countDown();
            unregister();
        }
    };
    waiter.register();
    latch.await();
    return slave;
}

From source file:org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException {
    if (!(request instanceof UpdateRequest)) {
        return super.request(request);
    }/*from  www  . j  ava  2s  . co  m*/
    UpdateRequest req = (UpdateRequest) request;

    // this happens for commit...
    if (req.getDocuments() == null || req.getDocuments().isEmpty()) {
        blockUntilFinished();
        return super.request(request);
    }

    SolrParams params = req.getParams();
    if (params != null) {
        // check if it is waiting for the searcher
        if (params.getBool(UpdateParams.WAIT_SEARCHER, false)) {
            log.info("blocking for commit/optimize");
            blockUntilFinished(); // empty the queue
            return super.request(request);
        }
    }

    try {
        CountDownLatch tmpLock = lock;
        if (tmpLock != null) {
            tmpLock.await();
        }

        boolean success = queue.offer(req);

        for (;;) {
            synchronized (runners) {
                if (runners.isEmpty() || (queue.remainingCapacity() < queue.size() // queue is half full and we can add more runners
                        && runners.size() < threadCount)) {
                    // We need more runners, so start a new one.
                    Runner r = new Runner();
                    runners.add(r);
                    scheduler.execute(r);
                } else {
                    // break out of the retry loop if we added the element to the queue successfully, *and*
                    // while we are still holding the runners lock to prevent race conditions.
                    // race conditions.
                    if (success)
                        break;
                }
            }

            // Retry to add to the queue w/o the runners lock held (else we risk temporary deadlock)
            // This retry could also fail because
            // 1) existing runners were not able to take off any new elements in the queue
            // 2) the queue was filled back up since our last try
            // If we succeed, the queue may have been completely emptied, and all runners stopped.
            // In all cases, we should loop back to the top to see if we need to start more runners.
            //
            if (!success) {
                success = queue.offer(req, 100, TimeUnit.MILLISECONDS);
            }

        }

    } catch (InterruptedException e) {
        log.error("interrupted", e);
        throw new IOException(e.getLocalizedMessage());
    }

    // RETURN A DUMMY result
    NamedList<Object> dummy = new NamedList<Object>();
    dummy.add("NOTE", "the request is processed in a background stream");
    return dummy;
}

From source file:thingynet.cache.CacheClientService.java

void waitForCachePut(CacheClient client) throws InterruptedException {
    rwl.writeLock().lock();/*from   w ww  .j  a  v a 2  s.  c  o m*/
    CountDownLatch latch = latches.get(client.getCacheKey());
    if (latch == null) {
        latch = new CountDownLatch(1);
        latches.put(client.getCacheKey(), latch);
        // TODO fix            workflowService.createReadyNow("CachePut", client.getCachePutNode().getName(), client.getCachePutContext());
    }
    rwl.writeLock().unlock();
    latch.await();
}