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.vmware.photon.controller.api.client.resource.FlavorApiTest.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);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override/*from w w  w . ja  v a  2  s.c om*/
        public void onSuccess(@Nullable 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.FlavorRestApiTest.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);

    FlavorApi flavorApi = new FlavorRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.deleteAsync("foo", new FutureCallback<Task>() {
        @Override//ww w . ja va2s . c om
        public void onSuccess(@Nullable 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: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();//from  ww w  .  ja  v a2  s. co m

        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();
    server.dispose();
}

From source file:io.syndesis.connector.sql.stored.SqlStoredStartConnectorComponentTest.java

@Test
public void camelConnectorTest() throws Exception {

    BasicDataSource ds = new BasicDataSource();
    ds.setUsername(properties.getProperty("sql-stored-start-connector.user"));
    ds.setPassword(properties.getProperty("sql-stored-start-connector.password"));
    ds.setUrl(properties.getProperty("sql-stored-start-connector.url"));

    SimpleRegistry registry = new SimpleRegistry();
    registry.put("dataSource", ds);
    CamelContext context = new DefaultCamelContext(registry);

    CountDownLatch latch = new CountDownLatch(1);

    final Result result = new Result();

    try {/*w w w  . j  a  v  a 2s  .co  m*/
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("sql-stored-start-connector:DEMO_OUT( OUT INTEGER c)").process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        String jsonBean = (String) exchange.getIn().getBody();
                        result.setResult(jsonBean);
                        latch.countDown();
                    }
                }).to("stream:out");
            }
        });
        context.start();
        latch.await(5l, TimeUnit.SECONDS);
        Assert.assertEquals("{\"c\":60}", result.getJsonBean());
    } finally {
        context.stop();
    }
}

From source file:io.openvidu.server.recording.service.RecordingManager.java

public void stopOneIndividualStreamRecording(String sessionId, String streamId, boolean forceAfterKmsRestart) {
    Recording recording = this.sessionsRecordings.get(sessionId);
    if (recording == null) {
        log.error("Cannot stop recording of existing stream {}. Session {} is not being recorded", streamId,
                sessionId);/*  w  w w. j  ava 2  s.c  o  m*/
    }
    if (io.openvidu.java.client.Recording.OutputMode.INDIVIDUAL.equals(recording.getOutputMode())) {
        // Stop specific RecorderEndpoint for this stream
        log.info("Stopping RecorderEndpoint in session {} for stream of participant {}", sessionId, streamId);
        final CountDownLatch stoppedCountDown = new CountDownLatch(1);
        this.singleStreamRecordingService.stopRecorderEndpointOfPublisherEndpoint(sessionId, streamId,
                stoppedCountDown, forceAfterKmsRestart);
        try {
            if (!stoppedCountDown.await(5, TimeUnit.SECONDS)) {
                log.error("Error waiting for recorder endpoint of stream {} to stop in session {}", streamId,
                        sessionId);
            }
        } catch (InterruptedException e) {
            log.error("Exception while waiting for state change", e);
        }
    } else if (io.openvidu.java.client.Recording.OutputMode.COMPOSED.equals(recording.getOutputMode())
            && !recording.hasVideo()) {
        // Disconnect this stream from existing Composite recorder
        log.info("Removing PublisherEndpoint from Composite in session {} for stream of participant {}",
                sessionId, streamId);
        this.composedRecordingService.removePublisherEndpointFromComposite(sessionId, streamId);
    }
}

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

@Test
public void testGetFlavorAsync() throws IOException, InterruptedException {
    final Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavor1);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.getFlavorAsync(flavor1.getId(), new FutureCallback<Flavor>() {
        @Override//from  w w w  . j a  va  2 s.co m
        public void onSuccess(@Nullable Flavor result) {
            assertEquals(result, flavor1);
            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.FlavorRestApiTest.java

@Test
public void testGetFlavorAsync() throws IOException, InterruptedException {
    final Flavor flavor1 = new Flavor();
    flavor1.setId("flavor1");
    flavor1.setKind("vm");

    ObjectMapper mapper = new ObjectMapper();
    String serializedResponse = mapper.writeValueAsString(flavor1);

    setupMocks(serializedResponse, HttpStatus.SC_OK);

    FlavorApi flavorApi = new FlavorRestApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.getFlavorAsync(flavor1.getId(), new FutureCallback<Flavor>() {
        @Override/*from   w w w. ja  va  2 s .c o m*/
        public void onSuccess(@Nullable Flavor result) {
            assertEquals(result, flavor1);
            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:de.hybris.platform.media.storage.impl.DefaultLocalMediaFileCacheServiceIntegrationTest.java

private void runThreadsWithLatch(final int numThreads, final CacheTestExecutor executor) {
    try {/*w  ww . j  ava2s. c om*/
        final CountDownLatch latch = new CountDownLatch(numThreads);
        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        executor.execute();
                    } finally {
                        latch.countDown();
                    }
                }

            }).start();

        }
        latch.await(10, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:org.eclipse.hono.service.AbstractApplication.java

/**
 * Stops this application in a controlled fashion.
 * /*from  w  w w.  ja  va  2s . c  o m*/
 * @param maxWaitTime The maximum time to wait for the server to shut down (in seconds).
 * @param shutdownHandler The handler to invoke with the result of the shutdown attempt.
 */
public final void shutdown(final long maxWaitTime, final Handler<Boolean> shutdownHandler) {

    try {
        log.info("shutting down application...");

        preShutdown();
        final CountDownLatch latch = new CountDownLatch(1);

        stopHealthCheckServer().setHandler(result -> {

            if (vertx != null) {
                log.info("closing vert.x instance ...");
                vertx.close(r -> {
                    if (r.failed()) {
                        log.error("could not close vert.x instance", r.cause());
                    }
                    latch.countDown();
                });
            } else {
                latch.countDown(); // nothing to wait for
            }
        });

        if (latch.await(maxWaitTime, TimeUnit.SECONDS)) {
            log.info("application has been shut down successfully");
            shutdownHandler.handle(Boolean.TRUE);
        } else {
            log.error("shut down timed out, aborting...");
            shutdownHandler.handle(Boolean.FALSE);
        }
    } catch (InterruptedException e) {
        log.error("application shut down has been interrupted, aborting...");
        Thread.currentThread().interrupt();
        shutdownHandler.handle(Boolean.FALSE);
    }
}

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

@Test
public void testCreateAsync() throws Exception {
    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);

    FlavorApi flavorApi = new FlavorApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    flavorApi.createAsync(new FlavorCreateSpec(), new FutureCallback<Task>() {
        @Override/*from ww w .  j  a v  a2s.  c o m*/
        public void onSuccess(@Nullable 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));
}