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.contentful.vaultintegration.BaseTest.java

protected void sync(SyncConfig config) throws InterruptedException {
    if (config == null) {
        config = SyncConfig.builder().setClient(client).build();
    }//from   w  w w .ja v a 2  s  .c  o m

    final CountDownLatch latch = new CountDownLatch(1);

    Executor executor = new Executor() {
        @Override
        public void execute(Runnable command) {
            command.run();
        }
    };

    final SyncResult[] result = { null };
    SyncCallback callback = new SyncCallback() {
        @Override
        public void onResult(SyncResult r) {
            result[0] = r;
            latch.countDown();
        }
    };

    vault.requestSync(config, callback, executor);
    latch.await();

    assertThat(result[0]).isNotNull();

    if (!result[0].isSuccessful()) {
        throw (RuntimeException) result[0].error();
    }
}

From source file:com.brienwheeler.apps.main.ContextMainTest.java

@Test
public void testContextDirect() throws InterruptedException {
    PropertiesTestUtils.clearAllTestSystemProperties();
    System.clearProperty(TestDataConstants.RMAP_TEST_PROP);
    Assert.assertNull(System.getProperty(TestDataConstants.RMAP_TEST_PROP));

    CountDownLatch latch = new CountDownLatch(1);
    TestContextMain main = new TestContextMain(new String[] { C, TestDataConstants.RMAP_CTX_DIRECT }, latch);
    TestRunner testRunner = new TestRunner(main);
    testRunner.start();//from w  w  w .j a va  2  s  .co  m

    latch.await();

    Assert.assertEquals(TestDataConstants.RMAP_TEST_VAL, System.getProperty(TestDataConstants.RMAP_TEST_PROP));
    assertLaunchCount(main, 1);

    main.shutdown();
    testRunner.join();
}

From source file:com.brienwheeler.apps.main.ContextMainTest.java

@Test
public void testContextIndirect() throws InterruptedException {
    PropertiesTestUtils.clearAllTestSystemProperties();
    Assert.assertNull(System.getProperty(TestDataConstants.RMAP_TEST_PROP));

    CountDownLatch latch = new CountDownLatch(1);
    TestContextMain main = new TestContextMain(new String[] { C, TestDataConstants.RMAP_CTX_INDIRECT }, latch);
    TestRunner testRunner = new TestRunner(main);
    testRunner.start();/*from  ww  w .j av  a  2  s. c  o  m*/

    latch.await();

    Assert.assertEquals(TestDataConstants.RMAP_TEST_VAL, System.getProperty(TestDataConstants.RMAP_TEST_PROP));
    assertLaunchCount(main, 1);

    main.shutdown();
    testRunner.join();
}

From source file:com.netflix.curator.framework.recipes.queue.TestQueueSharder.java

private BlockingQueueConsumer<String> makeConsumer(final CountDownLatch latch) {
    ConnectionStateListener connectionStateListener = new ConnectionStateListener() {
        @Override// w w  w.  j a  v  a2 s.co m
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };

    return new BlockingQueueConsumer<String>(connectionStateListener) {
        @Override
        public void consumeMessage(String message) throws Exception {
            if (latch != null) {
                latch.await();
            }
            super.consumeMessage(message);
        }
    };
}

From source file:com.auditbucket.test.functional.TestForceDeadlock.java

/**
 * Multi threaded test that tests to make sure duplicate Doc Types and Headers are not created
 *
 * @throws Exception/*from  w  w w .  jav  a2  s .c  om*/
 */
@Test
public void metaHeaderUnderLoad() throws Exception {
    cleanUpGraph(); // No transaction so need to clear down the graph

    String monowai = "Monowai";
    regService.registerSystemUser(new RegistrationBean(monowai, mike, "bah"));
    SecurityContextHolder.getContext().setAuthentication(authMike);
    Fortress fortress = fortressService.registerFortress("auditTest" + System.currentTimeMillis());
    String docType = "TestAuditX";

    CountDownLatch latch = new CountDownLatch(4);
    ArrayList<TagInputBean> tags = getTags(10);

    Map<Integer, CallerRefRunner> runners = new HashMap<>();
    int threadMax = 15;
    for (int i = 0; i < threadMax; i++) {
        runners.put(i, addRunner(fortress, docType, "ABC" + i, 20, tags, latch));
    }

    latch.await();
    boolean working = false;
    Map<Integer, Future<Integer>> futures = new HashMap<>();
    String apiKey = fortress.getCompany().getApiKey();
    try {
        for (int i = 0; i < threadMax; i++) {
            futures.put(i, trackEP.trackHeadersAsync(runners.get(i).getInputBeans(), true, apiKey));
        }
        working = true;
    } catch (RuntimeException e) {
        logger.error("rte ", e);
    }
    for (int i = 0; i < threadMax; i++) {
        if (futures.get(i) != null) {
            while (!futures.get(i).isDone()) {
                Thread.yield();
            }
            doFutureWorked(futures.get(i), runners.get(i).getMaxRun());
        }
    }
    assertEquals(true, working);
    assertNotNull(tagService.findTag(fortress.getCompany(), tags.get(0).getName(), tags.get(0).getIndex()));

    Map<String, Tag> createdTags = tagService.findTags(fortress.getCompany(), tags.get(0).getIndex());
    assertEquals(false, createdTags.isEmpty());
    assertEquals(10, createdTags.size());
}

From source file:WorkQueue.java

/**
 * Executes the tasks using a thread pool and returns once all tasks have
 * finished./* www  .j  a  v a  2  s. com*/
 *
 * @throws IllegalStateException if interrupted while waiting for the tasks
 *         to finish
 */
public void run(Collection<Runnable> tasks) {
    // Create a semphore that the wrapped runnables will execute
    int numTasks = tasks.size();
    CountDownLatch latch = new CountDownLatch(numTasks);
    for (Runnable r : tasks) {
        workQueue.offer(new CountingRunnable(r, latch));
    }
    try {
        // Wait until all the tasks have finished
        latch.await();
    } catch (InterruptedException ie) {
        throw new IllegalStateException("Not all tasks finished", ie);
    }
}

From source file:com.google.code.fqueue.memcached.TestFqueueServer.java

public void mutiThreadWrite() throws InterruptedException, TimeoutException, MemcachedException {
    int threadCount = 8;
    ExecutorService pool = Executors.newFixedThreadPool(threadCount);
    CountDownLatch latch = new CountDownLatch(threadCount);
    // MemcachedBenchJob.test = tester;
    MemcachedTest[] muti = new MemcachedTest[threadCount];
    for (int i = 0; i < threadCount; i++) {
        muti[i] = new MemcachedTest(latch);
    }//from  ww w  .j  a  va2s  . co  m
    log.info("start");
    long start = System.currentTimeMillis();
    for (int i = 0; i < threadCount; i++) {
        pool.execute(muti[i]);
    }
    latch.await();
    long spend = System.currentTimeMillis() - start;

    log.info(threadCount + "threads:" + threadCount * 10000 + " spend:" + spend + " ms");
    assertEquals(threadCount * 10000, getSize());

}

From source file:com.yahoo.gondola.container.ZookeeperRegistryClientTest.java

private void testGetEntries(RegistryClient writer, RegistryClient reader, boolean remote) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    InetSocketAddress addr = new InetSocketAddress(1234);
    if (remote) {
        reader.addListener(entry -> {
            if (entry.gondolaAddress.equals(addr)) {
                latch.countDown();/*from w  w w.j a va  2 s .co  m*/
            }
        });
    }

    String hostId = writer.register(SITE_1_HOST_3_CLUSTERS, addr, URI.create("https://api1.yahoo.com:4443"));

    if (remote) {
        latch.await();
    }

    List<RegistryClient.Entry> writerEntries = writer.getEntries().entrySet().stream().map(Map.Entry::getValue)
            .filter(e -> e.hostId.equals(hostId)).collect(Collectors.toList());

    assertEquals(writerEntries.size(), 1);

    Map<String, RegistryClient.Entry> readerEntries = reader.getEntries();
    assertEquals(readerEntries.size(), 1);

    for (RegistryClient.Entry e : writerEntries) {
        RegistryClient.Entry readerEntry = readerEntries.get(e.hostId);
        assertEquals(readerEntry.hostId, e.hostId);
        assertEquals(readerEntry.gondolaAddress, e.gondolaAddress);
    }
}

From source file:com.basho.riak.pbc.itest.ITestDataLoad.java

@Test
public void concurrentDataLoad() throws Exception {
    final int NUM_THREADS = 5;
    final int NUM_OBJECTS = 200;

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(NUM_THREADS);

    final Thread[] threads = new Thread[NUM_THREADS];
    final AtomicInteger idx = new AtomicInteger(0);

    final RiakClient riak = new RiakClient(RIAK_HOST, RIAK_PORT);

    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new Runnable() {

            public void run() {
                try {
                    startLatch.await();

                    Random rnd = new Random();
                    for (int i = 0; i < NUM_OBJECTS / NUM_THREADS; i++) {
                        String key = "data-load-" + idx.getAndIncrement();
                        String value = CharsetUtils.asString(data[rnd.nextInt(NUM_VALUES)],
                                CharsetUtils.ISO_8859_1);
                        RiakObject[] objects = riak.fetch(BUCKET, key);
                        RiakObject o = null;
                        if (objects.length == 0) {
                            o = new RiakObject(BUCKET, key, value);
                        } else {
                            o = new RiakObject(objects[0].getVclock(), objects[0].getBucketBS(),
                                    objects[0].getKeyBS(), copyFromUtf8(value));
                        }/*from   w w  w  . j av a 2 s .  c  o  m*/

                        RiakObject result = riak.store(o, new RequestMeta().w(2).returnBody(true))[0];
                        assertEquals(o.getBucket(), result.getBucket());
                        assertEquals(o.getKey(), result.getKey());
                        assertEquals(o.getValue(), result.getValue());
                    }
                    endLatch.countDown();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
        threads[i].start();
    }

    startLatch.countDown();

    endLatch.await();
}

From source file:com.ekumen.tangobot.application.MainActivity.java

/**
 * Helper method to block the calling thread until the latch is zeroed by some other task.
 * @param latch Latch to wait for.//from www . j  av  a 2  s  .c o  m
 * @param latchName Name to be used in log messages for the given latch.
 */
private void waitForLatchUnlock(CountDownLatch latch, String latchName) {
    try {
        mLog.info("Waiting for " + latchName + " latch release...");
        latch.await();
        mLog.info(latchName + " latch released!");
    } catch (InterruptedException ie) {
        mLog.warn("Warning: continuing before " + latchName + " latch was released");
    }
}