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.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testChainedTask() throws Exception {
    TaskBase task = new SleepIncrementTask(100).andThen(new SleepIncrementTask(150))
            .andThen(new SleepIncrementTask(200)).getEntity();

    final CountDownLatch latch = new CountDownLatch(3);
    FIFOTaskQueue tq = new FIFOTaskQueue(10) {
        @Override// ww w  . ja v  a 2s.c om
        public boolean finishTask(final long id, final String output) {
            latch.countDown();
            return super.finishTask(id, output);
        }

        @Override
        public long finishTaskAndEnqueueRunningTask(final long id, final String output, final TaskBase newTask,
                final String worker) {
            latch.countDown();
            return super.finishTaskAndEnqueueRunningTask(id, output, newTask, worker);
        }
    };
    tq.enqueueTask(task, Integer.toString(++nameCounter), 0);

    Semaphore idleWorkersSemaphore = new Semaphore(2);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, tq);
    TaskDispatcher dispatcher = new TaskDispatcher(2, idleWorkersSemaphore, workerPool, tq);
    dispatcher.start();

    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(SleepIncrementTask.executionCounter.intValue(), 3);

    Assert.assertEquals(tq.getResult(0), "0");
    Assert.assertEquals(tq.getResult(1), "1");
    Assert.assertEquals(tq.getResult(2), "2");
    dispatcher.stop();
}

From source file:org.jboss.aerogear.test.api.sender.SenderRequest.java

public SenderRequest send(UnifiedMessage message, String pushApplicationId, String masterSecret) {
    DefaultPushSender.Builder senderBuilder = DefaultPushSender
            .withRootServerURL(getSession().getBaseUrl().toExternalForm()).pushApplicationId(pushApplicationId)
            .masterSecret(masterSecret);

    if (customTrustStorePath != null) {
        senderBuilder.customTrustStore(customTrustStorePath, customTrustStoreType, customTrustStorePassword);
    }//  w  w  w. j  a v  a2  s  .  com

    PushSender senderClient = senderBuilder.build();

    final CountDownLatch latch = new CountDownLatch(1);

    MessageResponseCallback callback = new MessageResponseCallback() {
        @Override
        public void onComplete() {
            latch.countDown();
        }
    };

    try {
        // The send is synchronous for now but I left the latch.await there in case the send becomes async again.
        senderClient.send(message, callback);
        latch.await(5000, TimeUnit.MILLISECONDS);
    } catch (PushSenderHttpException exception) {
        // In case we get the exception, we will assert it
        UnexpectedResponseException.verifyStatusCode(exception.getStatusCode(), HttpStatus.SC_ACCEPTED);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return this;
}

From source file:com.github.dozermapper.core.DozerBeanMapperTest.java

@Test
public void shouldBeThreadSafe() throws Exception {
    Mapper mapper = DozerBeanMapperBuilder.create().withMappingFiles("mappings/testDozerBeanMapping.xml")
            .build();// www  .  j a va2 s .c  om

    final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);

    for (int i = 0; i < THREAD_COUNT; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    mapper.map(new TestObject(), TestObjectPrime.class);
                } finally {
                    latch.countDown();
                }
            }
        }).start();

    }
    latch.await();
    assertTrue(exceptions.isEmpty());
}

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

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

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

From source file:com.test.database.jedis.TestJedisEvalLua.java

public static void testTryGetHongBao() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(threadCount);
    System.err.println("start:" + System.currentTimeMillis() / 1000);
    watch.start();//from   ww w.j  a  v a2s . co m
    for (int i = 0; i < threadCount; ++i) {
        final int temp = i;
        Thread thread = new Thread() {
            public void run() {
                String sha = null;
                Jedis jedis = new Jedis(host, port);
                sha = jedis.scriptLoad(tryGetHongBaoScript);
                if (temp == 0) {
                    System.err.println("SCRIPT SHA: " + sha);
                }
                int j = honBaoCount / threadCount * temp;
                while (true) {
                    // Object object = jedis.eval(tryGetHongBaoScript, 4,
                    // hongBaoList, hongBaoConsumedList,
                    // hongBaoConsumedMap, "" + j);
                    Object object = jedis.evalsha(sha, 4, hongBaoList, hongBaoConsumedList, hongBaoConsumedMap,
                            "" + j);
                    j++;
                    if (object != null) {
                        System.out.println("Get hongBao:" + object);
                    } else if (jedis.llen(hongBaoList) == 0) {
                        break;
                    }
                }
                latch.countDown();
                jedis.close();
            }
        };
        thread.start();
    }

    latch.await();
    watch.stop();

    System.err.println("time:" + watch.getTime() + " ms");
    System.err.println("speed:" + honBaoCount / watch.getTime());
    System.err.println("end:" + System.currentTimeMillis() / 1000);
}

From source file:com.pinterest.rocksplicator.controller.DispatcherTest.java

@Test
public void testChainedTaskWithError() throws Exception {
    TaskBase task = new SleepIncrementTask(100).andThen(new ThrowingTask("Oops..."))
            .andThen(new SleepIncrementTask(150)).getEntity();

    final CountDownLatch latch = new CountDownLatch(2);
    FIFOTaskQueue tq = new FIFOTaskQueue(10) {
        @Override/*from w  w  w .j a  v a2 s. co  m*/
        public boolean finishTask(final long id, final String output) {
            latch.countDown();
            return super.finishTask(id, output);
        }

        @Override
        public boolean failTask(final long id, final String reason) {
            latch.countDown();
            return super.failTask(id, reason);
        }

        @Override
        public long finishTaskAndEnqueueRunningTask(final long id, final String output, final TaskBase newTask,
                final String worker) {
            latch.countDown();
            return super.finishTaskAndEnqueueRunningTask(id, output, newTask, worker);
        }
    };
    tq.enqueueTask(task, Integer.toString(++nameCounter), 0);

    Semaphore idleWorkersSemaphore = new Semaphore(2);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, tq);
    TaskDispatcher dispatcher = new TaskDispatcher(2, idleWorkersSemaphore, workerPool, tq);
    dispatcher.start();

    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
    Assert.assertEquals(SleepIncrementTask.executionCounter.intValue(), 1);

    Assert.assertEquals(tq.getResult(0), "0");
    Assert.assertEquals(tq.getResult(1), "Oops...");
    dispatcher.stop();
}

From source file:com.netflix.curator.framework.recipes.queue.TestDistributedIdQueue.java

@Test
public void testDeletingWithLock() throws Exception {
    DistributedIdQueue<TestQueueItem> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();//from  w  w  w.ja v a2s  .  c  o  m
    try {
        final CountDownLatch consumingLatch = new CountDownLatch(1);
        final CountDownLatch waitLatch = new CountDownLatch(1);
        QueueConsumer<TestQueueItem> consumer = new QueueConsumer<TestQueueItem>() {
            @Override
            public void consumeMessage(TestQueueItem message) throws Exception {
                consumingLatch.countDown();
                waitLatch.await();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };

        queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks")
                .buildIdQueue();
        queue.start();

        queue.put(new TestQueueItem("test"), "id");

        Assert.assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it
        Assert.assertEquals(queue.remove("id"), 0);

        waitLatch.countDown();
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.linkedin.pinot.perf.QueryRunner.java

/**
 * Use multiple threads to run queries as fast as possible.
 *
 * Start {numThreads} worker threads to send queries (blocking call) back to back, and use the main thread to collect
 * the statistic information and log them periodically.
 *
 * @param conf perf benchmark driver config.
 * @param queryFile query file./*from  w  w  w.  java  2s  .c o m*/
 * @param numThreads number of threads sending queries.
 * @throws Exception
 */
@SuppressWarnings("InfiniteLoopStatement")
public static void multiThreadedsQueryRunner(PerfBenchmarkDriverConf conf, String queryFile,
        final int numThreads) throws Exception {
    final long randomSeed = 123456789L;
    final Random random = new Random(randomSeed);
    final int reportIntervalMillis = 3000;

    final List<String> queries;
    try (FileInputStream input = new FileInputStream(new File(queryFile))) {
        queries = IOUtils.readLines(input);
    }

    final int numQueries = queries.size();
    final PerfBenchmarkDriver driver = new PerfBenchmarkDriver(conf);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

    final DescriptiveStatistics stats = new DescriptiveStatistics();
    final CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < numQueries; j++) {
                    String query = queries.get(random.nextInt(numQueries));
                    long startTime = System.currentTimeMillis();
                    try {
                        driver.postQuery(query);
                        long clientTime = System.currentTimeMillis() - startTime;
                        synchronized (stats) {
                            stats.addValue(clientTime);
                        }

                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(clientTime);
                    } catch (Exception e) {
                        LOGGER.error("Caught exception while running query: {}", query, e);
                        return;
                    }
                }
                latch.countDown();
            }
        });
    }

    executorService.shutdown();

    int iter = 0;
    long startTime = System.currentTimeMillis();
    while (latch.getCount() > 0) {
        Thread.sleep(reportIntervalMillis);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        LOGGER.info("Time Passed: {}s, Query Executed: {}, QPS: {}, Avg Response Time: {}ms", timePassedSeconds,
                count, count / timePassedSeconds, avgResponseTime);

        iter++;
        if (iter % 10 == 0) {
            printStats(stats);
        }
    }

    printStats(stats);
}

From source file:edu.umn.msi.tropix.proteomics.cagrid.IntegrationTestBase.java

protected boolean pollJob(Job job) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    class Listener implements JobUpdateListener {
        private boolean finishedProperly = false;

        public void jobComplete(final Ticket ticket, final boolean finishedProperly, final Status finalStatus) {
            this.finishedProperly = finishedProperly;
            latch.countDown();
        }// w w  w .  java  2 s  .c o m

        public void update(final Ticket ticket, final Status status) {
            final QueueStage stage = QueueStage.fromStatusUpdateList(status);
            LOG.info("Queue stage is " + stage.getStageEnumerationValue().getValue());
        }
    }
    final Listener listener = new Listener();
    dListener.setJobUpdateListener(listener);
    jobPoller.pollJob(job);
    latch.await();
    return listener.finishedProperly;
}

From source file:ufo.remote.calls.benchmark.client.caller.activemq.ActiveMQTester.java

@Override
protected void startTest(final TesterResult result) {

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

    String url = ActiveMQApacheCamelConfig.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  www.  j  ava 2  s . c  om
            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();

}