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:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java

@Test
public void testDeleteAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

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

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/* ww  w.  j  av a  2 s . c  om*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            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.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 w w .j  a va  2  s. c  om*/
        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.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  ww w  . ja  v a 2 s . c  om*/
        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:example.springdata.mongodb.people.ReactiveMongoTemplateIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining. It prints
 * the two counts ({@code 4} and {@code 6}) to the console.
 *//*  w w  w.  ja  va  2 s  .co  m*/
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

    template.count(new Query(), Person.class) //
            .doOnNext(System.out::println) //
            .thenMany(template.save(Flux.just(new Person("Hank", "Schrader", 43), //
                    new Person("Mike", "Ehrmantraut", 62)))) //
            .last() //
            .flatMap(v -> template.count(new Query(), Person.class)) //
            .doOnNext(System.out::println) //
            .doOnSuccess(it -> countDownLatch.countDown()) //
            .doOnError(throwable -> countDownLatch.countDown()) //
            .subscribe();

    countDownLatch.await();
}

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

@Test
public void exposesRemoteAddress() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(1);

    NettyContext server = TcpServer.create(port).newHandler((in, out) -> {
        InetSocketAddress remoteAddr = in.remoteAddress();
        assertNotNull("remote address is not null", remoteAddr.getAddress());
        latch.countDown();

        return Flux.never();
    }).block(Duration.ofSeconds(30));

    NettyContext client = TcpClient.create(port)
            .newHandler((in, out) -> out.sendString(Flux.just("Hello World!"))).block(Duration.ofSeconds(30));

    assertTrue("latch was counted down", latch.await(5, TimeUnit.SECONDS));

    client.dispose();/* w w w  . ja v a 2s . c o  m*/
    server.dispose();
}

From source file:info.archinnov.achilles.it.TestAsyncCRUDSimpleEntity.java

@Test
public void should_delete_instance_async() throws Exception {
    //Given/* w  w  w . j av a  2 s  . c  o  m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = buildDateKey();
    final SimpleEntity entity = new SimpleEntity(id, date, "value");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql",
            ImmutableMap.of("id", id, "table", "simple"));

    final CountDownLatch latch = new CountDownLatch(1);
    final CassandraLogAsserter logAsserter = new CassandraLogAsserter();
    logAsserter.prepareLogLevel(ASYNC_LOGGER_STRING, "%msg - [%thread]%n");

    //When
    final CompletableFuture<ExecutionInfo> future = manager.crud().delete(entity)
            .withResultSetAsyncListener(rs -> {
                LOGGER.info(CALLED);
                latch.countDown();
                return rs;
            }).executeAsyncWithStats();

    //Then
    latch.await();
    logAsserter.assertContains("Called");
    final List<Row> rows = session.execute("SELECT * FROM simple WHERE id = " + id).all();
    assertThat(rows).isEmpty();

    final ExecutionInfo executionInfo = future.get();
    assertThat(executionInfo.getQueriedHost().isUp()).isTrue();
}

From source file:com.vmware.photon.controller.deployer.dcp.DeployerXenonServiceHostTest.java

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

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            DeployerXenonServiceHost.FACTORY_SERVICE_FIELD_NAME_SELF_LINK,
            DeployerXenonServiceHost.FACTORY_SERVICES);
    serviceSelfLinks.add(DeployerXenonServiceHost.UPLOAD_VIB_SCHEDULER_SERVICE);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override//from   w  ww .j a  v a2s .  co m
        public void handle(Operation completedOp, Throwable failure) {
            latch.countDown();
        }
    };

    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.amazonaws.services.simpleworkflow.flow.worker.GenericWorker.java

@Override
public void resumePolling() {
    if (log.isInfoEnabled()) {
        log.info("resumePolling");
    }/*from www. java 2 s  .c o m*/
    CountDownLatch existing = suspendLatch.getAndSet(null);
    if (existing != null) {
        existing.countDown();
    }
}

From source file:com.netflix.curator.framework.recipes.shared.TestSharedCount.java

@Test
public void testMultiClients() throws Exception {
    final int CLIENT_QTY = 5;

    List<Future<List<Integer>>> futures = Lists.newArrayList();
    final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>();
    try {/*from w w  w . java  2  s.c o  m*/
        final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY);
        final Semaphore semaphore = new Semaphore(0);
        ExecutorService service = Executors
                .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build());
        for (int i = 0; i < CLIENT_QTY; ++i) {
            Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    final List<Integer> countList = Lists.newArrayList();
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new RetryOneTime(1));
                    clients.add(client);
                    client.start();

                    SharedCount count = new SharedCount(client, "/count", 10);

                    final CountDownLatch latch = new CountDownLatch(1);
                    count.addListener(new SharedCountListener() {
                        @Override
                        public void countHasChanged(SharedCountReader sharedCount, int newCount)
                                throws Exception {
                            if (newCount < 0) {
                                latch.countDown();
                            } else {
                                countList.add(newCount);
                            }

                            semaphore.release();
                        }

                        @Override
                        public void stateChanged(CuratorFramework client, ConnectionState newState) {
                        }
                    });
                    count.start();
                    startLatch.countDown();
                    latch.await();
                    return countList;
                }
            });
            futures.add(future);
        }

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        clients.add(client);
        client.start();

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

        SharedCount count = new SharedCount(client, "/count", 10);
        count.start();

        List<Integer> countList = Lists.newArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; ++i) {
            Thread.sleep(random.nextInt(10));

            int next = random.nextInt(100);
            countList.add(next);
            count.setCount(next);

            Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS));
        }
        count.setCount(-1);

        for (Future<List<Integer>> future : futures) {
            List<Integer> thisCountList = future.get();
            Assert.assertEquals(thisCountList, countList);
        }
    } finally {
        for (CuratorFramework client : clients) {
            IOUtils.closeQuietly(client);
        }
    }
}

From source file:aos.camel.RiderAutoPartsCallbackTest.java

@Test
public void testCallback() throws Exception {
    // related is the list of related items
    final List<String> relates = new ArrayList<String>();

    // latch to count down every time we got a reply
    final CountDownLatch latch = new CountDownLatch(numPartners);

    // use this callback to gather the replies and add it to the related list
    Synchronization callback = new SynchronizationAdapter() {
        @Override//from  ww w. j  a  va  2  s  .  com
        public void onComplete(Exchange exchange) {
            // get the reply and add it to related
            relates.add(exchange.getOut().getBody(String.class));
            // count down the latch
            latch.countDown();
        }

        @Override
        public void onFailure(Exchange exchange) {
            // count down the latch even if we failed
            latch.countDown();
        }
    };

    // send the same message to the business partners so they can return their feedback
    String body = "bumper";
    for (int i = 0; i < numPartners; i++) {
        template.asyncCallbackRequestBody("seda:partner:" + i, body, callback);
    }
    LOG.info("Send " + numPartners + " messages to partners.");

    // wait at most 1.5 seconds or until we got all replies
    boolean all = latch.await(1500, TimeUnit.MILLISECONDS);

    // log what we got as reply
    LOG.info("Got " + relates.size() + " replies, is all? " + all);
    for (String related : relates) {
        LOG.info("Related item category is: " + related);
    }

    // assert the unit test
    assertEquals(3, relates.size());
    assertEquals("bumper extension", relates.get(0));
    assertEquals("bumper filter", relates.get(1));
    assertEquals("bumper cover", relates.get(2));
}