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.bt.aloha.util.ConcurrentUpdateManagerTest.java

@Test
public void testConcurrentUpdateConflictAwawreExceptionAbsorbed() throws Exception {
    // setup/*from w  w  w . j a v  a 2 s.c  om*/
    final CountDownLatch firstWriterRead = new CountDownLatch(1);
    final CountDownLatch secondWriterWrote = new CountDownLatch(1);
    final AtomicInteger failuresCounter = new AtomicInteger();

    ConcurrentUpdateBlock concurrentUpdateBlock = new ConflictAwareConcurrentUpdateBlock() {
        public void execute() {
            DialogInfo di = dialogCollection.get(dialogId);
            log.debug("First writer read");
            firstWriterRead.countDown();

            di.setApplicationData("first");
            log.debug("Waiting for second writer to write");
            try {
                secondWriterWrote.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            dialogCollection.replace(di);
            log.debug("First writer replaced");
        }

        public String getResourceId() {
            return dialogId;
        }

        public void onConcurrentUpdateConflict() {
            failuresCounter.incrementAndGet();
            throw new RuntimeException("bugger off");
        }
    };

    Runnable competingWriter = new Runnable() {
        public void run() {
            log.debug("Waiting for first writer to read");
            try {
                firstWriterRead.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DialogInfo di = dialogCollection.get(dialogId);
            di.setApplicationData("second");
            dialogCollection.replace(di);
            log.debug("Second writer replaced");
            secondWriterWrote.countDown();
        }
    };

    // act
    new Thread(competingWriter).start();
    concurrentUpdateManager.executeConcurrentUpdate(concurrentUpdateBlock);

    // assert
    assertEquals(1, failuresCounter.get());
    assertEquals("first", dialogCollection.get(dialogId).getApplicationData());
}

From source file:com.fizzed.blaze.ssh.SshExec.java

@Override
protected Result doRun() throws BlazeException {
    Session jschSession = ((JschSession) session).getJschSession();
    ObjectHelper.requireNonNull(jschSession, "ssh session must be established first");
    ObjectHelper.requireNonNull(command, "ssh command cannot be null");

    ChannelExec channel = null;/*w w  w  .  j  a  va2 s .c om*/
    try {
        channel = (ChannelExec) jschSession.openChannel("exec");

        if (pty) {
            channel.setPty(true);
        }

        // setup environment
        if (this.environment != null) {
            for (Map.Entry<String, String> entry : this.environment.entrySet()) {
                log.debug("Adding env {}={}", entry.getKey(), entry.getValue());
                channel.setEnv(entry.getKey(), entry.getValue());
            }
        }

        // NOTE: In order for JSCH to pump the inputstream to its outputstream
        // it starts an "exec thread" for every channel-exec it creates
        // that also includes non-null inputstream. The problem is that
        // JSCH's exec thread will block forever on the inputstream.read()
        // call unless the inputstream is actually closed.  Since we don't
        // want that behavior, we'll sneakily introduce a wrapped inputstream
        // that will supply an interruptible read() call. This is done in
        // 2 steps:  1) our read() method will use a combo of Thread.sleep()
        // and available() to provide a non-blocking read() that will also
        // response to a Thread.interrupt() call.  and 2) we'll capture
        // a reference to JSCH's exec thread by saving it when it actually
        // enters the read() method.

        // setup in/out streams
        final InputStream is = (pipeInput != null ? new InterruptibleInputStream(pipeInput.stream()) : null);
        final OutputStream os = (pipeOutput != null ? pipeOutput.stream() : new NullOutputStream());
        final OutputStream es = (pipeErrorToOutput ? os
                : (pipeError != null ? pipeError.stream() : new NullOutputStream()));

        if (is != null) {
            channel.setInputStream(is, false);
        }

        // both streams closing signals exec is finished
        final CountDownLatch outputStreamClosedSignal = new CountDownLatch(1);
        final CountDownLatch errorStreamClosedSignal = new CountDownLatch(1);

        // determine final ouput and then wrap to monitor for close events
        if (os != null) {
            channel.setOutputStream(new WrappedOutputStream(os) {
                @Override
                public void close() throws IOException {
                    outputStreamClosedSignal.countDown();
                    super.close();
                }
            }, false);
        } else {
            outputStreamClosedSignal.countDown();
        }

        // determine final error and then wrap to monitor for close events
        if (es != null) {
            channel.setErrStream(new WrappedOutputStream(es) {
                @Override
                public void close() throws IOException {
                    errorStreamClosedSignal.countDown();
                    super.close();
                }
            }, false);
        } else {
            errorStreamClosedSignal.countDown();
        }

        // building the command may be a little tricky, not sure about spaces...
        final StringBuilder sb = new StringBuilder(PathHelper.toString(command));

        arguments.stream().forEach((arg) -> {
            sb.append(" ");
            // TODO: should we actually escape instead such as " " -> "\ "???
            if (arg.contains(" ")) {
                sb.append("'");
                sb.append(arg);
                sb.append("'");
            } else {
                sb.append(arg);
            }
        });

        String finalCommand = sb.toString();

        log.debug("ssh-exec [{}]", finalCommand);

        channel.setCommand(finalCommand);

        // this connects and sends command
        channel.connect();

        // wait for both streams to be closed
        outputStreamClosedSignal.await();
        errorStreamClosedSignal.await();

        Integer exitValue = channel.getExitStatus();

        if (!this.exitValues.contains(exitValue)) {
            throw new UnexpectedExitValueException("Process exited with unexpected value", this.exitValues,
                    exitValue);
        }

        return new Result(this, exitValue);
    } catch (JSchException | InterruptedException e) {
        throw new SshException(e.getMessage(), e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }

        /**
        // cleanup JSCH exec thread if it exists
        Thread execThread = execThreadRef.get();
        if (execThread != null) {
        log.trace("Interrupting thread [{}]", execThread.getName());
        execThread.interrupt();
        }
        */
    }
}

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

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

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

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

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

    String nextPageLink = "nextPageLink";

    ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2), nextPageLink, null);
    ResourceList<Task> taskResourceListNextPage = new ResourceList<>(Arrays.asList(task3));

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

    setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK);

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

    resourceTicketApi.getTasksForResourceTicketAsync("foo", new FutureCallback<ResourceList<Task>>() {
        @Override/*from   w  w w.  ja v a  2  s  .co  m*/
        public void onSuccess(@Nullable ResourceList<Task> result) {
            assertEquals(result.getItems().size(),
                    taskResourceList.getItems().size() + taskResourceListNextPage.getItems().size());
            assertTrue(result.getItems().containsAll(taskResourceList.getItems()));
            assertTrue(result.getItems().containsAll(taskResourceListNextPage.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 testGetResourceTicketTasksAsyncForPagination() throws IOException, InterruptedException {

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

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

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

    String nextPageLink = "nextPageLink";

    ResourceList<Task> taskResourceList = new ResourceList<>(Arrays.asList(task1, task2), nextPageLink, null);
    ResourceList<Task> taskResourceListNextPage = new ResourceList<>(Arrays.asList(task3));

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

    setupMocksForPagination(serializedTask, serializedTaskNextPage, nextPageLink, HttpStatus.SC_OK);

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

    resourceTicketApi.getTasksForResourceTicketAsync("foo", new FutureCallback<ResourceList<Task>>() {
        @Override/*from w w w.  ja  v a  2s. c o  m*/
        public void onSuccess(@Nullable ResourceList<Task> result) {
            assertEquals(result.getItems().size(),
                    taskResourceList.getItems().size() + taskResourceListNextPage.getItems().size());
            assertTrue(result.getItems().containsAll(taskResourceList.getItems()));
            assertTrue(result.getItems().containsAll(taskResourceListNextPage.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:io.kamax.mxisd.backend.firebase.GoogleFirebaseAuthenticator.java

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    if (!isEnabled()) {
        throw new IllegalStateException();
    }//from   www .  ja  va  2 s  .com

    log.info("Trying to authenticate {}", mxid);

    final BackendAuthResult result = BackendAuthResult.failure();

    String localpart = mxid.getLocalPart();
    CountDownLatch l = new CountDownLatch(1);
    getFirebase().verifyIdToken(password).addOnSuccessListener(token -> {
        try {
            if (!StringUtils.equals(localpart, token.getUid())) {
                log.info(
                        "Failure to authenticate {}: Matrix ID localpart '{}' does not match Firebase UID '{}'",
                        mxid, localpart, token.getUid());
                result.fail();
                return;
            }

            result.succeed(mxid.getId(), UserIdType.MatrixID.getId(), token.getName());
            log.info("{} was successfully authenticated", mxid);
            log.info("Fetching profile for {}", mxid);
            CountDownLatch userRecordLatch = new CountDownLatch(1);
            getFirebase().getUser(token.getUid()).addOnSuccessListener(user -> {
                try {
                    toEmail(result, user.getEmail());
                    toMsisdn(result, user.getPhoneNumber());

                    for (UserInfo info : user.getProviderData()) {
                        toEmail(result, info.getEmail());
                        toMsisdn(result, info.getPhoneNumber());
                    }

                    log.info("Got {} 3PIDs in profile", result.getProfile().getThreePids().size());
                } finally {
                    userRecordLatch.countDown();
                }
            }).addOnFailureListener(e -> {
                try {
                    log.warn("Unable to fetch Firebase user profile for {}", mxid);
                    result.fail();
                } finally {
                    userRecordLatch.countDown();
                }
            });

            waitOnLatch(result, userRecordLatch, "Firebase user profile");
        } finally {
            l.countDown();
        }
    }).addOnFailureListener(e -> {
        try {
            if (e instanceof IllegalArgumentException) {
                log.info("Failure to authenticate {}: invalid firebase token", mxid);
            } else {
                log.info("Failure to authenticate {}: {}", mxid, e.getMessage(), e);
                log.info("Exception", e);
            }

            result.fail();
        } finally {
            l.countDown();
        }
    });

    waitOnLatch(result, l, "Firebase auth check");
    return result;
}

From source file:org.apache.servicemix.http.ConsumerEndpointTest.java

public void testHttpInOutUnderLoad() throws Exception {
    final int nbThreads = 16;
    final int nbRequests = 8;
    final int endpointTimeout = 100;
    final int echoSleepTime = 90;
    final int soTimeout = 60 * 1000 * 1000;
    final int listenerTimeout = 5000;

    ExchangeCompletedListener listener = new ExchangeCompletedListener(listenerTimeout);
    container.addListener(listener);/* w w w .ja  v a  2  s .  com*/

    HttpComponent http = new HttpComponent();
    //http.getConfiguration().setJettyConnectorClassName(SocketConnector.class.getName());
    HttpConsumerEndpoint ep = new HttpConsumerEndpoint();
    ep.setService(new QName("urn:test", "svc"));
    ep.setEndpoint("ep");
    ep.setTargetService(new QName("urn:test", "echo"));
    ep.setLocationURI("http://localhost:8192/ep1/");
    ep.setTimeout(endpointTimeout);
    http.setEndpoints(new HttpEndpointType[] { ep });
    container.activateComponent(http, "http");

    final CountDownLatch latchRecv = new CountDownLatch(nbThreads * nbRequests);
    EchoComponent echo = new EchoComponent() {
        protected boolean transform(MessageExchange exchange, NormalizedMessage in, NormalizedMessage out)
                throws MessagingException {
            latchRecv.countDown();
            try {
                Thread.sleep(echoSleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            out.setContent(in.getContent());
            return true;
        }
    };
    echo.setService(new QName("urn:test", "echo"));
    echo.setEndpoint("endpoint");
    container.activateComponent(echo, "echo");

    ((ExecutorFactoryImpl) container.getExecutorFactory()).getDefaultConfig().setMaximumPoolSize(16);

    container.start();

    final List<Throwable> throwables = new CopyOnWriteArrayList<Throwable>();
    final CountDownLatch latchSent = new CountDownLatch(nbThreads * nbRequests);
    for (int t = 0; t < nbThreads; t++) {
        new Thread() {
            public void run() {
                final SourceTransformer transformer = new SourceTransformer();
                final HttpClient client = new HttpClient();
                client.getParams().setSoTimeout(soTimeout);
                for (int i = 0; i < nbRequests; i++) {
                    try {
                        PostMethod post = new PostMethod("http://localhost:8192/ep1/");
                        post.setRequestEntity(new StringRequestEntity("<hello>world</hello>"));
                        client.executeMethod(post);
                        if (post.getStatusCode() != 200) {
                            throw new InvalidStatusResponseException(post.getStatusCode());
                        }
                        Node node = transformer.toDOMNode(new StreamSource(post.getResponseBodyAsStream()));
                        log.info(transformer.toString(node));
                        assertEquals("world", textValueOfXPath(node, "/hello/text()"));
                    } catch (Throwable t) {
                        throwables.add(t);
                    } finally {
                        latchSent.countDown();
                        //System.out.println("[" + System.currentTimeMillis() + "] Request " + latch.getCount() + " processed");
                    }
                }
            }
        }.start();
    }
    latchSent.await();
    latchRecv.await();
    listener.assertExchangeCompleted();
    for (Throwable t : throwables) {
        t.printStackTrace();
    }
}

From source file:com.github.sdbg.debug.core.internal.webkit.protocol.WebkitRemoteObject.java

/**
 * Return the length of the list if this object is a list.
 * // w w  w  .  j av  a2s.c o m
 * @param webkitConnection
 * @return
 */
public int getListLength(WebkitConnection connection) {
    if (listLength == -1) {
        final CountDownLatch latch = new CountDownLatch(1);

        try {
            connection.getRuntime().callListLength(objectId, new WebkitCallback<Integer>() {
                @Override
                public void handleResult(WebkitResult<Integer> result) {
                    if (result.isError()) {
                        listLength = 0;
                    } else if (result.getResult() == null) {
                        listLength = 0;
                    } else {
                        listLength = result.getResult().intValue();
                    }

                    latch.countDown();
                }
            });
        } catch (IOException e) {
            listLength = 0;
            latch.countDown();
        }

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

        }
    }

    return listLength;
}

From source file:com.microsoft.office.integration.test.MessagesAsyncTestCase.java

public void testCreateInDefaultFolder() {
    try {//ww w.  j  a va2 s  . com
        message = Messages.newMessage();
        sourceMessage = getEntityFromResource("simpleMessage.json");
        String subject = sourceMessage.getProperty("Subject").getPrimitiveValue().toString();
        message.setSubject(subject);
        counter = new CountDownLatch(1);
        Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
            public void onFailure(Throwable t) {
                reportError(t);
                counter.countDown();
            }

            public void onSuccess(Void result) {
                try {
                    assertTrue(StringUtils.isNotEmpty(MessagesAsyncTestCase.this.message.getId()));
                    final CountDownLatch cdl = new CountDownLatch(1);
                    Futures.addCallback(Me.getDraftsAsync(), new FutureCallback<IFolder>() {
                        public void onFailure(Throwable t) {
                            reportError(t);
                            cdl.countDown();
                        }

                        public void onSuccess(IFolder result) {
                            assertEquals(MessagesAsyncTestCase.this.message.getParentFolderId(),
                                    result.getId());
                            cdl.countDown();
                        };
                    });

                    cdl.await();
                } catch (Throwable t) {
                    reportError(t);
                }
                counter.countDown();
            }
        });

        try {
            if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
                fail("testSize() timed out");
            }
        } catch (InterruptedException e) {
            fail("testSize() has been interrupted");
        }
    } finally {
        try {
            removeMessage();
        } catch (Exception e) {
            reportError(e);
        }
    }
}

From source file:com.twitter.distributedlog.admin.DistributedLogAdmin.java

private static Map<String, StreamCandidate> checkStreams(
        final com.twitter.distributedlog.DistributedLogManagerFactory factory, final Collection<String> streams,
        final ExecutorService executorService, final BookKeeperClient bkc, final String digestpw,
        final int concurrency) throws IOException {
    final LinkedBlockingQueue<String> streamQueue = new LinkedBlockingQueue<String>();
    streamQueue.addAll(streams);/*from  w  w  w.java2 s . c  o  m*/
    final Map<String, StreamCandidate> candidateMap = new ConcurrentSkipListMap<String, StreamCandidate>();
    final AtomicInteger numPendingStreams = new AtomicInteger(streams.size());
    final CountDownLatch doneLatch = new CountDownLatch(1);
    Runnable checkRunnable = new Runnable() {
        @Override
        public void run() {
            while (!streamQueue.isEmpty()) {
                String stream;
                try {
                    stream = streamQueue.take();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
                StreamCandidate candidate;
                try {
                    LOG.info("Checking stream {}.", stream);
                    candidate = checkStream(factory, stream, executorService, bkc, digestpw);
                    LOG.info("Checked stream {} - {}.", stream, candidate);
                } catch (IOException e) {
                    LOG.error("Error on checking stream {} : ", stream, e);
                    doneLatch.countDown();
                    break;
                }
                if (null != candidate) {
                    candidateMap.put(stream, candidate);
                }
                if (numPendingStreams.decrementAndGet() == 0) {
                    doneLatch.countDown();
                }
            }
        }
    };
    Thread[] threads = new Thread[concurrency];
    for (int i = 0; i < concurrency; i++) {
        threads[i] = new Thread(checkRunnable, "check-thread-" + i);
        threads[i].start();
    }
    try {
        doneLatch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    if (numPendingStreams.get() != 0) {
        throw new IOException(numPendingStreams.get() + " streams left w/o checked");
    }
    for (int i = 0; i < concurrency; i++) {
        threads[i].interrupt();
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    return candidateMap;
}

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

@Test
public void should_batch_counters_async() throws Exception {
    // Start batch
    AsyncBatch batch = asyncManager.createBatch();
    batch.startBatch();/*  w ww. j  a  v  a2  s.  co m*/

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

    entity = batch.insert(entity);

    entity.setLabel("label");

    Tweet welcomeTweet = TweetTestBuilder.tweet().randomId().content("welcomeTweet").buid();
    entity.setWelcomeTweet(welcomeTweet);

    entity.getVersion().incr(10L);
    batch.update(entity);

    RegularStatement selectLabel = select("label").from("CompleteBean").where(eq("id", entity.getId()));
    Map<String, Object> result = asyncManager.nativeQuery(selectLabel).getFirst().getImmediately();
    assertThat(result).isNull();

    RegularStatement selectCounter = select("counter_value").from("achilles_counter_table")
            .where(eq("fqcn", CompleteBean.class.getCanonicalName()))
            .and(eq("primary_key", entity.getId().toString())).and(eq("property_name", "version"));

    result = asyncManager.nativeQuery(selectCounter).getFirst().getImmediately();

    assertThat(result).isNull();

    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<Object> successSpy = new AtomicReference<>();
    final AtomicReference<Throwable> exceptionSpy = new AtomicReference<>();

    FutureCallback<Object> successCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            successSpy.getAndSet(result);
            latch.countDown();
        }

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

    FutureCallback<Object> errorCallBack = new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            exceptionSpy.getAndSet(t);
            latch.countDown();
        }
    };

    // Flush
    batch.asyncEndBatch(successCallBack, errorCallBack);

    latch.await();

    Statement statement = new SimpleStatement("SELECT label from CompleteBean where id=" + entity.getId());
    Row row = asyncManager.getNativeSession().execute(statement).one();
    assertThat(row.getString("label")).isEqualTo("label");

    result = asyncManager.nativeQuery(selectCounter).getFirst().getImmediately();
    assertThat(result.get("counter_value")).isEqualTo(10L);
    assertThatBatchContextHasBeenReset(batch);

    assertThat(successSpy.get()).isNotNull().isSameAs(Empty.INSTANCE);
    assertThat(exceptionSpy.get()).isNull();
}