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.nsxclient.apis.FabricApiTest.java

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

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getTransportNode("id", new com.google.common.util.concurrent.FutureCallback<TransportNode>() {
        @Override//w w w . j a  v  a 2 s  . c  o m
        public void onSuccess(TransportNode 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:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java

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

    FabricApi client = new FabricApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getTransportZone("id", new com.google.common.util.concurrent.FutureCallback<TransportZone>() {
        @Override/*  w ww . ja  va 2  s. c o m*/
        public void onSuccess(TransportZone 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.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testThatSmallResponsesAreNotEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();//from w  ww .j  a  va 2  s .  c o  m

    byte[] content = generate(100).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, null));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

From source file:org.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testThatLargeResponsesAreNotEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();/*from   w w w  .j  av  a 2  s.  c o  m*/

    byte[] content = generate(2000).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, null));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

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

@Test
public void testReadOnly() throws Exception {
    System.setProperty("readonlymode.enabled", "true");
    try {/* ww  w . j a  v a  2  s .  co  m*/
        Timing timing = new Timing();

        CuratorFramework client = null;
        TestingCluster cluster = new TestingCluster(2);
        try {
            cluster.start();

            client = CuratorFrameworkFactory.builder().connectString(cluster.getConnectString())
                    .canBeReadOnly(true).connectionTimeoutMs(timing.connection())
                    .sessionTimeoutMs(timing.session()).retryPolicy(new ExponentialBackoffRetry(100, 3))
                    .build();
            client.start();

            client.create().forPath("/test");

            final CountDownLatch readOnlyLatch = new CountDownLatch(1);
            final CountDownLatch reconnectedLatch = new CountDownLatch(1);
            ConnectionStateListener listener = new ConnectionStateListener() {
                @Override
                public void stateChanged(CuratorFramework client, ConnectionState newState) {
                    if (newState == ConnectionState.READ_ONLY) {
                        readOnlyLatch.countDown();
                    } else if (newState == ConnectionState.RECONNECTED) {
                        reconnectedLatch.countDown();
                    }
                }
            };
            client.getConnectionStateListenable().addListener(listener);

            InstanceSpec ourInstance = cluster
                    .findConnectionInstance(client.getZookeeperClient().getZooKeeper());
            Iterator<InstanceSpec> iterator = cluster.getInstances().iterator();
            InstanceSpec killInstance = iterator.next();
            if (killInstance.equals(ourInstance)) {
                killInstance = iterator.next(); // kill the instance we're not connected to
            }
            cluster.killServer(killInstance);

            Assert.assertEquals(reconnectedLatch.getCount(), 1);
            Assert.assertTrue(timing.awaitLatch(readOnlyLatch));

            Assert.assertEquals(reconnectedLatch.getCount(), 1);
            cluster.restartServer(killInstance);
            Assert.assertTrue(timing.awaitLatch(reconnectedLatch));
        } finally {
            IOUtils.closeQuietly(client);
            IOUtils.closeQuietly(cluster);
        }
    } finally {
        System.clearProperty("readonlymode.enabled");
    }
}

From source file:org.wisdom.framework.vertx.ResponseEncodingTest.java

@Test
public void testEncodingOfResponse() throws InterruptedException, IOException {
    Router router = prepareServer();/*from w ww  .j  av  a2 s.c o m*/

    byte[] content = generate(1000).getBytes();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result index() {
            return ok(content, false);
        }
    };
    final Route route1 = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
    configureRouter(router, route1);

    server.start();
    waitForStart(server);

    // Now start bunch of clients
    int num = NUMBER_OF_CLIENTS;
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(num);

    int port = server.httpPort();

    for (int i = 0; i < num; ++i) {// create and start threads
        executor.submit(new Client(startSignal, doneSignal, port, i, content, "gzip"));
    }

    startSignal.countDown(); // let all threads proceed
    assertThat(doneSignal.await(60, TimeUnit.SECONDS)).isTrue(); // wait for all to finish

    assertThat(failure).isEmpty();
    assertThat(success).hasSize(num);
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testCreateClientShouldHandshake() throws Exception {
    SocketAddress address = createSocketAddress(3000);
    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    ServerInfo serverInfo = new ServerInfo();
    serverInfo.putToOwnerships(runtime.getMethodName() + "_stream", runtime.getMethodName() + "_owner");
    Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address, serverInfo);
    builder.provideProxyClient(address, mockProxyClient.getLeft());

    final AtomicReference<ServerInfo> resultHolder = new AtomicReference<ServerInfo>(null);
    final CountDownLatch doneLatch = new CountDownLatch(1);
    ProxyListener listener = new ProxyListener() {
        @Override/*ww w  . j a va 2s . c om*/
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            resultHolder.set(serverInfo);
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    ProxyClientManager clientManager = createProxyClientManager(builder, 0L);
    clientManager.registerProxyListener(listener);
    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    clientManager.createClient(address);
    assertEquals("Create client should build the proxy client", 1, clientManager.getNumProxies());

    // When a client is created, it would handshake with that proxy
    doneLatch.await();
    assertEquals("Handshake should return server info", serverInfo, resultHolder.get());
}

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

@Test
public void should_apply_post_delete_interceptors() throws Exception {

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

    final CountDownLatch latch = new CountDownLatch(1);
    manager2.delete(entity, withAsyncListeners(new FutureCallback<Object>() {
        @Override// w ww. j  av  a2s .co m
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {

        }
    }));

    latch.await();

    assertThat(entity.getLabel()).isEqualTo("postRemove");
}

From source file:com.greplin.zookeeper.RobustZooKeeper.java

public void sync() throws IOException, InterruptedException {

    log.info("Called sync() on client " + clientNumber);
    final CountDownLatch waitForSync = new CountDownLatch(1);
    final ZooKeeper c = getClient();
    assert c.getState().isAlive();

    c.sync("/", new AsyncCallback.VoidCallback() {
        @Override//from   w w  w  .  j  a  v a  2  s.  c  om
        public void processResult(int rc, String path, Object ctx) {
            log.info("Sync callback triggered on client " + clientNumber);
            waitForSync.countDown();
        }
    }, null);

    log.info("Waitng for sync callback on client " + clientNumber);
    waitForSync.await();

    log.info("sync() finished on " + clientNumber);
    return;
}

From source file:com.rabbitmq.client.test.performance.ScalabilityTest.java

private float timeRouting(Channel channel, String[] routingKeys) throws IOException, InterruptedException {

    boolean mandatory = true;
    boolean immdediate = true;
    final CountDownLatch latch = new CountDownLatch(params.messageCount);
    channel.addReturnListener(new ReturnListener() {
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            latch.countDown();
        }/*from   w  ww  .  ja v  a2  s.  c  om*/
    });

    final long start = System.nanoTime();

    // route some messages
    Random r = new Random();
    int size = routingKeys.length;
    for (int n = 0; n < params.messageCount; n++) {
        String key = routingKeys[r.nextInt(size)];
        channel.basicPublish("amq.direct", key, true, false, MessageProperties.MINIMAL_BASIC, null);
    }

    // wait for the returns to come back
    latch.await();

    // Compute the roundtrip time
    final long finish = System.nanoTime();
    final long wallclock = finish - start;
    return (params.messageCount == 0) ? (float) 0.0 : wallclock / (float) params.messageCount / 1000;
}