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 boolean await(long timeout, TimeUnit unit) 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 , or the specified waiting time elapses.

Usage

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

@Test
public void testSync() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from w ww . ja  v a 2 s.co  m
    try {
        client.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getType() == CuratorEventType.SYNC) {
                    Assert.assertEquals(event.getPath(), "/head");
                    ((CountDownLatch) event.getContext()).countDown();
                }
            }
        });

        client.create().forPath("/head");
        Assert.assertNotNull(client.checkExists().forPath("/head"));

        CountDownLatch latch = new CountDownLatch(1);
        client.sync("/head", latch);
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    } finally {
        client.close();
    }
}

From source file:com.vmware.photon.controller.rootscheduler.SchedulerDcpHostTest.java

private void waitForServicesStartup(SchedulerDcpHost host)
        throws TimeoutException, InterruptedException, NoSuchFieldException, IllegalAccessException {

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            SchedulerDcpHost.FACTORY_SERVICE_FIELD_NAME_SELF_LINK, SchedulerDcpHost.FACTORY_SERVICES);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = (operation, throwable) -> {
        latch.countDown();/*from   ww  w  .  j a va2  s  . c om*/
    };

    String[] links = new String[serviceSelfLinks.size()];
    host.registerForServiceAvailability(handler, serviceSelfLinks.toArray(links));
    if (!latch.await(10, TimeUnit.SECONDS)) {
        throw new TimeoutException();
    }
}

From source file:com.onyxscheduler.domain.SchedulerIT.java

@Test
public void shouldNotFireJobWithNonReachableFutureDate()
        throws InterruptedException, Scheduler.DuplicateJobKeyException {
    CountDownLatch latch = new CountDownLatch(1);
    latchProvider.setLatch(latch);//from ww w  .  j a  v a2s.com
    CountDownJob job = buildJobWithFixedDateTrigger(buildNonReachableFutureDate());

    scheduler.scheduleJob(job);

    assertThat(latch.await(FIRE_THRESHOLD_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), is(false));
}

From source file:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testDeleteDhcpRelayProfile() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);//w  w w .  j ava 2s . c  o m

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.deleteDhcpRelayProfile("id", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            latch.countDown();
        }

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

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testDeleteDhcpRelayService() throws IOException, InterruptedException {
    setupMocks(null, HttpStatus.SC_OK);/*ww w .  ja  va  2s.co  m*/

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.deleteDhcpRelayService("id", new com.google.common.util.concurrent.FutureCallback<Void>() {
        @Override
        public void onSuccess(Void result) {
            latch.countDown();
        }

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

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:org.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testThatSmallResponsesAreNotEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();//from   w w w .jav  a2 s  .  c o m

    byte[] content = generate(100).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, null));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

From source file:org.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testThatLargeResponsesAreNotEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();// w w w  . ja  v a  2  s .c  o  m

    byte[] content = generate(2000).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, null));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

From source file:org.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testEncodingOfResponse() throws InterruptedException, IOException {
    Router router = prepareServer();/*from  ww w . j a  va 2  s .  c  o m*/

    byte[] content = generate(1000).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, "gzip"));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

From source file:com.supermy.im.mongo.MongoRepository.java

/**
 *
 * @param collectionName/*from  w  w w .  j  av a2s  .c om*/
 * @return
 */
public boolean collectionExists(final String collectionName) {

    MongoIterable colls = mongoDatabase().listCollectionNames();

    List<String> collectionNames = new ArrayList<String>();

    try {
        final CountDownLatch countDownLatch = new CountDownLatch(1);//??

        colls.into(collectionNames, new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                // logger.debug("?");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(collectionNames);
    System.out.println(collectionNames.size());

    for (String name : collectionNames) {
        if (name.equalsIgnoreCase(collectionName)) {
            return true;
        }
    }
    return false;
}

From source file:WorkQueue.java

/**
 * Waits until all the tasks associated with the group identifier have
 * finished.  Once a task group has been successfully waited upon, the group
 * identifier is removed from the queue and is valid to be reused for a new
 * task group.//  w  ww  . j  a va 2  s .  c  o  m
 *
 * @throws IllegalArgumentException if the {@code taskGroupId} is not
 *         currently associated with any active taskGroup
 */
public boolean await(Object taskGroupId, long timeout, TimeUnit unit) {
    CountDownLatch latch = taskKeyToLatch.get(taskGroupId);
    if (latch == null)
        throw new IllegalArgumentException("Unknown task group: " + taskGroupId);
    try {
        if (latch.await(timeout, unit)) {
            // Once finished, remove the key so it can be associated with a
            // new task
            taskKeyToLatch.remove(taskGroupId);
            return true;
        }
        return false;
    } catch (InterruptedException ie) {
        throw new IllegalStateException("Not all tasks finished", ie);
    }
}