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:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void createSessionTest() throws IOException, InterruptedException {
    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override//from w  w  w .  j a v  a 2  s. co  m
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("foo", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
}

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

@Test
public void testGetResourceTicketTasksAsync() throws IOException, InterruptedException {

    Task task1 = new Task();
    task1.setId("task1");

    Task task2 = new Task();
    task2.setId("task2");

    final ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2));

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getTasksForResourceTicketAsync("foo", new FutureCallback<ResourceList<Task>>() {
        @Override/* www.  ja va  2s.  c om*/
        public void onSuccess(@Nullable ResourceList<Task> result) {
            assertEquals(result.getItems(), taskResourceList.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.ResourceTicketRestApiTest.java

@Test
public void testGetResourceTicketTasksAsync() throws IOException, InterruptedException {

    Task task1 = new Task();
    task1.setId("task1");

    Task task2 = new Task();
    task2.setId("task2");

    final ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2));

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

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ResourceTicketApi resourceTicketApi = new ResourceTicketRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    resourceTicketApi.getTasksForResourceTicketAsync("foo", new FutureCallback<ResourceList<Task>>() {
        @Override// ww  w. j a v a  2  s  .c o m
        public void onSuccess(@Nullable ResourceList<Task> result) {
            assertEquals(result.getItems(), taskResourceList.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.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testCreateDhcpRelayProfile() throws IOException, InterruptedException {
    final DhcpRelayProfile mockResponse = new DhcpRelayProfile();
    mockResponse.setId("id");
    mockResponse.setResourceType(ServiceProfileResourceType.DHCP_RELAY_PROFILE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.createDhcpRelayProfile(new DhcpRelayProfileCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<DhcpRelayProfile>() {
                @Override//from  w w w  .  j  av  a  2s.c o  m
                public void onSuccess(DhcpRelayProfile 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.DhcpServiceApiTest.java

@Test
public void testCreateDhcpRelayService() throws IOException, InterruptedException {
    final DhcpRelayService mockResponse = new DhcpRelayService();
    mockResponse.setId("id");
    mockResponse.setResourceType(LogicalServiceResourceType.DHCP_RELAY_SERVICE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.createDhcpRelayService(new DhcpRelayServiceCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<DhcpRelayService>() {
                @Override/*w w  w . j a  va  2 s  .  c o m*/
                public void onSuccess(DhcpRelayService 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.netflix.curator.framework.imps.TestWithCluster.java

@Test
public void testSplitBrain() throws Exception {
    Timing timing = new Timing();

    CuratorFramework client = null;/*from ww w . j  a  v a  2  s  . co m*/
    TestingCluster cluster = new TestingCluster(3);
    cluster.start();
    try {
        // make sure all instances are up
        for (InstanceSpec instanceSpec : cluster.getInstances()) {
            client = CuratorFrameworkFactory.newClient(instanceSpec.getConnectString(), new RetryOneTime(1));
            client.start();
            client.checkExists().forPath("/");
            client.close();
            client = null;
        }

        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(),
                timing.connection(), new RetryOneTime(1));
        client.start();

        final CountDownLatch latch = new CountDownLatch(2);
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST)) {
                    latch.countDown();
                }
            }
        });

        client.checkExists().forPath("/");

        for (InstanceSpec instanceSpec : cluster.getInstances()) {
            if (!instanceSpec
                    .equals(cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()))) {
                Assert.assertTrue(cluster.killServer(instanceSpec));
            }
        }

        Assert.assertTrue(timing.awaitLatch(latch));
    } finally {
        IOUtils.closeQuietly(client);
        IOUtils.closeQuietly(cluster);
    }
}

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

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

    serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks(
            DeployerDcpServiceHost.FACTORY_SERVICE_FIELD_NAME_SELF_LINK,
            DeployerDcpServiceHost.FACTORY_SERVICES);

    final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size());
    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override//from  www  .ja v a 2s.  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.supermy.im.mongo.MongoRepository.java

/**
 *
 * @param collectionName/* ww w  .  j a  v a2s .c  om*/
 * @return
 */
public boolean collectionExists(final String collectionName) {

    MongoIterable colls = mongoDatabase().listCollectionNames();

    List<String> collectionNames = new ArrayList<String>();

    try {
        final CountDownLatch countDownLatch = new CountDownLatch(1);//??

        colls.into(collectionNames, new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                // logger.debug("?");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(collectionNames);
    System.out.println(collectionNames.size());

    for (String name : collectionNames) {
        if (name.equalsIgnoreCase(collectionName)) {
            return true;
        }
    }
    return false;
}

From source file:com.example.grpc.springboot.Cmd.java

@Override
public void run(String... args) throws Exception {
    Channel channel = channelFactory.createChannel("EchoService");

    CountDownLatch latch = new CountDownLatch(1);
    EchoServiceStub stub = EchoServiceGrpc.newStub(channel);

    for (int i = 0; i < 10; ++i) {
        stub.echo(Echo.newBuilder().setMessage("Hello" + i).build(), new StreamObserver<Echo>() {

            @Override//from   w  w w . j a  v a 2s  .c  o m
            public void onNext(Echo value) {
                System.out.println(value.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                latch.countDown();

            }

            @Override
            public void onCompleted() {
                System.out.println("Finished");
                latch.countDown();
            }
        });
    }

    latch.await();
}

From source file:com.vmware.photon.controller.api.client.resource.ClusterApiTest.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 ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from  ww  w  .  j  av a 2  s.  c o  m*/
        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));
}