Example usage for java.util.concurrent CountDownLatch CountDownLatch

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

Introduction

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

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

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

public void testRead() {
    // create message first
    prepareMessage();//w  w  w  .j a va2  s.c  o  m
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                try {
                    readAndCheck();
                } finally {
                    // clean-up
                    removeMessage();
                }
            } catch (Exception e) {
                reportError(e);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testRead() timed out");
        }
    } catch (InterruptedException e) {
        fail("testRead() has been interrupted");
    }
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

@Before
public void loadEnv() {
    latch = new CountDownLatch(msgs * threads);
    threadPool = Executors.newCachedThreadPool();
}

From source file:com.imagesleuth.imagesleuthclient2.Getter.java

public void get(final String id, final File result)
        throws InterruptedException, IOException, URISyntaxException {

    Test.testNull(id);//from   w  w w . j a  va  2  s.com
    Test.testNull(result);
    final CountDownLatch latch = new CountDownLatch(1);

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultHeaders(harray)
            .setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(requestConfig).build()) {
        httpclient.start();
        URIBuilder builder = new URIBuilder();
        if (url.startsWith("https://")) {
            String baseURL = url.substring(8);
            builder.setScheme("https").setHost(baseURL).setPath("/api/v1/results").setParameter("id", id);
        } else if (url.startsWith("http://")) {
            String baseURL = url.substring(7);
            builder.setScheme("http").setHost(baseURL).setPath("/api/v1/results").setParameter("id", id);
        } else {
            builder.setScheme("http").setHost(url).setPath("/api/v1/results").setParameter("id", id);
        }
        URI uri = builder.build();
        final HttpGet request = new HttpGet(uri);
        httpclient.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {

                int code = response.getStatusLine().getStatusCode();
                latch.countDown();
                if (code == 200) {
                    if (response.getEntity() != null) {
                        StringWriter writer = new StringWriter();
                        try {
                            IOUtils.copy(response.getEntity().getContent(), writer);
                            //System.out.println("result: " + writer.toString());
                            JsonNode json = mapper.readTree(writer.toString());
                            String s = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
                            try (FileWriter fw = new FileWriter(result)) {
                                fw.write(s);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void failed(final Exception ex) {
                latch.countDown();
                System.out.println(request.getRequestLine() + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch.countDown();
                System.out.println(request.getRequestLine() + " cancelled");
            }

        });
        latch.await();
    }
    //System.out.println("Shutting down");
}

From source file:es.us.lsi.restest.engine.UnirestTest.java

@Before
public void setUp() {
    lock = new CountDownLatch(1);
    status = false;
}

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

@Test
public void testGetClusterAsync() throws IOException, InterruptedException {
    final Cluster cluster = new Cluster();
    cluster.setName("clusterName");
    cluster.setState(ClusterState.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(cluster);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getClusterAsync("foo", new FutureCallback<Cluster>() {
        @Override/*from w ww .java  2s.c o m*/
        public void onSuccess(Cluster result) {
            assertEquals(result, cluster);
            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:ufo.remote.calls.benchmark.client.caller.vertx.VertxClusterTester.java

@Override
protected void startTest(final TesterResult result) {

    EventBus bus = vertx.eventBus();/*  w w w.  j av a  2s. co m*/
    CountDownLatch latch = new CountDownLatch(result.totalCalls);
    AtomicInteger failures = new AtomicInteger(0);

    for (int i = 0; i < result.totalCalls; i++) {
        bus.send("echo", result.message, (AsyncResult<Message<String>> response) -> {

            if (response.failed()) {
                failures.incrementAndGet();
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Received [{}]", response.result().body());
            }
            latch.countDown();
        });

    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();

}

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

@Test
public void testGetClusterAsync() throws IOException, InterruptedException {
    final Cluster cluster = new Cluster();
    cluster.setName("clusterName");
    cluster.setState(ClusterState.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(cluster);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getClusterAsync("foo", new FutureCallback<Cluster>() {
        @Override//from  w  w w  .  java  2  s  .c o  m
        public void onSuccess(Cluster result) {
            assertEquals(result, cluster);
            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.ericsson.gerrit.plugins.highavailability.cache.CacheEvictionIT.java

@Test
@UseLocalDisk/*  www .  j  a v  a  2 s .c  o m*/
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void flushAndSendPost() throws Exception {
    final String flushRequest = "/plugins/high-availability/cache/" + Constants.PROJECTS;
    final CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(flushRequest)) {
            expectedRequestLatch.countDown();
        }
    });

    adminSshSession.exec("gerrit flush-caches --cache " + Constants.PROJECTS);
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(flushRequest)));
}

From source file:com.uphyca.kitkat.storage.internal.impl.LiveSdkSkyDriveClient.java

@Override
public void initializeIfNecessary() {
    if (mLiveConnectClient != null) {
        return;/*from   w  ww. j ava2s  .  co  m*/
    }
    final CountDownLatch lock = new CountDownLatch(1);
    mLiveAuthClient.initialize(SCOPES, new LiveAuthListener() {
        @Override
        public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
            if (status == LiveStatus.CONNECTED) {
                mLiveConnectClient = new LiveConnectClient(session);
            }
            lock.countDown();
        }

        @Override
        public void onAuthError(LiveAuthException exception, Object userState) {
            lock.countDown();
        }
    });
    try {
        lock.await();
    } catch (InterruptedException ignore) {
    }
}

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  w  w w. ja v a 2 s  .  co  m
    };

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