Example usage for java.util.concurrent CountDownLatch await

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

Introduction

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

Prototype

public boolean await(long timeout, TimeUnit unit) throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted , or the specified waiting time elapses.

Usage

From source file:com.github.mrstampy.gameboot.otp.netty.OtpNettyTest.java

private void sendMessage(AbstractGameBootMessage message, Channel channel) throws Exception {
    CountDownLatch cdl = new CountDownLatch(1);
    clientHandler.setResponseLatch(cdl);

    boolean b = clientHandler.hasKey();

    channel.writeAndFlush(converter.toJsonArray(message));

    log.info("Sending {}: {}", (b ? "encrypted" : "unencrypted"), converter.toJson(message));

    cdl.await(1, TimeUnit.SECONDS);
}

From source file:com.palantir.docker.compose.DockerComposeRuleShould.java

@SuppressWarnings("unchecked")
@Test// w  w w  .  jav  a 2  s.  c  o  m
public void be_able_to_save_logs_to_a_directory_while_containers_are_running()
        throws IOException, InterruptedException {
    File logLocation = logFolder.newFolder();
    DockerComposeRule loggingComposition = DockerComposeRule.builder().from(rule)
            .saveLogsTo(logLocation.getAbsolutePath()).build();
    when(dockerCompose.ps()).thenReturn(TestContainerNames.of("db"));
    CountDownLatch latch = new CountDownLatch(1);
    when(dockerCompose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("db log", outputStream);
        latch.countDown();
        return true;
    });
    loggingComposition.before();
    assertThat(latch.await(1, TimeUnit.SECONDS), is(true));
    loggingComposition.after();
    assertThat(logLocation.listFiles(), arrayContaining(fileWithName("db.log")));
    assertThat(new File(logLocation, "db.log"), is(fileContainingString("db log")));
}

From source file:WorkQueue.java

/**
 * Waits until all the tasks associated with the group identifier have
 * finished.  Once a task group has been successfully waited upon, the group
 * identifier is removed from the queue and is valid to be reused for a new
 * task group.//from w w w  . j ava2 s . c om
 *
 * @throws IllegalArgumentException if the {@code taskGroupId} is not
 *         currently associated with any active taskGroup
 */
public void await(Object taskGroupId) {
    CountDownLatch latch = taskKeyToLatch.get(taskGroupId);
    if (latch == null)
        throw new IllegalArgumentException("Unknown task group: " + taskGroupId);
    try {
        while (!latch.await(5, TimeUnit.SECONDS))
            System.out.println("cur count: " + latch.getCount());
        // Once finished, remove the key so it can be associated with a new
        // task
        taskKeyToLatch.remove(taskGroupId);
    } catch (InterruptedException ie) {
        throw new IllegalStateException("Not all tasks finished", ie);
    }
}

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

@Test
public void testBackgroundDelete() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//w  w w  . j av  a 2s.co  m
    try {
        client.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getType() == CuratorEventType.DELETE) {
                    Assert.assertEquals(event.getPath(), "/head");
                    ((CountDownLatch) event.getContext()).countDown();
                }
            }
        });

        client.create().forPath("/head");
        Assert.assertNotNull(client.checkExists().forPath("/head"));

        CountDownLatch latch = new CountDownLatch(1);
        client.delete().inBackground(latch).forPath("/head");
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNull(client.checkExists().forPath("/head"));
    } finally {
        client.close();
    }
}

From source file:io.fabric8.msg.jnatsd.TestConnect.java

@Test
public void testConnect() throws Exception {
    Connection subConnection = connectionFactory.createConnection();
    final int count = 1000;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = subConnection.subscribe("foo", new MessageHandler() {
        @Override//from ww w .  ja v  a  2 s.  c  om
        public void onMessage(Message message) {
            countDownLatch.countDown();
            //System.out.println("GOT " + message);
        }
    });

    Connection pubConnection = new ConnectionFactory().createConnection();

    for (int i = 0; i < count; i++) {
        String test = "Test" + i;
        pubConnection.publish("foo", "bah", test.getBytes());
    }

    countDownLatch.await(2, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    pubConnection.close();
    subConnection.close();
}

From source file:com.twotoasters.android.hoottestapplication.test.HootTest.java

private <T> void executeTest(final HootRequest request, CountDownLatch latch) {
    try {/*from   w  w w  .j av a2  s. co  m*/
        runTestOnUiThread(new Runnable() {

            @Override
            public void run() {
                request.execute();
            }
        });
    } catch (Throwable e1) {
        fail(e1.getMessage());
    }

    try {
        latch.await(200, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

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  w  ww  .ja v a 2s  .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.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 w w  .jav  a 2 s  .  co m*/
        log.info("received token: " + customToken + " *");
        countDownLatch.countDown();
    });
    countDownLatch.await(10, TimeUnit.SECONDS);
    return Utilities.prepareFirebaseJsonResponseForToken(token[0], deviceInfo.getKey());
}

From source file:org.eclipse.hono.adapter.VertxBasedAdapterApplication.java

@PostConstruct
public void registerVerticles() {

    if (running.compareAndSet(false, true)) {
        final int instanceCount = honoConfig.getMaxInstances();

        try {/*from www . ja  v a 2 s.  c o m*/
            final CountDownLatch latch = new CountDownLatch(1);
            final Future<Void> startFuture = Future.future();
            startFuture.setHandler(done -> {
                if (done.succeeded()) {
                    latch.countDown();
                } else {
                    LOG.error("could not start '{}' adapter", this.getName(), done.cause());
                }
            });

            deployVerticle(instanceCount, startFuture);

            if (latch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
                LOG.info("'{}' adapter startup completed successfully", this.getName());
            } else {
                LOG.error("startup timed out after {} seconds, shutting down ...",
                        honoConfig.getStartupTimeout());
                shutdown();
            }
        } catch (InterruptedException e) {
            LOG.error("startup process has been interrupted, shutting down ...");
            Thread.currentThread().interrupt();
            shutdown();
        }
    }
}

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

@Test
public void testBackgroundCreate() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from   ww w .j  a  va  2 s.  c om
    try {
        client.getCuratorListenable().addListener(new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getType() == CuratorEventType.CREATE) {
                    Assert.assertEquals(event.getPath(), "/test");
                    ((CountDownLatch) event.getContext()).countDown();
                }
            }
        });

        CountDownLatch latch = new CountDownLatch(1);
        client.create().inBackground(latch).forPath("/test", new byte[] { 1, 2, 3 });
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    } finally {
        client.close();
    }
}