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

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

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.getDhcpRelayService("id", new com.google.common.util.concurrent.FutureCallback<DhcpRelayService>() {
        @Override//www  . ja v  a  2 s. co  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.vmware.photon.controller.common.xenon.ServiceHostUtils.java

public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout,
        TimeUnit timeUnit) throws Throwable {
    QueryTask.Query selfLinkClause = new QueryTask.Query()
            .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("/photon/*")
            .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD);

    QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification();
    querySpecification.query.addBooleanClause(selfLinkClause);
    QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true);

    NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer,
            queryTask);/*from   w  w w.jav a2s .c o m*/

    Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryDocumentLinks(queryResponse);

    if (documentLinks == null || documentLinks.size() <= 0) {
        return;
    }

    CountDownLatch latch = new CountDownLatch(1);

    OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() {
        @Override
        public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) {
            if (failures != null && !failures.isEmpty()) {
                for (Throwable e : failures.values()) {
                    logger.error("deleteAllDocuments failed", e);
                }
            }
            latch.countDown();
        }
    };

    Collection<Operation> deletes = new LinkedList<>();
    for (String documentLink : documentLinks) {
        Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}")
                .setReferer(UriUtils.buildUri(host, referrer));
        deletes.add(deleteOperation);
    }

    OperationJoin join = OperationJoin.create(deletes);
    join.setCompletion(handler);
    join.sendWith(host);
    if (!latch.await(timeout, timeUnit)) {
        throw new TimeoutException(String
                .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit));
    }
}

From source file:io.openvidu.server.kurento.core.KurentoParticipant.java

public String receiveMediaFrom(Participant sender, String sdpOffer) {
    final String senderName = sender.getParticipantPublicId();

    log.info("PARTICIPANT {}: Request to receive media from {} in room {}", this.getParticipantPublicId(),
            senderName, this.session.getSessionId());
    log.trace("PARTICIPANT {}: SdpOffer for {} is {}", this.getParticipantPublicId(), senderName, sdpOffer);

    if (senderName.equals(this.getParticipantPublicId())) {
        log.warn("PARTICIPANT {}: trying to configure loopback by subscribing", this.getParticipantPublicId());
        throw new OpenViduException(Code.USER_NOT_STREAMING_ERROR_CODE,
                "Can loopback only when publishing media");
    }/*from   ww  w  . j a v a  2  s  .c  om*/

    KurentoParticipant kSender = (KurentoParticipant) sender;

    if (kSender.getPublisher() == null) {
        log.warn("PARTICIPANT {}: Trying to connect to a user without " + "a publishing endpoint",
                this.getParticipantPublicId());
        return null;
    }

    log.debug("PARTICIPANT {}: Creating a subscriber endpoint to user {}", this.getParticipantPublicId(),
            senderName);

    SubscriberEndpoint subscriber = getNewOrExistingSubscriber(senderName);

    try {
        CountDownLatch subscriberLatch = new CountDownLatch(1);
        SdpEndpoint oldMediaEndpoint = subscriber.createEndpoint(subscriberLatch);
        try {
            if (!subscriberLatch.await(KurentoSession.ASYNC_LATCH_TIMEOUT, TimeUnit.SECONDS)) {
                throw new OpenViduException(Code.MEDIA_ENDPOINT_ERROR_CODE,
                        "Timeout reached when creating subscriber endpoint");
            }
        } catch (InterruptedException e) {
            throw new OpenViduException(Code.MEDIA_ENDPOINT_ERROR_CODE,
                    "Interrupted when creating subscriber endpoint: " + e.getMessage());
        }
        if (oldMediaEndpoint != null) {
            log.warn(
                    "PARTICIPANT {}: Two threads are trying to create at "
                            + "the same time a subscriber endpoint for user {}",
                    this.getParticipantPublicId(), senderName);
            return null;
        }
        if (subscriber.getEndpoint() == null) {
            throw new OpenViduException(Code.MEDIA_ENDPOINT_ERROR_CODE, "Unable to create subscriber endpoint");
        }

        String subscriberEndpointName = this.getParticipantPublicId() + "_" + kSender.getPublisherStreamId();

        subscriber.setEndpointName(subscriberEndpointName);
        subscriber.getEndpoint().setName(subscriberEndpointName);
        subscriber.setStreamId(kSender.getPublisherStreamId());

        endpointConfig.addEndpointListeners(subscriber, "subscriber");

    } catch (OpenViduException e) {
        this.subscribers.remove(senderName);
        throw e;
    }

    log.debug("PARTICIPANT {}: Created subscriber endpoint for user {}", this.getParticipantPublicId(),
            senderName);
    try {
        String sdpAnswer = subscriber.subscribe(sdpOffer, kSender.getPublisher());
        log.trace("PARTICIPANT {}: Subscribing SdpAnswer is {}", this.getParticipantPublicId(), sdpAnswer);
        log.info("PARTICIPANT {}: Is now receiving video from {} in room {}", this.getParticipantPublicId(),
                senderName, this.session.getSessionId());

        if (!ProtocolElements.RECORDER_PARTICIPANT_PUBLICID.equals(this.getParticipantPublicId())) {
            endpointConfig.getCdr().recordNewSubscriber(this, this.session.getSessionId(),
                    sender.getPublisherStreamId(), sender.getParticipantPublicId(), subscriber.createdAt());
        }

        return sdpAnswer;
    } catch (KurentoServerException e) {
        // TODO Check object status when KurentoClient sets this info in the object
        if (e.getCode() == 40101) {
            log.warn("Publisher endpoint was already released when trying "
                    + "to connect a subscriber endpoint to it", e);
        } else {
            log.error("Exception connecting subscriber endpoint " + "to publisher endpoint", e);
        }
        this.subscribers.remove(senderName);
        releaseSubscriberEndpoint(senderName, subscriber, null);
    }
    return null;
}

From source file:com.linkedin.helix.tools.ClusterStateVerifier.java

public static boolean verifyByZkCallback(ZkVerifier verifier, long timeout) {
    long startTime = System.currentTimeMillis();
    CountDownLatch countDown = new CountDownLatch(1);
    ZkClient zkClient = verifier.getZkClient();
    String clusterName = verifier.getClusterName();

    // add an ephemeral node to /{clusterName}/CONFIGS/CLUSTER/verify
    // so when analyze zk log, we know when a test ends
    zkClient.createEphemeral("/" + clusterName + "/CONFIGS/CLUSTER/verify");

    ExtViewVeriferZkListener listener = new ExtViewVeriferZkListener(countDown, zkClient, verifier);

    String extViewPath = PropertyPathConfig.getPath(PropertyType.EXTERNALVIEW, clusterName);
    zkClient.subscribeChildChanges(extViewPath, listener);
    for (String child : zkClient.getChildren(extViewPath)) {
        String childPath = extViewPath.equals("/") ? extViewPath + child : extViewPath + "/" + child;
        zkClient.subscribeDataChanges(childPath, listener);
    }/*  w  w  w.j a v a2  s.com*/

    // do initial verify
    boolean result = verifier.verify();
    if (result == false) {
        try {
            result = countDown.await(timeout, TimeUnit.MILLISECONDS);
            if (result == false) {
                // make a final try if timeout
                result = verifier.verify();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // clean up
    zkClient.unsubscribeChildChanges(extViewPath, listener);
    for (String child : zkClient.getChildren(extViewPath)) {
        String childPath = extViewPath.equals("/") ? extViewPath + child : extViewPath + "/" + child;
        zkClient.unsubscribeDataChanges(childPath, listener);
    }

    long endTime = System.currentTimeMillis();

    zkClient.delete("/" + clusterName + "/CONFIGS/CLUSTER/verify");
    // debug
    System.err.println(result + ": wait " + (endTime - startTime) + "ms, " + verifier);

    return result;
}

From source file:org.eclipse.hono.application.HonoApplication.java

/**
 * Stops the Hono server in a controlled fashion.
 * //  w w w  . jav  a 2s . c  om
 * @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 {
        preShutdown();
        final CountDownLatch latch = new CountDownLatch(1);
        if (vertx != null) {
            LOG.debug("shutting down Hono server...");
            vertx.close(r -> {
                if (r.failed()) {
                    LOG.error("could not shut down Hono cleanly", r.cause());
                }
                latch.countDown();
            });
        }
        if (latch.await(maxWaitTime, TimeUnit.SECONDS)) {
            LOG.info("Hono server has been shut down successfully");
            shutdownHandler.handle(Boolean.TRUE);
        } else {
            LOG.error("shut down of Hono server timed out, aborting...");
            shutdownHandler.handle(Boolean.FALSE);
        }
    } catch (InterruptedException e) {
        LOG.error("shut down of Hono server has been interrupted, aborting...");
        Thread.currentThread().interrupt();
        shutdownHandler.handle(Boolean.FALSE);
    }
}

From source file:org.apache.cxf.systest.jaxrs.AbstractJAXRSContinuationsTest.java

protected void doTestContinuation(String pathSegment) throws Exception {
    final String port = getPort();
    ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);
    List<BookWorker> workers = new ArrayList<>(5);
    for (int x = 1; x < 6; x++) {
        workers.add(new BookWorker("http://localhost:" + port + getBaseAddress() + pathSegment + "/" + x,
                Integer.toString(x), "CXF in Action" + x, startSignal, doneSignal));
    }//from   w w  w.  j  a v a2s  .co  m
    for (BookWorker w : workers) {
        executor.execute(w);
    }

    startSignal.countDown();
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
    for (BookWorker w : workers) {
        w.checkError();
    }
}

From source file:com.mozilla.fhr.consumer.FHRConsumer.java

@Override
public void poll() {
    final CountDownLatch latch = new CountDownLatch(streams.size());
    workers = new ArrayList<Future<Void>>(streams.size());
    for (final KafkaStream<Message> stream : streams) {
        workers.add(executor.submit(new FHRConsumerWorker(stream, latch)));
    }/*w w  w  . ja  v a  2 s . c o  m*/

    // Wait for all tasks to complete which in the normal case they will
    // run indefinitely unless killed
    try {
        while (true) {
            latch.await(10, TimeUnit.SECONDS);
            if (latch.getCount() != streams.size()) {
                // we have a dead thread and should exit
                break;
            }
        }
    } catch (InterruptedException e) {
        LOG.info("Interrupted during polling", e);
    }

    // Spit out errors if there were any
    for (Future<Void> worker : workers) {
        try {
            if (worker.isDone() && !worker.isCancelled()) {
                worker.get(1, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            LOG.error("Thread was interrupted:", e);
        } catch (ExecutionException e) {
            LOG.error("Exception occured in thread:", e);
        } catch (TimeoutException e) {
            LOG.error("Timed out waiting for thread result:", e);
        } catch (CancellationException e) {
            LOG.error("Thread has been canceled: ", e);
        }
    }
}

From source file:com.opengamma.integration.viewer.status.impl.ViewStatusCalculationTask.java

@Override
public PerViewStatusResult call() throws Exception {
    s_logger.debug("Start calculating result for security:{} with values{}", _securityType,
            Sets.newTreeSet(_valueRequirementNames).toString());

    final PerViewStatusResult statusResult = new PerViewStatusResult(_securityType);
    //No need to do any work if there are no ValueRequirements to compute
    if (_valueRequirementNames.isEmpty()) {
        return statusResult;
    }// w ww  .  j a v  a2  s . co m
    final ViewDefinition viewDefinition = createViewDefinition();
    final ViewProcessor viewProcessor = _toolContext.getViewProcessor();
    final ViewClient client = viewProcessor.createViewClient(_user);

    final CountDownLatch latch = new CountDownLatch(1);
    client.setResultListener(new ViewStatusResultListener(latch, statusResult, viewDefinition));
    client.attachToViewProcess(viewDefinition.getUniqueId(),
            ExecutionOptions.infinite(_marketDataSpecification));

    try {
        s_logger.info("main thread waiting");
        if (!latch.await(30, TimeUnit.SECONDS)) {
            s_logger.error("Timed out waiting for {}", viewDefinition);
        }
    } catch (final InterruptedException ex) {
        throw new OpenGammaRuntimeException("Interrupted while waiting for " + viewDefinition, ex);
    }
    client.detachFromViewProcess();
    removeViewDefinition(viewDefinition);
    s_logger.debug("PerViewStatusResult for securityType:{} is {}", _securityType, statusResult);
    return statusResult;
}

From source file:io.opentracing.contrib.elasticsearch5.TracingTest.java

@Test
public void restClient() throws Exception {
    RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http"))
            .setHttpClientConfigCallback(new TracingHttpClientConfigCallback(mockTracer)).build();

    HttpEntity entity = new NStringEntity(
            "{\n" + "    \"user\" : \"kimchy\",\n" + "    \"post_date\" : \"2009-11-15T14:12:12\",\n"
                    + "    \"message\" : \"trying out Elasticsearch\"\n" + "}",
            ContentType.APPLICATION_JSON);

    Response indexResponse = restClient.performRequest("PUT", "/twitter/tweet/1",
            Collections.<String, String>emptyMap(), entity);

    assertNotNull(indexResponse);/*from w w w. ja  v a  2  s  .c  o  m*/

    final CountDownLatch latch = new CountDownLatch(1);
    restClient.performRequestAsync("PUT", "/twitter/tweet/2", Collections.<String, String>emptyMap(), entity,
            new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    latch.countDown();
                }
            });

    latch.await(30, TimeUnit.SECONDS);
    restClient.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "PUT");
    assertNull(mockTracer.activeSpan());
}

From source file:org.kurento.test.base.BrowserKurentoClientTest.java

private void makeAssertions(String browserKey, String messageAppend, BrowserClient browser, int playtime, int x,
        int y, CountDownLatch eosLatch, Color... expectedColors) throws InterruptedException {
    Assert.assertTrue("Not received media in the recording (timeout waiting playing event) " + messageAppend,
            getBrowser(browserKey).waitForEvent("playing"));
    for (Color color : expectedColors) {
        Assert.assertTrue("The color of the recorded video should be " + color + " " + messageAppend,
                getBrowser(browserKey).similarColorAt(color, x, y));
    }// w  w  w  .j  a v a2 s .  c  o m

    if (eosLatch != null) {
        Assert.assertTrue("Not received EOS event in player", eosLatch.await(getTimeout(), TimeUnit.SECONDS));
    } else {
        Thread.sleep(playtime * 1000);
    }

    double currentTime = getBrowser(browserKey).getCurrentTime();
    Assert.assertTrue("Error in play time in the recorded video (expected: " + playtime + " sec, real: "
            + currentTime + " sec) " + messageAppend, getBrowser(browserKey).compare(playtime, currentTime));
}