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:io.opentracing.contrib.elasticsearch5.TracingTest.java

@Test
public void transportClient() throws Exception {

    Settings settings = Settings.builder().put("cluster.name", clusterName).build();

    TransportClient client = new TracingPreBuiltTransportClient(mockTracer, settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"),
                    Integer.parseInt(HTTP_TRANSPORT_PORT)));

    IndexRequest indexRequest = new IndexRequest("twitter").type("tweet").id("1")
            .source(jsonBuilder().startObject().field("user", "kimchy").field("postDate", new Date())
                    .field("message", "trying out Elasticsearch").endObject());

    IndexResponse indexResponse = client.index(indexRequest).actionGet();
    assertNotNull(indexResponse);//from   www.ja va  2  s . co  m

    final CountDownLatch latch = new CountDownLatch(1);
    client.index(indexRequest, new ActionListener<IndexResponse>() {
        @Override
        public void onResponse(IndexResponse indexResponse) {
            latch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            latch.countDown();
        }
    });

    latch.await(30, TimeUnit.SECONDS);
    client.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "IndexRequest");
    assertNull(mockTracer.activeSpan());
}

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

@PostConstruct
public void registerVerticles() {

    if (running.compareAndSet(false, true)) {
        final int instanceCount = honoConfig.getMaxInstances();

        try {/*from  w  w w .  j  a  v  a2 s .c o m*/
            final CountDownLatch latch = new CountDownLatch(1);
            final Future<Void> startFuture = Future.future();
            startFuture.setHandler(done -> {
                if (done.succeeded()) {
                    latch.countDown();
                } else {
                    LOG.error("could not start '{}' adapter", this.getName(), done.cause());
                }
            });

            deployVerticle(instanceCount, startFuture);

            if (latch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
                LOG.info("'{}' adapter startup completed successfully", this.getName());
            } else {
                LOG.error("startup timed out after {} seconds, shutting down ...",
                        honoConfig.getStartupTimeout());
                shutdown();
            }
        } catch (InterruptedException e) {
            LOG.error("startup process has been interrupted, shutting down ...");
            Thread.currentThread().interrupt();
            shutdown();
        }
    }
}

From source file:com.netflix.curator.framework.recipes.leader.TestLeaderSelectorParticipants.java

@Test
public void testId() throws Exception {
    LeaderSelector selector = null;//from  ww w  . j a  v  a 2  s  . c om
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        LeaderSelectorListener listener = new LeaderSelectorListener() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                latch.countDown();
                Thread.currentThread().join();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        selector = new LeaderSelector(client, "/ls", listener);
        selector.setId("A is A");
        selector.start();

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));

        Participant leader = selector.getLeader();
        Assert.assertTrue(leader.isLeader());
        Assert.assertEquals(leader.getId(), "A is A");

        Collection<Participant> participants = selector.getParticipants();
        Assert.assertEquals(participants.size(), 1);
        Assert.assertEquals(participants.iterator().next().getId(), "A is A");
        Assert.assertEquals(participants.iterator().next().getId(), selector.getId());
    } finally {
        IOUtils.closeQuietly(selector);
        IOUtils.closeQuietly(client);
    }
}

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

private void letOtherTaskFinish(CountDownLatch firstLatch, CountDownLatch secondLatch) {
    firstLatch.countDown();
    try {//from ww w.  j  a v a2s  .  co  m
        secondLatch.await();
    } catch (InterruptedException e) {
        throw Throwables.rewrapAndThrowUncheckedException(e);
    }
}

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 a va  2s .  c om*/

    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);/*from  w w  w  .j  a va 2 s .c  om*/

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

public void stop() throws Exception {
    if (started.compareAndSet(true, false)) {
        pingPong.stop();//  ww w .j  av a2s  . c  o  m
        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.microsoft.office.integration.test.ContactsAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareContact();/*from w w w.  j a  v a2  s  .co  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:hws.util.ZkDataMonitor.java

public ZkClient(String serverAddr, int sessionTimeout) throws IOException, InterruptedException {
    final CountDownLatch connectedSignal = new CountDownLatch(1);
    this.zk = new ZooKeeper(serverAddr, sessionTimeout, new Watcher() {
        @Override//from w  w  w.  j  ava 2 s . c om
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                connectedSignal.countDown();
            }
        }
    });
    connectedSignal.await();
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

@Test
public void testFileChangedCallback() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);

    SdkCredentialsFileContentMonitor monitor = new SdkCredentialsFileContentMonitor(targetFile,
            MONITOR_POLLING_INTERVAL_MILLIS, new FileAlterationListenerAdaptor() {

                @Override//from   ww  w.j a  v a  2  s.c  o m
                public void onFileChange(final File changedFile) {
                    latch.countDown();
                }
            });
    monitor.setDebugMode(true);
    monitor.start();

    touch(targetFile);

    long waitTime = MONITOR_POLLING_INTERVAL_MILLIS * 2;
    Assert.assertTrue("File monitor callback not invoked after waiting for " + waitTime + " ms.",
            latch.await(waitTime, TimeUnit.MILLISECONDS));
}