Example usage for java.util.concurrent CountDownLatch getCount

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

Introduction

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

Prototype

public long getCount() 

Source Link

Document

Returns the current count.

Usage

From source file:org.bpmscript.correlation.hibernate.HibernateCorrelationServiceTest.java

/**
 * Test method for {@link org.bpmscript.correlation.hibernate.HibernateCorrelationService#send(java.lang.Object)}.
 * @throws Exception /*from  w ww .j a v  a2s  .  c  om*/
 */
public void testSend() throws Exception {
    final int total = 1;
    final int criteriaTotal = 1;
    final CountDownLatch latch = new CountDownLatch(total);
    //final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    HibernateCorrelationServiceTestSupport testSupport = new HibernateCorrelationServiceTestSupport(
            new ICorrelationChannel() {

                public void send(Serializable replyToken, Object message) {
                    assertEquals("replyToken", replyToken);
                    log.info(latch.getCount());
                    latch.countDown();
                }

                public Object getContent(Object message) {
                    return null;
                }

            });
    testSupport.execute(new ITestCallback<IServiceLookup>() {
        public void execute(IServiceLookup services) throws Exception {
            final HibernateCorrelationService correlationService = services.get("correlationService");
            {
                Correlation correlation = new Correlation();
                correlation.addCriteria("message", "Hello World!");
                correlation.addCriteria("message.length", 12);
                correlation.addCriteria("message[0]", "H");
                correlationService.addCorrelation("channel", "groupId", "correlationId", "replyToken",
                        correlation, 1000000);
            }
            for (int i = 0; i < criteriaTotal; i++) {
                Correlation correlation = new Correlation();
                correlation.addCriteria("message", "Hello World! " + i);
                correlation.addCriteria("message.length", i);
                correlation.addCriteria("message[0]", "H");
                correlationService.addCorrelation("channel", "groupId", "correlationId", "replyToken " + i,
                        correlation, 1000000);
            }
            log.info("created all messages");

            IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
                public void execute(int count) throws Exception {
                    correlationService.send("channel", "Hello World!");
                }
            }, new IWaitForCallback() {
                public void call() throws Exception {
                    latch.await(360, TimeUnit.SECONDS);
                }
            }, false));
        }
    });
}

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

@Test
public void testLoad() throws Exception {
    EmbeddedConnection subConnection = new EmbeddedConnection(jNatsd);
    subConnection.start();/*from w  ww.j a v  a2 s .  c  o m*/
    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.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  ww .  j a va  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:org.apache.hadoop.hbase.procedure2.TestProcedureInMemoryChore.java

@Test
public void testChoreAddAndRemove() throws Exception {
    final int timeoutMSec = 50;
    final int nCountDown = 5;

    // submit the chore and wait for execution
    CountDownLatch latch = new CountDownLatch(nCountDown);
    TestLatchChore chore = new TestLatchChore(timeoutMSec, latch);
    procExecutor.addChore(chore);//from   www  . jav  a  2s.co m
    assertTrue(chore.isRunnable());
    latch.await();

    // remove the chore and verify it is no longer executed
    assertTrue(chore.isRunnable());
    procExecutor.removeChore(chore);
    latch = new CountDownLatch(nCountDown);
    chore.setLatch(latch);
    latch.await(timeoutMSec * nCountDown, TimeUnit.MILLISECONDS);
    LOG.info("chore latch count=" + latch.getCount());
    assertFalse(chore.isRunnable());
    assertTrue("latchCount=" + latch.getCount(), latch.getCount() > 0);
}

From source file:io.fabric8.maven.core.service.openshift.OpenshiftBuildService.java

private void waitUntilBuildFinished(CountDownLatch latch) {
    while (latch.getCount() > 0L) {
        try {/*from   w ww. j av  a  2s  .c  om*/
            latch.await();
        } catch (InterruptedException e) {
            // ignore
        }
    }
}

From source file:com.doctor.esper.reference_5_2_0.Chapter21Performance.java

/**
 * We recommend using multiple threads to send events into Esper. We provide a test class below. Our test class does not use a blocking queue and thread pool so as to avoid a point of contention.
 * /*  w w w.  java  2s.  co  m*/
 * ???Esper??
 * 
 * 
 * We recommend using Java threads as test_testing_performance_with_multiple_threads() , or a blocking queue and thread pool with sendEvent() or alternatively we recommend configuring inbound threading if your application does not already employ threading. Esper provides the configuration
 * option to use engine-level queues and threadpools for inbound, outbound and internal executions. See Section 15.7.1, Advanced Threading? for more information.
 * 
 * ?http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#config-engine-threading
 * 
 * @throws InterruptedException
 */
@Test
public void test_testing_performance_with_multiple_threads() throws InterruptedException {
    int numEvents = 1000000;
    int numThreads = 3;
    Thread[] threads = new Thread[numThreads];
    CountDownLatch countDownLatch = new CountDownLatch(numThreads);

    int eventPerThreads = numEvents / numThreads;
    for (int i = 0; i < numThreads; i++) {
        threads[i] = new Thread(new MyRunnable(countDownLatch, eventPerThreads, esperTemplateBean));
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < numThreads; i++) {
        threads[i].start();
    }
    countDownLatch.await(10, TimeUnit.MINUTES);
    if (countDownLatch.getCount() > 0) {
        throw new RuntimeException("Failed to complete in 10 minute");
    }

    System.out.println("Took " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "milliseconds ");
}

From source file:fi.jumi.core.stdout.OutputCapturerTest.java

/**
 * {@link Throwable#printStackTrace} synchronizes on {@code System.err}, but it can still interleave with something
 * that is printed to {@code System.out}. We can fix that by synchronizing all printing on {@code System.err}, but
 * only in one direction; the output from {@code Throwable.printStackTrace(System.out)} may still interleave with
 * printing to {@code System.err}.//from ww  w. j  ava  2 s  .c o  m
 */
@Test
public void printing_a_stack_trace_to_stderr_and_normally_to_stdout_concurrently() throws Exception {
    CountDownLatch isPrintingToOut = new CountDownLatch(1);
    CountDownLatch hasPrintedStackTrace = new CountDownLatch(1);
    Exception exception = new Exception("dummy exception");
    CombinedOutput combinedOutput = new CombinedOutput();
    capturer.captureTo(combinedOutput);

    runConcurrently(() -> {
        await(isPrintingToOut);
        exception.printStackTrace(capturer.err());
        hasPrintedStackTrace.countDown();
    }, () -> {
        while (hasPrintedStackTrace.getCount() > 0) {
            capturer.out().println("*garbage*");
            isPrintingToOut.countDown();
        }
    });

    assertThat(combinedOutput.toString(), containsString(Throwables.getStackTraceAsString(exception)));
}

From source file:com.cuddlesoft.nori.test.database.APISettingsDatabaseTest.java

/** Test if the database sends a Broadcast to the {@link android.support.v4.content.LocalBroadcastManager} when the data is changed. */
public void testUpdateBroadcast() throws Throwable {
    // Create a lock that waits for the broadcast to be received in the background.
    final CountDownLatch lock = new CountDownLatch(3);

    runTestOnUiThread(new Runnable() {
        @Override//from   w  w w  .  java 2s .  c o m
        public void run() {
            // Register BroadcastReceiver.
            LocalBroadcastManager.getInstance(context).registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    lock.countDown(); // Should receive 3 Broadcasts, one for each database operation.
                    if (lock.getCount() == 0) {
                        // Unregister broadcast receiver.
                        LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
                    }
                }
            }, new IntentFilter(APISettingsDatabase.BROADCAST_UPDATE));
            // Trigger database change broadcasts.
            APISettingsDatabase database = new APISettingsDatabase(context);
            long rowID = database.insert(new SearchClient.Settings(SearchClient.Settings.APIType.DANBOORU,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.update(rowID, new SearchClient.Settings(SearchClient.Settings.APIType.DANBOORU_LEGACY,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.delete(rowID);
            database.close();
        }
    });

    // Wait 10 seconds for the test to complete.
    lock.await(10, TimeUnit.SECONDS);
    assertThat(lock.getCount()).isEqualTo(0);
}

From source file:io.github.tjg1.nori.test.database.APISettingsDatabaseTest.java

/** Test if the database sends a Broadcast to the {@link android.support.v4.content.LocalBroadcastManager} when the data is changed. */
public void testUpdateBroadcast() throws Throwable {
    // Create a lock that waits for the broadcast to be received in the background.
    final CountDownLatch lock = new CountDownLatch(3);

    runTestOnUiThread(new Runnable() {
        @Override/*from w  w w.j  a v  a  2 s .  c  om*/
        public void run() {
            // Register BroadcastReceiver.
            LocalBroadcastManager.getInstance(context).registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    lock.countDown(); // Should receive 3 Broadcasts, one for each database operation.
                    if (lock.getCount() == 0) {
                        // Unregister broadcast receiver.
                        LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
                    }
                }
            }, new IntentFilter(APISettingsDatabase.BROADCAST_UPDATE));
            // Trigger database change broadcasts.
            APISettingsDatabase database = new APISettingsDatabase(context);
            long rowID = database.insert(new SearchClient.Settings(SearchClient.Settings.APIType.DANBOARD,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.update(rowID, new SearchClient.Settings(SearchClient.Settings.APIType.DANBOARD_LEGACY,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.delete(rowID);
            database.close();
        }
    });

    // Wait 10 seconds for the test to complete.
    lock.await(10, TimeUnit.SECONDS);
    assertThat(lock.getCount()).isEqualTo(0);
}

From source file:org.mule.transport.sftp.SftpIdentityFileFunctionalTestCase.java

@Test
public void testIdentityFile() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<String> message = new AtomicReference<String>();
    final AtomicInteger loopCount = new AtomicInteger(0);

    EventCallback callback = new EventCallback() {
        @Override//www.  j  a  va  2s .co m
        public synchronized void eventReceived(MuleEventContext context, Object component) {
            try {
                logger.info("called " + loopCount.incrementAndGet() + " times");
                // without this we may have problems with the many repeats
                if (1 == latch.getCount()) {
                    String o = IOUtils.toString((SftpInputStream) context.getMessage().getPayload());
                    message.set(o);
                    latch.countDown();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    };

    MuleClient client = new MuleClient(muleContext);

    // Ensure that no other files exists
    // cleanupRemoteFtpDirectory(client, INBOUND_ENDPOINT_NAME);

    Map<?, ?> properties = new HashMap<Object, Object>();
    // properties.put("filename", "foo.bar");

    Object component = getComponent("testComponent");
    assertTrue("FunctionalTestComponent expected", component instanceof FunctionalTestComponent);
    FunctionalTestComponent ftc = (FunctionalTestComponent) component;
    assertNotNull(ftc);

    ftc.setEventCallback(callback);

    logger.debug("before dispatch");
    // Send an file to the SFTP server, which the inbound-endpoint then can pick
    // up
    client.dispatch(getAddressByEndpoint(client, INBOUND_ENDPOINT_NAME), TEST_MESSAGE, properties);
    logger.debug("before retrieve");

    latch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);

    assertEquals(TEST_MESSAGE, message.get());
}