Example usage for java.util.concurrent CountDownLatch CountDownLatch

List of usage examples for java.util.concurrent CountDownLatch CountDownLatch

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch CountDownLatch.

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:thingynet.cache.CacheClientService.java

void waitForCachePut(CacheClient client) throws InterruptedException {
    rwl.writeLock().lock();/* w  w w . j a  v a2s .  c om*/
    CountDownLatch latch = latches.get(client.getCacheKey());
    if (latch == null) {
        latch = new CountDownLatch(1);
        latches.put(client.getCacheKey(), latch);
        // TODO fix            workflowService.createReadyNow("CachePut", client.getCachePutNode().getName(), client.getCachePutContext());
    }
    rwl.writeLock().unlock();
    latch.await();
}

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

public void testRead() {
    prepareFolder();/*from   w  ww.java 2 s .  c o m*/
    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 {
                FoldersAsyncTestCase.this.readAndCheck();
                FoldersAsyncTestCase.this.removeFolder();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

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

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedDoubleBarrier.java

@Test
public void testMultiClient() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch postEnterLatch = new CountDownLatch(QTY);
    final CountDownLatch postLeaveLatch = new CountDownLatch(QTY);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger max = new AtomicInteger(0);
    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < QTY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override/*from   ww w .j  a  va  2s.  co m*/
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        timing.session(), timing.connection(), new RetryOneTime(1));
                try {
                    client.start();
                    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                    Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                    synchronized (TestDistributedDoubleBarrier.this) {
                        int thisCount = count.incrementAndGet();
                        if (thisCount > max.get()) {
                            max.set(thisCount);
                        }
                    }

                    postEnterLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                    Assert.assertEquals(count.get(), QTY);

                    Assert.assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS));
                    count.decrementAndGet();

                    postLeaveLatch.countDown();
                    Assert.assertTrue(timing.awaitLatch(postEnterLatch));
                } finally {
                    IOUtils.closeQuietly(client);
                }

                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> f : futures) {
        f.get();
    }
    Assert.assertEquals(count.get(), 0);
    Assert.assertEquals(max.get(), QTY);
}

From source file:org.eclipse.hono.example.ExampleSender.java

/**
 * Connects to the Hono server./*from  w  w w.jav  a 2 s.  co m*/
 */
@PostConstruct
public void prepare() {

    LOG.info("starting sender");
    final CountDownLatch startup = new CountDownLatch(1);
    ctx = vertx.getOrCreateContext();
    final Future<RegistrationResult> startupTracker = Future.future();
    startupTracker.setHandler(done -> {
        if (done.succeeded()) {
            startup.countDown();
        } else {
            LOG.error("Error occurred during initialization: {}", done.cause().getMessage());
        }
    });

    ctx.runOnContext(go -> {
        /* step 1: connect Hono client */
        final Future<HonoClient> connectionTracker = Future.future();
        client.connect(getClientOptions(), connectionTracker.completer());
        connectionTracker.compose(v -> {
            /* step 2: create a registration client */
            return getRegistrationClient();
        }).compose(regClient -> {
            /* step 3: register a device */
            Future<RegistrationResult> regResultTracker = Future.future();
            regClient.register(deviceId, null, regResultTracker.completer());
            return regResultTracker;
        }).compose(regResult -> {
            /* step 4: handle result of registration */
            if (regResult.getStatus() == HTTP_CREATED || regResult.getStatus() == HTTP_CONFLICT) {
                LOG.info("device registered");
                startupTracker.complete();
            } else {
                startupTracker.fail(String.format("Failed to register device [%s]: %s", deviceId, regResult));
            }
        }, startupTracker);
    });

    try {
        if (!startup.await(5, TimeUnit.SECONDS)) {
            LOG.error("shutting down");
            vertx.close();
        }
    } catch (InterruptedException e) {
        // nothing to do
    }
}

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

@Test
public void testLoad() throws Exception {
    EmbeddedConnection subConnection = new EmbeddedConnection(jNatsd);
    subConnection.start();//  w  w  w .j  av a2  s .  c  om
    final int count = 1000;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    subConnection.addSubscriber("foo", msg -> {
        countDownLatch.countDown();
    });

    EmbeddedConnection pubConnection = new EmbeddedConnection(jNatsd);
    pubConnection.start();

    long start = System.currentTimeMillis();

    for (int i = 0; i < count; i++) {
        String test = "Test" + i;
        pubConnection.publish("foo", "bah", test.getBytes());
    }

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

    long finish = System.currentTimeMillis();

    long totalTime = finish - start;

    int messagesPerSecond = (int) ((count * 1000) / totalTime);

    System.err.println("Duration to pub/sub " + count + " messages = " + totalTime + " ms = "
            + messagesPerSecond + " msg/sec");
    pubConnection.close();
    subConnection.close();
}

From source file:com.alibaba.rocketmq.storm.domain.BatchMessage.java

public BatchMessage(List<MessageExt> msgList, MessageQueue mq) {
    this.msgList = msgList;
    this.mq = mq;

    this.batchId = UUID.randomUUID();
    this.latch = new CountDownLatch(1);
    this.isSuccess = false;
}

From source file:net.sf.jasperreports.phantomjs.ProcessOutputReader.java

public ProcessOutputReader(PhantomJSProcess process) {
    this.process = process;
    this.processId = process.getId();
    this.startLatch = new CountDownLatch(1);
}

From source file:com.adaptris.core.jms.MockJmsConnectionErrorHandler.java

@Override
public void init() throws CoreException {
    String loggingId = retrieveConnection(AdaptrisConnection.class).getUniqueId();
    if (!isEmpty(loggingId)) {
        idForLogging = loggingId;//from w  w  w  . j  a  va 2 s.  c om
    } else {
        idForLogging = abbreviate(retrieveConnection(JmsConnection.class).getBrokerDetailsForLogging(), 20);
    }
    try {
        String s = "MockJmsConnectionErrorHandler";
        final String idForLogging = abbreviate(s, 20);
        MyExceptionHandler handler = new MyExceptionHandler();
        verifier = new MockJmsConnectionVerifier(idForLogging, new CountDownLatch(1));
        if (callback != null) {
            callback.register(verifier);
        }
        Thread verifierThread = new Thread(verifier);
        verifierThread.setUncaughtExceptionHandler(handler);
        verifierThread.start();
        if (additionalLogging()) {
            log.debug("ActiveJmsConnectionErrorHandler for " + idForLogging + " started");
        }
    } catch (Exception e) {
        throw new CoreException(e);
    }
}

From source file:com.github.oscerd.camel.cassandra.embedded.CassandraBaseTest.java

@Override
public void doPostSetup() {
    String id = RandomStringUtils.random(12, "0123456789abcdefghijklmnopqrstuvwxyz");
    fs = new Farsandra();
    fs.withVersion("2.0.3");
    fs.withCleanInstanceOnStart(true);// w ww  .  j a  v a2  s.  co m
    fs.withInstanceName("target" + File.separator + id);
    fs.withCreateConfigurationFiles(true);
    fs.withHost("localhost");
    fs.withSeeds(Arrays.asList("localhost"));
    final CountDownLatch started = new CountDownLatch(1);
    fs.getManager().addOutLineHandler(new LineHandler() {
        @Override
        public void handleLine(String line) {
            if (line.contains("Listening for thrift clients...")) {
                started.countDown();
            }
        }
    });
    fs.getManager().addProcessHandler(new ProcessHandler() {
        @Override
        public void handleTermination(int exitValue) {
            started.countDown();
        }
    });
    fs.start();
    try {
        started.await();
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS simplex WITH replication "
            + "= {'class':'SimpleStrategy', 'replication_factor':3};");
    session.execute("CREATE TABLE IF NOT EXISTS simplex.airport (" + "id int PRIMARY KEY," + "ident text,"
            + "type text," + "name text," + "latitude_deg float," + "longitude_deg float," + "elevation_ft int,"
            + "continent text," + "iso_country text," + "iso_region text," + "municipality text,"
            + "scheduled_service text," + "gps_code text," + "iata_code text," + "local_code text,"
            + "home_link text," + "wikipedia_link text," + "keywords text," + ");");
    session.execute("CREATE INDEX IF NOT EXISTS name_idx ON simplex.airport(name);");
    session.execute("CREATE INDEX IF NOT EXISTS continent_idx ON simplex.airport(continent);");
    session.close();
    cluster.close();
    try {
        Thread.sleep(5 * 1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:camelinaction.RiderAutoPartsCallbackTest.java

@Test
public void testCallback() throws Exception {
    // related is the list of related items
    final List<String> relates = new ArrayList<String>();

    // latch to count down every time we got a reply
    final CountDownLatch latch = new CountDownLatch(numPartners);

    // use this callback to gather the replies and add it to the related list
    Synchronization callback = new SynchronizationAdapter() {
        @Override// ww  w  . ja v a  2 s.com
        public void onComplete(Exchange exchange) {
            // get the reply and add it to related
            String body = exchange.getOut().getBody(String.class);
            relates.add(body);

            log.info("Get async reply {}", body);

            // count down the latch
            latch.countDown();
        }

        @Override
        public void onFailure(Exchange exchange) {
            // count down the latch even if we failed
            latch.countDown();
        }
    };

    // send the same message to the business partners so they can return their feedback
    String body = "bumper";
    for (int i = 0; i < numPartners; i++) {
        template.asyncCallbackRequestBody("seda:partner:" + i, body, callback);
    }
    LOG.info("Send " + numPartners + " messages to partners.");

    // wait at most 2 seconds or until we got all replies
    boolean all = latch.await(2000, TimeUnit.MILLISECONDS);

    // log what we got as reply
    LOG.info("Got " + relates.size() + " replies, is all? " + all);
    for (String related : relates) {
        LOG.info("Related item category is: " + related);
    }

    // assert the unit test
    assertEquals(3, relates.size());
    assertEquals("bumper extension", relates.get(0));
    assertEquals("bumper filter", relates.get(1));
    assertEquals("bumper cover", relates.get(2));
}