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:ufo.remote.calls.benchmark.client.caller.hornetq.HornetQTester.java

@Override
protected void startTest(final TesterResult result) {

    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.setExecutorService(Executors.newFixedThreadPool(20));

    String url = HornetQApacheCamelConfig.JMS_NAME
            + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false";
    AtomicInteger failures = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(result.totalCalls);

    for (int i = 0; i < result.totalCalls; i++) {
        producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() {

            @Override//from   w  w w.ja  va  2s  .c o  m
            public void onFailure(final Exchange exchange) {
                failures.incrementAndGet();
                latch.countDown();
            }

            @Override
            public void onComplete(final Exchange exchange) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Received message [{}]", exchange.getIn().getBody());
                }
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();

}

From source file:com.github.sdbg.core.test.util.PlainTestProject.java

/**
 * Disposes allocated resources and deletes project.
 *//*from  w  ww .  ja  va 2 s .c o m*/
public void dispose() throws Exception {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();

    final CountDownLatch latch = new CountDownLatch(1);

    try {
        workspace.run(new IWorkspaceRunnable() {
            @Override
            public void run(IProgressMonitor monitor) throws CoreException {
                TestUtilities.deleteProject(project);
                latch.countDown();
            }
        }, null);
    } finally {
        latch.countDown();
    }

    latch.await();
}

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

private void readAndCheck() throws Exception {
    // reread a contact
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        public void onFailure(Throwable t) {
            reportError(t);/*  ww  w .j a  va  2  s  . c  o  m*/
            cdl.countDown();
        }

        public void onSuccess(IContact result) {
            contact = result;
            try {
                Class<?> cls = contact.getClass();
                Class<?>[] emptyParametersArray = new Class<?>[0];
                for (ODataProperty property : sourceContact.getProperties()) {
                    try {
                        Method getter = cls.getMethod("get" + property.getName(), emptyParametersArray);
                        assertEquals(property.getPrimitiveValue().toValue(), getter.invoke(contact));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:com.microsoft.office.core.EventsAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareEvent();//ww  w. ja v a 2  s . c o  m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(EventsAsyncTestCase.this.event.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });

    cdl.await();
}

From source file:com.microsoft.office.core.ContactsAsyncTestCase.java

private void deleteAndCheck() throws Exception {
    removeContact();//from   ww w .  j  a  v  a 2  s  .  c  o m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getContacts().getAsync(contact.getId()), new FutureCallback<IContact>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(IContact result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }
            cdl.countDown();
        }
    });
    cdl.await();
}

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

public void shutdown(final long maxWaitTime, final Handler<Boolean> shutdownHandler) {

    try {// w  w  w. j  a v  a 2s  . c  om
        final CountDownLatch latch = new CountDownLatch(1);
        if (vertx != null) {
            vertx.close(r -> {
                if (r.failed()) {
                    LOG.error("could not shut down '{}' adapter cleanly", this.getName(), r.cause());
                }
                latch.countDown();
            });
        }
        if (latch.await(maxWaitTime, TimeUnit.SECONDS)) {
            LOG.info("'{}' adapter shut down completed", this.getName());
            shutdownHandler.handle(Boolean.TRUE);
        } else {
            LOG.error("shut down of '{}' adapter timed out, aborting...", this.getName());
            shutdownHandler.handle(Boolean.FALSE);
        }
    } catch (InterruptedException e) {
        LOG.error("shut down of '{}' adapter has been interrupted, aborting...", this.getName());
        Thread.currentThread().interrupt();
        shutdownHandler.handle(Boolean.FALSE);
    }
}

From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java

@Test
public void collect_logs_in_parallel_for_two_containers() throws IOException, InterruptedException {
    when(compose.ps()).thenReturn(TestContainerNames.of("db", "db2"));
    CountDownLatch dbLatch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("log", outputStream);
        dbLatch.countDown();
        return true;
    });//ww  w.  jav a2  s  .com
    CountDownLatch db2Latch = new CountDownLatch(1);
    when(compose.writeLogs(eq("db2"), any(OutputStream.class))).thenAnswer((args) -> {
        OutputStream outputStream = (OutputStream) args.getArguments()[1];
        IOUtils.write("other", outputStream);
        db2Latch.countDown();
        return true;
    });

    logCollector.startCollecting(compose);
    assertThat(dbLatch.await(1, TimeUnit.SECONDS), is(true));
    assertThat(db2Latch.await(1, TimeUnit.SECONDS), is(true));

    assertThat(logDirectory.listFiles(),
            arrayContainingInAnyOrder(fileWithName("db.log"), fileWithName("db2.log")));
    assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log")));
    assertThat(new File(logDirectory, "db2.log"), is(fileContainingString("other")));

    logCollector.stopCollecting();
}

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

private void deleteAndCheck() throws Exception {
    removeEvent();/*  w  w w .j a v  a  2s  .c om*/
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.getEvents().getAsync(event.getId()), new FutureCallback<IEvent>() {
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        public void onSuccess(IEvent result) {
            try {
                assertNull(result);
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

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

@Test
public void testBasic() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {//from  ww w  .j  a  v a  2s .c  om
        client.start();

        final CountDownLatch latch = new CountDownLatch(3);
        final List<String> paths = Lists.newArrayList();
        BackgroundCallback callback = new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                paths.add(event.getPath());
                latch.countDown();
            }
        };
        client.create().inBackground(callback).forPath("/one");
        client.create().inBackground(callback).forPath("/one/two");
        client.create().inBackground(callback).forPath("/one/two/three");

        latch.await();

        Assert.assertEquals(paths, Arrays.asList("/one", "/one/two", "/one/two/three"));
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:org.cleverbus.core.common.asynch.confirm.ConfirmationPollExecutorTest.java

@Test
public void testGetNextMessage_moreThreads() throws InterruptedException {
    // firstly commit messages to DB (we can commit because we have embedded DB for tests only)
    TransactionTemplate txTemplate = new TransactionTemplate(jpaTransactionManager);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override//from  w w  w .ja  v  a  2 s.  com
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Message msg = insertNewMessage("1234_4567");
            confirmationService.insertFailedConfirmation(msg);

            msg = insertNewMessage("1234_4567_8");
            confirmationService.insertFailedConfirmation(msg);

            msg = insertNewMessage("1234_4567_9");
            confirmationService.insertFailedConfirmation(msg);
        }
    });

    // prepare threads
    int threads = 5;
    final CountDownLatch latch = new CountDownLatch(threads);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                pollExecutor.run();
            } finally {
                latch.countDown();
            }
        }
    };

    mock.expectedMessageCount(3);

    // start processing and waits for result
    for (int i = 0; i < threads; i++) {
        new Thread(task).start();
    }

    latch.await();

    mock.assertIsSatisfied();

    // verify messages
    ExternalCall extCall1 = findConfirmation("1234_4567");
    assertThat(extCall1, notNullValue());
    assertThat(extCall1.getState(), is(ExternalCallStateEnum.PROCESSING));

    ExternalCall extCall2 = findConfirmation("1234_4567_8");
    assertThat(extCall2, notNullValue());
    assertThat(extCall2.getState(), is(ExternalCallStateEnum.PROCESSING));

    ExternalCall extCall3 = findConfirmation("1234_4567_9");
    assertThat(extCall3, notNullValue());
    assertThat(extCall3.getState(), is(ExternalCallStateEnum.PROCESSING));

    // check confirmationService
    confirmationService.confirmationFailed(extCall1);
    extCall1 = findConfirmation("1234_4567");
    assertThat(extCall1.getState(), is(ExternalCallStateEnum.FAILED));

    confirmationService.confirmationComplete(extCall2);
    extCall2 = findConfirmation("1234_4567_8");
    assertThat(extCall2.getState(), is(ExternalCallStateEnum.OK));
}