Example usage for java.util.concurrent CountDownLatch countDown

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

Introduction

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

Prototype

public void countDown() 

Source Link

Document

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Usage

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.
 *///ww  w.ja  v a  2 s.com
@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:io.fabric8.msg.jnatsd.TestConnect.java

@Test
public void testConnect() throws Exception {
    Connection subConnection = connectionFactory.createConnection();
    final int count = 1000;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = subConnection.subscribe("foo", new MessageHandler() {
        @Override/*from  www. j  a  v  a 2  s. c o m*/
        public void onMessage(Message message) {
            countDownLatch.countDown();
            //System.out.println("GOT " + message);
        }
    });

    Connection pubConnection = new ConnectionFactory().createConnection();

    for (int i = 0; i < count; i++) {
        String test = "Test" + i;
        pubConnection.publish("foo", "bah", test.getBytes());
    }

    countDownLatch.await(2, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    pubConnection.close();
    subConnection.close();
}

From source file:com.vmware.photon.controller.api.client.resource.AuthApiTest.java

@Test
public void testGetAuthStatusAsync() throws IOException, InterruptedException {
    final Auth auth = new Auth();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(auth);

    setupMocks(serialized, HttpStatus.SC_OK);

    AuthApi authApi = new AuthApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    authApi.getAuthStatusAsync(new FutureCallback<Auth>() {
        @Override/*from   w  w  w  .ja v  a  2  s.  com*/
        public void onSuccess(@Nullable Auth result) {
            assertEquals(result, auth);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });
}

From source file:com.vmware.photon.controller.api.client.resource.AuthRestApiTest.java

@Test
public void testGetAuthStatusAsync() throws IOException, InterruptedException {
    final Auth auth = new Auth();

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(auth);

    setupMocks(serialized, HttpStatus.SC_OK);

    AuthApi authApi = new AuthRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    authApi.getAuthStatusAsync(new FutureCallback<Auth>() {
        @Override//from  ww  w  .ja v  a 2 s .  co  m
        public void onSuccess(@Nullable Auth result) {
            assertEquals(result, auth);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });
}

From source file:com.liferay.mobile.android.async.GroupServiceAsyncTest.java

@Test
public void getUserSites() throws Exception {
    Session session = new SessionImpl(this.session);

    final JSONArray[] sites = { null };
    final CountDownLatch lock = new CountDownLatch(1);

    session.setCallback(new JSONArrayCallback() {

        @Override//  w  ww. ja  va  2 s .  c  o m
        public void onSuccess(JSONArray result) {
            try {
                sites[0] = result;
                lock.countDown();
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    GroupService service = new GroupService(session);
    service.getUserSitesGroups();

    lock.await(500, TimeUnit.MILLISECONDS);
    GroupServiceTest.assertUserSites(sites[0]);
}

From source file:com.couchbase.client.internal.HttpFutureTest.java

@Test
public void testCancellation() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    long timeout = 1000;
    HttpFuture<CancellableOperation> future = new HttpFuture<CancellableOperation>(latch, timeout);
    HttpOperation op = new CancellableOperation();
    latch.countDown();
    future.setOperation(op);/*  w  w  w .ja va  2 s  . c om*/
    future.cancel(true);
    try {
        future.get();
        assertTrue("Future did not throw ExecutionException", false);
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof CancellationException);
        assertEquals("Cancelled", e.getCause().getMessage());
    } catch (Exception e) {
        assertTrue(e.getMessage(), false);
    }

}

From source file:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java

private Callable createQueryRunnable(DataSource dataSource, CountDownLatch countDownLatch) {
    return () -> {
        // open new connection
        try (Connection connection = dataSource.getConnection()) {
            // wait till all the other connections get opened
            countDownLatch.countDown();
            countDownLatch.await(1, MINUTES);

            //check that connection is alive
            checkThatConnectionAlive(connection);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }/* w  ww .  j  ava2 s  .c  o  m*/
        return null;
    };
}

From source file:com.liferay.mobile.android.async.FileUploadAsyncTest.java

@Test
public void uploadPhoto() throws Exception {
    Session session = new SessionImpl(this.session);
    DLAppService service = new DLAppService(session);

    long repositoryId = props.getGroupId();
    long folderId = DLAppServiceTest.PARENT_FOLDER_ID;

    InputStream is = getClass().getResourceAsStream("/" + FileUploadTest.FILE_NAME);

    final int[] size = { 0 };

    FileProgressCallback callback = new FileProgressCallback() {

        @Override//from w w  w  .  jav a 2 s .  c o  m
        public void onProgress(int totalBytes) {
            size[0] = totalBytes;
        }

    };

    UploadData data = new UploadData(is, FileUploadTest.MIME_TYPE, FileUploadTest.FILE_NAME, callback);

    final CountDownLatch lock = new CountDownLatch(1);

    session.setCallback(new JSONObjectCallback() {

        @Override
        public void onSuccess(JSONObject file) {
            _file = file;
            lock.countDown();
        }

        @Override
        public void onFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    service.addFileEntry(repositoryId, folderId, FileUploadTest.FILE_NAME, FileUploadTest.MIME_TYPE,
            FileUploadTest.FILE_NAME, "", "", data, null);

    lock.await(500, TimeUnit.MILLISECONDS);

    assertEquals(FileUploadTest.FILE_NAME, _file.get(DLAppServiceTest.TITLE));

    assertEquals(372434, size[0]);
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * Helper function./*from   w w w .j  av  a 2  s  .  c  o  m*/
 *
 * @param threads
 * @param cpds
 * @param workDelay
 * @param doPreparedStatement 
 * @return time taken
 * @throws InterruptedException
 */
public static long startThreadTest(int threads, DataSource cpds, int workDelay, boolean doPreparedStatement)
        throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(threads);

    ExecutorService pool = Executors.newFixedThreadPool(threads);
    ExecutorCompletionService<Long> ecs = new ExecutorCompletionService<Long>(pool);
    for (int i = 0; i <= threads; i++) { // create and start threads
        ecs.submit(new ThreadTesterUtil(startSignal, doneSignal, cpds, workDelay, doPreparedStatement));
    }

    startSignal.countDown(); // START TEST!
    doneSignal.await();
    long time = 0;
    for (int i = 0; i <= threads; i++) {
        try {
            time = time + ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    pool.shutdown();
    return time;
}