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.netflix.curator.framework.recipes.queue.TestDistributedIdQueue.java

@Test
public void testDeletingWithLock() throws Exception {
    DistributedIdQueue<TestQueueItem> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();// ww w . j  av a2s.  c  o m
    try {
        final CountDownLatch consumingLatch = new CountDownLatch(1);
        final CountDownLatch waitLatch = new CountDownLatch(1);
        QueueConsumer<TestQueueItem> consumer = new QueueConsumer<TestQueueItem>() {
            @Override
            public void consumeMessage(TestQueueItem message) throws Exception {
                consumingLatch.countDown();
                waitLatch.await();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks")
                .buildIdQueue();
        queue.start();

        queue.put(new TestQueueItem("test"), "id");

        Assert.assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it
        Assert.assertEquals(queue.remove("id"), 0);

        waitLatch.countDown();
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.palantir.atlasdb.schema.stream.StreamTest.java

private void letOtherTaskFinish(CountDownLatch firstLatch, CountDownLatch secondLatch) {
    firstLatch.countDown();// www.ja v a  2  s  .c  om
    try {
        secondLatch.await();
    } catch (InterruptedException e) {
        throw Throwables.rewrapAndThrowUncheckedException(e);
    }
}

From source file:example.springdata.cassandra.people.ReactivePersonRepositoryIntegrationTest.java

/**
 * Result set {@link com.datastax.driver.core.Row}s are converted to entities as they are emitted. Reactive pull and
 * prefetch define the amount of fetched records.
 *//*from   w  ww  .  ja v  a2  s .  co m*/
@Test
public void shouldPerformConversionBeforeResultProcessing() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.findAll() //
            .doOnNext(System.out::println) //
            .doOnComplete(countDownLatch::countDown) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:ufo.remote.calls.benchmark.client.caller.resttemplate.AsyncRestTemplateTester.java

@Override
protected void startTest(final TesterResult result) {

    String url = "http://" + hostname + ":" + port + path;

    CountDownLatch latch = new CountDownLatch(result.totalCalls);
    AtomicInteger failures = new AtomicInteger(0);
    Executor executor = Executors.newFixedThreadPool(10);
    for (int i = 0; i < result.totalCalls; i++) {
        executor.execute(new Caller(url, result.message, latch, failures));
    }//from  w ww .  j  ava  2 s  .co m

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();
}

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

@Test
public void subscribeConcurrentlyToTransformedPipelineOutputs() throws InterruptedException {

    // this test verifies that pipelines actions are only executed once, even if there are multiple concurrent subscribers
    firstStep = newPipelineWithResponseBody("{id:123}");
    secondStep = firstStep.applyAction(action);
    when(action.execute(any(), any())).thenReturn(firstStep.getOutput());

    // 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
    CountDownLatch countDown = new CountDownLatch(100);
    ExecutorService executorService = Executors.newCachedThreadPool();
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();
            secondStep.getOutput().subscribe(Subscribers.empty());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });//from w ww . ja  v a2  s  .c  o m

        countDown.countDown();
    }

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

    verify(action, times(1)).execute(any(), any());
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.data.KratuProcessor.java

public void processKratus(Long topAccountId, Date dateStart, Date dateEnd) throws InterruptedException {
    System.out.println("Processing Kratus for" + topAccountId);

    // We use a Latch so the main thread knows when all the worker threads are complete.
    final CountDownLatch latch = new CountDownLatch(1);
    Stopwatch stopwatch = Stopwatch.createStarted();

    RunnableKratu runnableKratu = createRunnableKratu(topAccountId, storageHelper, dateStart, dateEnd);

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    runnableKratu.setLatch(latch);//  ww w .  j a  va  2s  .c o m
    executorService.execute(runnableKratu);

    latch.await();
    stopwatch.stop();
}

From source file:example.springdata.cassandra.people.RxJava2PersonRepositoryIntegrationTest.java

/**
 * Result set {@link com.datastax.driver.core.Row}s are converted to entities as they are emitted. Reactive pull and
 * prefetch define the amount of fetched records.
 */// w  w w.  j a v a2s  .  c  o m
@Test
public void shouldPerformConversionBeforeResultProcessing() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.findAll() //
            .doOnNext(System.out::println) //
            .doOnEach(it -> countDownLatch.countDown()) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:com.perfect.autosdk.core.JsonProxy.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String addr = service.serverUrl + AddressUtil.getJsonAddr(interfaces) + '/' + method.getName();

    JsonConnection conn = new GZIPJsonConnection(addr);
    conn.setConnectTimeout(service.connectTimeoutMills);
    conn.setReadTimeout(service.readTimeoutMills);
    JsonEnvelop request = makeRequest(args[0]);
    conn.sendRequest(request);/*from www  .  j  a  va2 s.c  o m*/
    JsonEnvelop<ResHeader, ?> response = conn.readResponse(ResHeader.class, method.getReturnType());
    ResHeader resHeader = response.getHeader();
    if (!resHeader.getFailures().isEmpty()) {
        if (log.isErrorEnabled()) {
            log.error("Call Error: Head info = " + resHeader + "\n" + "account info = " + service.getUsername()
                    + "\n" + "request info = " + addr + "\n" + "request param = " + args[0]);
        }
        if (resHeader.getFailures().get(0).getCode() == 8904) {
            Timer timer = new Timer("waitLock");
            final CountDownLatch latch = new CountDownLatch(1);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("waiting....");
                    latch.countDown();
                }
            }, 15000);

            latch.await();
        }
    }
    ResHeaderUtil.resHeader.set(response.getHeader());
    BaiduApiQuota.setQuota(service.username, response.getHeader().getQuota());
    return response.getBody();
}

From source file:com.spotify.ffwd.AgentCore.java

private void waitUntilStopped(final Injector primary) throws InterruptedException {
    final CountDownLatch shutdown = new CountDownLatch(1);
    Runtime.getRuntime().addShutdownHook(setupShutdownHook(primary, shutdown));
    shutdown.await();
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case3.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

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

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");
                        rs.next();// w w w .j  a  v  a  2s  . co  m
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}