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.twitter.hbc.httpclient.BasicClientTest.java

@Test
public void testIOExceptionDuringProcessing() throws Exception {
    ClientBase clientBase = new ClientBase("name", mockClient, new HttpHosts("http://hi"),
            new RawEndpoint("/endpoint", HttpConstants.HTTP_GET), mockAuth, mockProcessor,
            mockReconnectionManager, mockRateTracker);
    BasicClient client = new BasicClient(clientBase, executorService);
    final CountDownLatch latch = new CountDownLatch(1);
    when(mockStatusLine.getStatusCode()).thenReturn(200);

    doNothing().when(mockProcessor).setup(any(InputStream.class));
    doThrow(new IOException()).doThrow(new IOException()).doThrow(new IOException()).doAnswer(new Answer() {
        @Override// w ww  .  j  ava  2 s.co  m
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            latch.countDown();
            return null;
        }
    }).when(mockProcessor).process();

    client.connect();
    latch.await();
    assertFalse(clientBase.isDone());
    verify(mockProcessor, times(4)).setup(any(InputStream.class));
    // throw 3 exceptions, 4th one keeps going
    verify(mockProcessor, atLeast(4)).process();

    client.stop();
    verify(mockConnectionManager, atLeastOnce()).shutdown();
    assertTrue(client.isDone());
    assertEquals(EventType.STOPPED_BY_USER, clientBase.getExitEvent().getEventType());
}

From source file:com.netflix.curator.framework.imps.TestFrameworkBackground.java

@Test
public void testBasic() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {//from w  ww . j  a v  a 2 s  .c o m
        client.start();

        final CountDownLatch latch = new CountDownLatch(3);
        final List<String> paths = Lists.newArrayList();
        BackgroundCallback callback = new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                paths.add(event.getPath());
                latch.countDown();
            }
        };
        client.create().inBackground(callback).forPath("/one");
        client.create().inBackground(callback).forPath("/one/two");
        client.create().inBackground(callback).forPath("/one/two/three");

        latch.await();

        Assert.assertEquals(paths, Arrays.asList("/one", "/one/two", "/one/two/three"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.pikai.jdbc.testcase.PoolTest.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);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[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();
                        conn.close();/* w  ww.  j  ava  2  s  .  co  m*/
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    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 + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

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

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *///from   ww w .java  2 s  . c om
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.count() //
            .doOnSuccess(System.out::println) //
            .toFlowable() //
            .switchMap(count -> repository.saveAll(Flowable.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))) //
            .lastElement() //
            .toSingle() //
            .flatMap(v -> repository.count()) //
            .doOnSuccess(System.out::println) //
            .doAfterTerminate(countDownLatch::countDown) //
            .subscribe();

    countDownLatch.await();
}

From source file:com.microsoft.office.integration.test.ContactsAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeContact();//from   w  w  w  .j  a  v a  2s.  c o m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IContact result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }
            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.alibaba.druid.benckmark.pool.Case1.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);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[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();
                        conn.close();//from w  w  w .  java  2 s . c o  m
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    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 + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

From source file:com.microsoft.office.integration.test.ContactsAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareContact();//from w  w w . j  av a2  s .c o m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(contact.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });

    cdl.await();
}

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

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 *//*from w  w  w .  j a  v a  2s .co  m*/
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    repository.count() //
            .doOnNext(System.out::println) //
            .thenMany(repository.saveAll(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))) //
            .last() //
            .flatMap(v -> repository.count()) //
            .doOnNext(System.out::println) //
            .doOnSuccess(it -> countDownLatch.countDown()) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_interceptors_after_flush_for_batch() throws Exception {
    // Given/*from w w w.j  a v  a 2 s .co m*/
    final AsyncBatch asyncBatch = asyncManager.createBatch();
    asyncBatch.startBatch();

    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    // When
    asyncBatch.insert(entity);

    // Then
    assertThat(entity.getName()).isEqualTo("DuyHai");
    assertThat(entity.getLabel()).isEqualTo("label");

    // When
    final CountDownLatch latch = new CountDownLatch(1);
    asyncBatch.asyncEndBatch(new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {

        }
    });

    latch.await();

    // Then
    assertThat(entity.getName()).isEqualTo("prePersist");

    assertThat(entity.getLabel()).isEqualTo("postPersist : label");
}

From source file:org.kurento.repository.OneRecordingServer.java

private void prepareToUploadVideo(RepositoryItem repositoryItem) throws InterruptedException {

    RepositoryHttpRecorder recorder = repositoryItem.createRepositoryHttpRecorder("video-upload");

    log.info("The video must be uploaded with PUT or POST to the URL: " + recorder.getURL());

    readyToUploadWatch.countDown();//from   www.ja v  a2  s  . c  om

    recorder.setAutoTerminationTimeout(5 * 1000);
    log.info(
            "The recorder will be auto-terminated 5 seconds after the last uploading of content (http PUT or POST)");

    final CountDownLatch terminatedLatch = new CountDownLatch(1);

    recorder.addSessionStartedListener(new RepositoryHttpEventListener<HttpSessionStartedEvent>() {
        @Override
        public void onEvent(HttpSessionStartedEvent event) {
            log.info("Uploading started");
        }
    });

    recorder.addSessionTerminatedListener(new RepositoryHttpEventListener<HttpSessionTerminatedEvent>() {
        @Override
        public void onEvent(HttpSessionTerminatedEvent event) {
            log.info("Uploading terminated");
            terminatedLatch.countDown();
        }
    });

    terminatedLatch.await();
}