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:io.fabric8.msg.jnatsd.JNatsd.java

public void stop() throws Exception {
    if (started.compareAndSet(true, false)) {
        pingPong.stop();/* ww  w .java  2 s  .  com*/
        final CountDownLatch countDownLatch = new CountDownLatch(servers.size());

        for (JNatsClient client : clients) {
            client.close();
        }

        for (NetServer server : servers) {
            server.close(handler -> {
                countDownLatch.countDown();
            });
        }
        countDownLatch.await(5, TimeUnit.SECONDS);
        LOG.info("JNatsd shutdown");
    }
}

From source file:com.ericsson.gerrit.plugins.highavailability.index.AbstractIndexForwardingIT.java

@Test
@UseLocalDisk/*  w  ww.  j ava2 s  . com*/
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void testIndexForwarding() throws Exception {
    String expectedRequest = getExpectedRequest();
    CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(expectedRequest)) {
            expectedRequestLatch.countDown();
        }
    });
    givenThat(post(urlEqualTo(expectedRequest)).willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT)));
    doAction();
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(expectedRequest)));
}

From source file:com.github.mrstampy.gameboot.otp.netty.OtpNettyTest.java

private void createClearChannel() throws InterruptedException {
    CountDownLatch cdl = new CountDownLatch(1);
    clientHandler.setResponseLatch(cdl);

    ChannelFuture cf = clearClient.connect(HOST, CLEAR_SERVER_PORT);
    cdl.await(5, TimeUnit.SECONDS);

    assertTrue(cf.isSuccess());//from   w  ww  .ja  v  a  2s . c  om
    clearChannel = cf.channel();

    assertNotNull(clientHandler.getSystemId());
    assertEquals(clearChannel, clientHandler.getClearChannel());
}

From source file:org.eclipse.hono.adapter.VertxBasedAdapterApplication.java

public void shutdown(final long maxWaitTime, final Handler<Boolean> shutdownHandler) {

    try {// w  w  w.  j a  v  a 2  s.  c  om
        final CountDownLatch latch = new CountDownLatch(1);
        if (vertx != null) {
            vertx.close(r -> {
                if (r.failed()) {
                    LOG.error("could not shut down '{}' adapter cleanly", this.getName(), r.cause());
                }
                latch.countDown();
            });
        }
        if (latch.await(maxWaitTime, TimeUnit.SECONDS)) {
            LOG.info("'{}' adapter shut down completed", this.getName());
            shutdownHandler.handle(Boolean.TRUE);
        } else {
            LOG.error("shut down of '{}' adapter timed out, aborting...", this.getName());
            shutdownHandler.handle(Boolean.FALSE);
        }
    } catch (InterruptedException e) {
        LOG.error("shut down of '{}' adapter has been interrupted, aborting...", this.getName());
        Thread.currentThread().interrupt();
        shutdownHandler.handle(Boolean.FALSE);
    }
}

From source file:org.elasticsearch.client.documentation.StoredScriptsDocumentationIT.java

public void testDeleteStoredScript() throws Exception {
    RestHighLevelClient client = highLevelClient();

    final StoredScriptSource scriptSource = new StoredScriptSource("painless",
            "Math.log(_score * 2) + params.my_modifier",
            Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()));

    putStoredScript("calculate-score", scriptSource);

    // tag::delete-stored-script-request
    DeleteStoredScriptRequest deleteRequest = new DeleteStoredScriptRequest("calculate-score"); // <1>
    // end::delete-stored-script-request

    // tag::delete-stored-script-request-masterTimeout
    deleteRequest.masterNodeTimeout(TimeValue.timeValueSeconds(50)); // <1>
    deleteRequest.masterNodeTimeout("50s"); // <2>
    // end::delete-stored-script-request-masterTimeout

    // tag::delete-stored-script-request-timeout
    deleteRequest.timeout(TimeValue.timeValueSeconds(60)); // <1>
    deleteRequest.timeout("60s"); // <2>
    // end::delete-stored-script-request-timeout

    // tag::delete-stored-script-execute
    DeleteStoredScriptResponse deleteResponse = client.deleteScript(deleteRequest, RequestOptions.DEFAULT);
    // end::delete-stored-script-execute

    // tag::delete-stored-script-response
    boolean acknowledged = deleteResponse.isAcknowledged();// <1>
    // end::delete-stored-script-response

    putStoredScript("calculate-score", scriptSource);

    // tag::delete-stored-script-execute-listener
    ActionListener<DeleteStoredScriptResponse> listener = new ActionListener<DeleteStoredScriptResponse>() {
        @Override//from ww  w  .j  a va 2  s  .c o m
        public void onResponse(DeleteStoredScriptResponse response) {
            // <1>
        }

        @Override
        public void onFailure(Exception e) {
            // <2>
        }
    };
    // end::delete-stored-script-execute-listener

    // Replace the empty listener by a blocking listener in test
    final CountDownLatch latch = new CountDownLatch(1);
    listener = new LatchedActionListener<>(listener, latch);

    // tag::delete-stored-script-execute-async
    client.deleteScriptAsync(deleteRequest, RequestOptions.DEFAULT, listener); // <1>
    // end::delete-stored-script-execute-async

    assertTrue(latch.await(30L, TimeUnit.SECONDS));
}

From source file:com.mgmtp.perfload.core.console.LtConsole.java

private void awaitLatch(final CountDownLatch latch, final String message)
        throws InterruptedException, TimeoutException {
    if (!latch.await(2L, TimeUnit.MINUTES)) {
        throw new TimeoutException(message);
    }/*  www . jav  a  2  s .  c  om*/
}

From source file:example.springdata.cassandra.basic.CassandraOperationsIntegrationTests.java

/**
 * Asynchronous query execution using callbacks.
 *//*from w  w  w.  ja v  a 2  s. c om*/
@Test
public void insertAsynchronously() throws InterruptedException {

    User user = new User();
    user.setId(42L);
    user.setUsername("heisenberg");
    user.setFirstname("Walter");
    user.setLastname("White");

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    template.insertAsynchronously(user, new WriteListener<User>() {

        @Override
        public void onWriteComplete(Collection<User> entities) {
            countDownLatch.countDown();
        }

        @Override
        public void onException(Exception x) {
        }
    });

    countDownLatch.await(5, TimeUnit.SECONDS);

    User loaded = template.selectOneById(User.class, user.getId());
    assertThat(loaded, is(equalTo(user)));
}

From source file:org.elasticsearch.client.documentation.StoredScriptsDocumentationIT.java

public void testGetStoredScript() throws Exception {
    RestHighLevelClient client = highLevelClient();

    final StoredScriptSource scriptSource = new StoredScriptSource("painless",
            "Math.log(_score * 2) + params.my_modifier",
            Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()));

    putStoredScript("calculate-score", scriptSource);

    {/*w  ww  .j  a v  a  2 s.co  m*/
        // tag::get-stored-script-request
        GetStoredScriptRequest request = new GetStoredScriptRequest("calculate-score"); // <1>
        // end::get-stored-script-request

        // tag::get-stored-script-request-masterTimeout
        request.masterNodeTimeout(TimeValue.timeValueSeconds(50)); // <1>
        request.masterNodeTimeout("50s"); // <2>
        // end::get-stored-script-request-masterTimeout

        // tag::get-stored-script-execute
        GetStoredScriptResponse getResponse = client.getScript(request, RequestOptions.DEFAULT);
        // end::get-stored-script-execute

        // tag::get-stored-script-response
        StoredScriptSource storedScriptSource = getResponse.getSource(); // <1>

        String lang = storedScriptSource.getLang(); // <2>
        String source = storedScriptSource.getSource(); // <3>
        Map<String, String> options = storedScriptSource.getOptions(); // <4>
        // end::get-stored-script-response

        assertThat(storedScriptSource, equalTo(scriptSource));

        // tag::get-stored-script-execute-listener
        ActionListener<GetStoredScriptResponse> listener = new ActionListener<GetStoredScriptResponse>() {
            @Override
            public void onResponse(GetStoredScriptResponse response) {
                // <1>
            }

            @Override
            public void onFailure(Exception e) {
                // <2>
            }
        };
        // end::get-stored-script-execute-listener

        // Replace the empty listener by a blocking listener in test
        final CountDownLatch latch = new CountDownLatch(1);
        listener = new LatchedActionListener<>(listener, latch);

        // tag::get-stored-script-execute-async
        client.getScriptAsync(request, RequestOptions.DEFAULT, listener); // <1>
        // end::get-stored-script-execute-async

        assertTrue(latch.await(30L, TimeUnit.SECONDS));
    }

}

From source file:com.metamx.emitter.core.EmitterTest.java

private void waitForEmission(HttpPostEmitter emitter) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    emitter.getExec().execute(new Runnable() {
        @Override/*w  ww . jav  a2  s  .c  om*/
        public void run() {
            latch.countDown();
        }
    });

    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail("latch await() did not complete in 10 seconds");
    }
}

From source file:io.fabric8.msg.jnatsd.TestLoad.java

@Test
public void testLoad() throws Exception {
    EmbeddedConnection subConnection = new EmbeddedConnection(jNatsd);
    subConnection.start();/*from   w ww  .j ava 2s  . c  o  m*/
    final int count = 1000;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    subConnection.addSubscriber("foo", msg -> {
        countDownLatch.countDown();
    });

    EmbeddedConnection pubConnection = new EmbeddedConnection(jNatsd);
    pubConnection.start();

    long start = System.currentTimeMillis();

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

    countDownLatch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());

    long finish = System.currentTimeMillis();

    long totalTime = finish - start;

    int messagesPerSecond = (int) ((count * 1000) / totalTime);

    System.err.println("Duration to pub/sub " + count + " messages = " + totalTime + " ms = "
            + messagesPerSecond + " msg/sec");
    pubConnection.close();
    subConnection.close();
}