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:net.javacrumbs.futureconverter.common.test.spring.SpringConvertedFutureTestHelper.java

@Override
public void waitForCalculationToFinish(ListenableFuture<String> convertedFuture) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    convertedFuture.addCallback(new ListenableFutureCallback<String>() {
        @Override/*  www.  jav a 2  s  . c  om*/
        public void onSuccess(String result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    });
    latch.await(1, TimeUnit.SECONDS);
}

From source file:com.facebook.LinkBench.LinkBenchDriverInj.java

/**
 * Start all runnables at the same time. Then block till all
 * tasks are completed. Returns the elapsed time (in millisec)
 * since the start of the first task to the completion of all tasks.
 *//*from   www .  j  av  a  2 s .  c  om*/
static long concurrentExec(final List<? extends Runnable> tasks, boolean runReq, Random rng) throws Throwable {
    final CountDownLatch startSignal = new CountDownLatch(tasks.size());
    final CountDownLatch doneSignal = new CountDownLatch(tasks.size());
    final AtomicLong startTime = new AtomicLong(0);
    for (final Runnable task : tasks) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                /*
                 * Run a task.  If an uncaught exception occurs, bail
                 * out of the benchmark immediately, since any results
                 * of the benchmark will no longer be valid anyway
                 */
                try {
                    startSignal.countDown();
                    startSignal.await();
                    long now = System.currentTimeMillis();
                    startTime.compareAndSet(0, now);
                    task.run();
                } catch (Throwable e) {
                    Logger threadLog = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER);
                    threadLog.error("Unrecoverable exception in worker thread:", e);
                    Runtime.getRuntime().halt(1);
                }
                doneSignal.countDown();
            }
        }).start();
    }

    if (runReq) {
        /* Do logic with injection rate. All tasks above should be waiting on tasks */
        long reqTime_ns = System.nanoTime();
        double requestrate_ns = ((double) requestrate) / 1e9;
        long numRequests = ConfigUtil.getLong(props, Config.NUM_REQUESTS);
        System.out.println("Processing Requests:" + genQueue);

        try {
            long runStartTime = System.currentTimeMillis();
            long curTime = runStartTime;
            for (int i = 0; i < numRequests; i++) {

                reqTime_ns = Timer.waitExpInterval(rng, reqTime_ns, requestrate_ns);
                //       System.out.println("Request time: "+System.currentTimeMillis());
                genQueue.put(System.nanoTime());
                curTime = System.currentTimeMillis();
                if (curTime > runStartTime + maxTime * 1000) {
                    System.out.println("Time limit elapsed");
                    break;
                }
            }

            // Send stop signal to all requesters
            for (int i = 0; i < nrequesters; i++) {
                genQueue.put((long) 0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    doneSignal.await(); // wait for all threads to finish
    long endTime = System.currentTimeMillis();
    return endTime - startTime.get();
}

From source file:siia.booking.integration.FlightNotificationsSpelTest.java

private Answer countsDownLatch(final CountDownLatch notifierInvoked) {
    return new Answer() {
        @Override/*from w  w  w . j  a v  a2s. c  o m*/
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            notifierInvoked.countDown();
            return null;
        }
    };
}

From source file:org.eclipse.hono.event.impl.ForwardingEventDownstreamAdapterTest.java

@Test
public void testProcessMessageForwardsEventMessageToDownstreamSender() throws InterruptedException {

    final Vertx vertx = mock(Vertx.class);
    final UpstreamReceiver client = newClient();
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final ProtonDelivery downstreamDelivery = mock(ProtonDelivery.class);
    when(downstreamDelivery.getRemoteState()).thenReturn(ACCEPTED);
    when(downstreamDelivery.remotelySettled()).thenReturn(true);

    // GIVEN an adapter with a connection to a downstream container
    final CountDownLatch latch = new CountDownLatch(1);
    ProtonSender sender = newMockSender(false);
    when(sender.send(any(Message.class), any(Handler.class))).then(invocation -> {
        latch.countDown();
        invocation.getArgumentAt(1, Handler.class).handle(downstreamDelivery);
        return null;
    });//  ww  w .j a v  a  2 s.com
    ForwardingEventDownstreamAdapter adapter = new ForwardingEventDownstreamAdapter(vertx,
            newMockSenderFactory(sender));
    adapter.setDownstreamConnectionFactory(newMockConnectionFactory(false));
    adapter.start(Future.future());
    adapter.addSender(client, sender);

    // WHEN processing an event
    Message msg = ProtonHelper.message(EVENT_MSG_CONTENT);
    MessageHelper.addDeviceId(msg, DEVICE_ID);
    adapter.processMessage(client, delivery, msg);

    // THEN the message has been delivered to the downstream container
    assertTrue(latch.await(1, TimeUnit.SECONDS));
    // and disposition was returned
    verify(delivery).disposition(ACCEPTED, true);
}

From source file:ch.cyberduck.core.http.DelayedHttpMultipartEntity.java

public void writeTo(final OutputStream out) throws IOException {
    try {//from   w  ww .j  a  v  a 2  s.co m
        stream = new OutputStream() {
            private final AtomicBoolean close = new AtomicBoolean();

            @Override
            public void write(final byte[] b, final int off, final int len) throws IOException {
                out.write(b, off, len);
            }

            @Override
            public void write(final int b) throws IOException {
                out.write(b);
            }

            @Override
            public void write(final byte[] b) throws IOException {
                out.write(b);
            }

            @Override
            public void close() throws IOException {
                if (close.get()) {
                    log.warn(String.format("Skip double close of stream %s", this));
                    return;
                }
                try {
                    out.write(footer);
                    super.close();
                } finally {
                    // Signal finished writing to stream
                    exit.countDown();
                    close.set(true);
                }
            }
        };
        stream.write(header);
    } finally {
        final CountDownLatch entry = this.getEntry();
        // Signal stream is ready for writing
        entry.countDown();
    }
    // Wait for signal when content has been written to the pipe
    try {
        exit.await();
    } catch (InterruptedException e) {
        log.error(String.format("Error waiting for exit signal %s", e.getMessage()));
        throw new IOException(e);
    }
    // Entity written to server
    consumed = true;
}

From source file:com.ericsson.gerrit.plugins.highavailability.index.AbstractIndexForwardingIT.java

@Test
@UseLocalDisk// w  ww.  ja v  a 2 s.  c o  m
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void testIndexForwarding() throws Exception {
    String expectedRequest = getExpectedRequest();
    CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(expectedRequest)) {
            expectedRequestLatch.countDown();
        }
    });
    givenThat(post(urlEqualTo(expectedRequest)).willReturn(aResponse().withStatus(HttpStatus.SC_NO_CONTENT)));
    doAction();
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(expectedRequest)));
}

From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java

@After
public void tearDown() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    Platform.runLater(() -> {/*from  www . ja v a2s .co  m*/
        if (tempWatcher.cancel()) {
            latch.countDown();
        }
    });
    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("Service failed to stop");
    }
    // give watchers some time to wind down recursively
    Thread.sleep(1000L);
    cleanupRecursive(directories.getRoot());
}

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

@Test
public void testNullPayload() throws Exception {
    Connection connection = connectionFactory.createConnection();
    final int count = 100;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = connection.subscribe("foo", new MessageHandler() {
        @Override//  ww w .j  a v  a  2  s  .c o m
        public void onMessage(Message message) {
            countDownLatch.countDown();
        }
    });

    for (int i = 0; i < count; i++) {
        connection.publish("foo", null);
    }

    countDownLatch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    connection.close();
}

From source file:hudson.plugins.mercurial.MercurialContainer.java

@SuppressWarnings("deprecation")
public Slave createSlave(JenkinsRule r) throws Exception {
    DumbSlave slave = new DumbSlave("slave" + r.jenkins.getNodes().size(), "dummy", "/home/test/slave", "1",
            Node.Mode.NORMAL, "mercurial", new SSHLauncher(ipBound(22), port(22), "test", "test", "", ""),
            RetentionStrategy.INSTANCE, Collections.<NodeProperty<?>>emptyList());
    r.jenkins.addNode(slave);/*from  w w  w.j  a  v  a2  s  .c o  m*/
    // Copied from JenkinsRule:
    final CountDownLatch latch = new CountDownLatch(1);
    ComputerListener waiter = new ComputerListener() {
        @Override
        public void onOnline(Computer C, TaskListener t) {
            latch.countDown();
            unregister();
        }
    };
    waiter.register();
    latch.await();
    return slave;
}

From source file:ninja.eivind.hotsreplayuploader.ClientTest.java

@Test
public void testJavaFXIsAvailable() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(2);
    Task<Void> javaFxTask = new Task<Void>() {
        @Override//from  ww  w. j  av  a 2  s .co m
        protected Void call() throws Exception {
            latch.countDown();
            return null;
        }
    };
    javaFxTask.setOnSucceeded((result) -> latch.countDown());
    new Thread(javaFxTask).run();

    if (!latch.await(1, TimeUnit.SECONDS)) {
        fail("JavaFX is not available.");
    }
}