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:ufo.remote.calls.benchmark.client.caller.vertx.VertxClusterTester.java

@Override
protected void startTest(final TesterResult result) {

    EventBus bus = vertx.eventBus();/*from  ww w  . j ava  2s  .c o  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.ClusterApiTest.java

@Test
public void testGetVmsAsync() throws IOException, InterruptedException {
    Vm vm1 = new Vm();
    vm1.setId("vm1");

    Vm vm2 = new Vm();
    vm2.setId("vm2");

    final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2));

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getVmsInClusterAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override/*from w  w w  . j  av  a 2  s  . c  o m*/
        public void onSuccess(ResourceList<Vm> result) {
            assertEquals(result.getItems(), vmList.getItems());
            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.api.client.resource.ClusterRestApiTest.java

@Test
public void testGetVmsAsync() throws IOException, InterruptedException {
    Vm vm1 = new Vm();
    vm1.setId("vm1");

    Vm vm2 = new Vm();
    vm2.setId("vm2");

    final ResourceList<Vm> vmList = new ResourceList<>(Arrays.asList(vm1, vm2));

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ClusterApi clusterApi = new ClusterRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.getVmsInClusterAsync("foo", new FutureCallback<ResourceList<Vm>>() {
        @Override/*from w  w  w .j a  va  2s.  co  m*/
        public void onSuccess(ResourceList<Vm> result) {
            assertEquals(result.getItems(), vmList.getItems());
            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:EventingTest.java

public void testEventing() throws Exception {

    meshKeeper.launcher().waitForAvailableAgents(60000);
    HostProperties[] hosts = meshKeeper.launcher().getAvailableAgents();

    MeshContainer c1 = meshKeeper.launcher().launchMeshContainer(hosts[0].getAgentId());
    MeshContainer c2 = meshKeeper.launcher()
            .launchMeshContainer((hosts.length > 1 ? hosts[1] : hosts[0]).getAgentId());

    Greeter g1 = new Greeter();
    g1.name = "machine1";

    Greeter g2 = new Greeter();
    g2.name = "machine2";

    //Let's host them in their containers,
    //Note that we replace the actual references
    //with their proxy counterparts.
    g1 = c1.host(g1.name, g1);/*from w  w  w.  j  a  va  2  s.c om*/
    g2 = c2.host(g2.name, g2);

    //Set up an event listener to wait for the hellos
    final CountDownLatch hellos = new CountDownLatch(2);
    final ArrayList<Exception> errors = new ArrayList<Exception>();
    MeshEventListener listener = new MeshEventListener() {

        public void onEvent(MeshEvent event) {
            switch (event.getType()) {
            case HELLO: {
                LOG.info("Got : " + event.getAttachment() + " from " + event.getSource());
                hellos.countDown();
                break;
            }
            case SAY_HELLO: {
                break;
            }

            case ERROR:
            default: {
                Exception e = event.getAttachment();
                LOG.error("Error from: " + event.getSource(), e);
                errors.add(e);

                while (hellos.getCount() > 0) {
                    hellos.countDown();
                }
            }
            }
        }
    };
    meshKeeper.eventing().openEventListener(listener, EVENT_TOPIC + ".*");

    //Start the
    g1.startListening();
    g2.startListening();
    meshKeeper.eventing().sendEvent(new MeshEvent(SAY_HELLO, "controller", null), EVENT_TOPIC + ".control");

    hellos.await(10, TimeUnit.SECONDS);
    Thread.sleep(2000);
    assertTrue("There were errors", errors.isEmpty());
    c1.close();
    c2.close();

    meshKeeper.eventing().closeEventListener(listener, EVENT_TOPIC + ".*");
}

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

@Test
public void testNotify() throws Exception {
    CuratorFramework client1 = null;/*from   w  ww . ja va  2 s  .  c o m*/
    CuratorFramework client2 = null;
    try {
        client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));

        client1.start();
        client2.start();

        final CountDownLatch latch = new CountDownLatch(1);
        client1.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getType() == CuratorEventType.WATCHED) {
                    if (event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged) {
                        if (event.getPath().equals("/test")) {
                            latch.countDown();
                        }
                    }
                }
            }
        });

        client1.create().forPath("/test", new byte[] { 1, 2, 3 });
        client1.checkExists().watched().forPath("/test");

        client2.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getType() == CuratorEventType.SYNC) {
                    client.setData().forPath("/test", new byte[] { 10, 20 });
                }
            }
        });

        client2.sync("/test", null);

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    } finally {
        IOUtils.closeQuietly(client1);
        IOUtils.closeQuietly(client2);
    }
}

From source file:com.amazonaws.cognito.devauthsample.identity.AWSCognitoDeveloperAuthenticationSample.java

public String getFirebaseToken(String uid)
        throws DataAccessException, UnauthorizedException, InterruptedException {
    DeviceAuthentication.DeviceInfo deviceInfo = ensureKnownDevice(uid);
    UserAuthentication.UserInfo userInfo = ensureKnownUser(deviceInfo.getUsername());

    CountDownLatch countDownLatch = new CountDownLatch(1);
    final String[] token = new String[1];
    FirebaseAuth.getInstance().createCustomToken(uid).addOnSuccessListener(customToken -> {
        // Send token back to client
        token[0] = customToken;// w  ww  .  j ava2  s  . com
        log.info("received token: " + customToken + " *");
        countDownLatch.countDown();
    });
    countDownLatch.await(10, TimeUnit.SECONDS);
    return Utilities.prepareFirebaseJsonResponseForToken(token[0], deviceInfo.getKey());
}

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

@Test
public void testGetFabricNode() throws IOException, InterruptedException {
    final FabricNode mockResponse = new FabricNode();
    mockResponse.setId("id");
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK);

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getFabricNode("nodeId", new com.google.common.util.concurrent.FutureCallback<FabricNode>() {
        @Override//from  ww  w . j av a  2s .  c o  m
        public void onSuccess(FabricNode result) {
            assertEquals(result, mockResponse);
            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.hawkular.apm.client.opentracing.APMTracerTest.java

@Test
public void testAsync() throws JsonProcessingException, InterruptedException {
    TestTraceRecorder recorder = new TestTraceRecorder();
    APMTracer tracer = new APMTracer(recorder);

    AsyncService service = new AsyncService(tracer);

    Message message = new Message();
    message.getHeaders().put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID);
    message.getHeaders().put(Constants.HAWKULAR_APM_ID, TEST_APM_ID);
    message.getHeaders().put(Constants.HAWKULAR_APM_TXN, TEST_TXN);

    CountDownLatch latch = new CountDownLatch(1);
    service.handle(message, obj -> {/*from ww w.j  a v a2s .  c  o  m*/
        latch.countDown();
    });

    latch.await(5, TimeUnit.SECONDS);

    Wait.until(() -> recorder.getTraces().size() == 1, 5, TimeUnit.SECONDS);

    assertEquals(1, recorder.getTraces().size());

    Trace trace1 = recorder.getTraces().get(0);
    assertEquals(TEST_TXN, trace1.getTransaction());
    assertEquals(1, trace1.getNodes().size());
    assertEquals(Consumer.class, trace1.getNodes().get(0).getClass());

    Consumer consumer = (Consumer) trace1.getNodes().get(0);

    // Check has supplied correlation id
    assertEquals(1, consumer.getCorrelationIds().size());
    assertEquals(consumer.getCorrelationIds().get(0),
            new CorrelationIdentifier(Scope.Interaction, TEST_APM_ID));

    // Get middle component
    assertEquals(1, consumer.getNodes().size());
    assertEquals(Producer.class, consumer.getNodes().get(0).getClass());

    Producer producer = (Producer) consumer.getNodes().get(0);

    assertEquals(1, service.getMessages().size());

    // Check producer has interaction based correlation id matching the value in the outbound message
    assertTrue(service.getMessages().get(0).getHeaders().containsKey(Constants.HAWKULAR_APM_ID));

    assertEquals(1, producer.getCorrelationIds().size());
    assertEquals(producer.getCorrelationIds().get(0), new CorrelationIdentifier(Scope.Interaction,
            service.getMessages().get(0).getHeaders().get(Constants.HAWKULAR_APM_ID)));

    assertEquals(TEST_APM_TRACEID,
            service.getMessages().get(0).getHeaders().get(Constants.HAWKULAR_APM_TRACEID));

    assertEquals(TEST_TXN, service.getMessages().get(0).getHeaders().get(Constants.HAWKULAR_APM_TXN));
}

From source file:com.predic8.membrane.examples.tests.integration.OAuth2RaceCondition.java

@Test
public void testSessionIdStateRaceCondition() throws Exception {
    HttpClient hc = HttpClientBuilder.create().build();

    login(hc);/*from  ww  w  .  j av a2s .  com*/
    System.out.println("Logged in");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 10; i++) {

        //            HttpClient hc1 = HttpClientBuilder.create().build();
        //            login(hc1);
        Future<Exception>[] results = new Future[2];

        int parallelReqs = 2;
        CountDownLatch cdl = new CountDownLatch(parallelReqs);

        for (int j = 0; j < parallelReqs; j++) {
            final int fj = j;
            results[j] = executor.submit(() -> {
                try {
                    int uri = (fj % 2 == 0 ? 1 : 2);
                    String url = "http://localhost:2011/test" + uri;
                    HttpGet get = new HttpGet(url);
                    //setNoRedirects(get);
                    cdl.countDown();
                    cdl.await();
                    try (CloseableHttpResponse getRes = (CloseableHttpResponse) hc.execute(get)) {
                        assertEquals(200, getRes.getStatusLine().getStatusCode());
                        String resText = EntityUtils.toString(getRes.getEntity(), "UTF-8");
                        System.out.println("Called: Test" + uri + ".\nActual: " + resText);
                        assertTrue(resText.contains(Integer.toString(uri)));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            });
        }
        for (int j = 0; j < parallelReqs; j++) {
            results[j].get();
        }

        for (int j = 0; j < parallelReqs; j++) {
            Exception e = results[j].get();
            if (e != null)
                throw new RuntimeException(e);
        }

    }
    executor.shutdown();
}

From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java

@Test
public void should_apply_interceptors_after_flush_for_batch() throws Exception {
    // Given/*w w  w. jav a 2  s. co  m*/
    final AsyncBatch asyncBatch = asyncManager.createBatch();
    asyncBatch.startBatch();

    CompleteBean entity = builder().randomId().name("DuyHai").label("label").buid();

    // When
    asyncBatch.insert(entity);

    // Then
    assertThat(entity.getName()).isEqualTo("DuyHai");
    assertThat(entity.getLabel()).isEqualTo("label");

    // When
    final CountDownLatch latch = new CountDownLatch(1);
    asyncBatch.asyncEndBatch(new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {

        }
    });

    latch.await();

    // Then
    assertThat(entity.getName()).isEqualTo("prePersist");

    assertThat(entity.getLabel()).isEqualTo("postPersist : label");
}