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:com.netflix.curator.framework.recipes.queue.TestQueueSharder.java

@Test
public void testDistribution() throws Exception {
    final int threshold = 100;
    final int factor = 10;

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    QueueSharder<String, DistributedQueue<String>> sharder = null;
    try {//from   w  w  w .ja  va  2  s .c om
        client.start();

        final CountDownLatch latch = new CountDownLatch(1);
        QueueConsumer<String> consumer = new QueueConsumer<String>() {
            @Override
            public void consumeMessage(String message) throws Exception {
                latch.await();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        QueueAllocator<String, DistributedQueue<String>> distributedQueueAllocator = makeAllocator(consumer);
        QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(threshold)
                .thresholdCheckMs(1).build();
        sharder = new QueueSharder<String, DistributedQueue<String>>(client, distributedQueueAllocator,
                "/queues", "/leader", policies);
        sharder.start();

        for (int i = 0; i < (factor * threshold); ++i) {
            sharder.getQueue().put(Integer.toString(i));
            Thread.sleep(5);
        }
        timing.forWaiting().sleepABit();

        SummaryStatistics statistics = new SummaryStatistics();
        for (String path : sharder.getQueuePaths()) {
            int numChildren = client.checkExists().forPath(path).getNumChildren();
            Assert.assertTrue(numChildren > 0);
            Assert.assertTrue(numChildren >= (threshold * .1));
            statistics.addValue(numChildren);
        }
        latch.countDown();

        Assert.assertTrue(statistics.getMean() >= (threshold * .9));
    } finally {
        timing.sleepABit(); // let queue clear
        Closeables.closeQuietly(sharder);
        Closeables.closeQuietly(client);
    }
}

From source file:com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileContentMonitorTest.java

@Test
public void testMonitorInStoppedStatus() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);

    SdkCredentialsFileContentMonitor monitor = new SdkCredentialsFileContentMonitor(targetFile,
            MONITOR_POLLING_INTERVAL_MILLIS, new FileAlterationListenerAdaptor() {

                @Override//w w  w.ja v  a 2s . c  o  m
                public void onFileChange(final File changedFile) {
                    System.err.println("stopped");
                    latch.countDown();
                }
            });
    monitor.setDebugMode(true);
    monitor.start();
    monitor.stop();

    touch(targetFile);

    long waitTime = MONITOR_POLLING_INTERVAL_MILLIS * 2;
    Assert.assertFalse("Who counted it down to zero???", latch.await(waitTime, TimeUnit.MILLISECONDS));
}

From source file:org.usergrid.benchmark.commands.queue.DirectReader.java

@Override
protected void doWork(CommandLine line, Queue<TestEvent> queue, String hostName, int workers, int count)
        throws Exception {

    CountDownLatch latch = new CountDownLatch(count * workers);

    //     queue.observe(new EventListener(latch, readsTimer, readLogger, queue));

    EventListener listener = new EventListener(latch, readsTimer, readLogger, queue);

    IQueue<TestEvent> hzQueue = instance.getQueue(line.getOptionValue("queue"));

    while (latch.getCount() != 0) {

        listener.onMessage(hzQueue.take());
    }//from  w  w  w.  j  a  v a 2 s .c o m

    latch.await();

    writeTimerData(readsTimer);

}

From source file:com.dianping.apistatic.Job.MovieShowBlockListCrawlerJob.java

@Override
protected void execute() throws Exception {
    movieShowIds.clear();/*from ww  w . j a  va 2s  .c om*/
    shopIdMap = readMapFromFile(Constants.SHOPIDMAP_PATH); // key cityid
    movieIdMap = readMapFromFile(Constants.MOVIEIDMAP_PATH); // key cityid

    if (MapUtils.isEmpty(shopIdMap) || MapUtils.isEmpty(movieIdMap)) {
        log("shopIdMapmovieIdMap", new RuntimeException("shopIdMapmovieIdMap"));
        return;
    }

    List<Integer> cityIds = getCityIds();
    if (CollectionUtils.isEmpty(cityIds)) {
        return;
    }

    int partitionSize = (cityIds.size() > 4 ? cityIds.size() / 4 : cityIds.size());
    List<List<Integer>> cityIdsList = Lists.partition(cityIds, partitionSize);
    CountDownLatch countDownLatch = new CountDownLatch(cityIdsList.size());

    for (List<Integer> list : cityIdsList) {
        MovieShowBlockCrawlerThread thread = new MovieShowBlockCrawlerThread(list, countDownLatch);
        thread.start();
    }

    try {
        countDownLatch.await();
    } catch (Exception e) {
        log("countDownLatch ", e);
        return;
    }

    if (CollectionUtils.isNotEmpty(movieShowIds)) {
        writeObjectAsJsonToFile(Constants.MOVIESHOWIDS_PATH, movieShowIds);
    }
}

From source file:com.googlecode.ehcache.annotations.integration.SelfPopulatingTest.java

/**
 * Control case on a method with selfPopulating = false.
 * //from  w w  w .  j av  a 2 s . c o m
 * @throws Exception
 */
@Test(timeout = 1000)
public void testSelfPopulatingFalse() throws Exception {
    final CountDownLatch threadRunningLatch = new CountDownLatch(2);
    final CountDownLatch proccedLatch = new CountDownLatch(1);
    this.selfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch);
    this.selfPopulatingTestInterface.setProccedLatch(proccedLatch);

    Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingBInvocationCount());

    final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingFalse-", true);

    threadGroup.addTask(new Runnable() {
        public void run() {
            selfPopulatingTestInterface.nonBlocking("test1");
        }
    });
    threadGroup.addTask(new Runnable() {
        public void run() {
            selfPopulatingTestInterface.nonBlocking("test1");
        }
    });

    threadGroup.start();

    // wait for both threads to get going
    threadRunningLatch.await();

    // Let both threads complete
    proccedLatch.countDown();

    threadGroup.join();

    // verify 2 calls to methodB
    Assert.assertEquals(2, this.selfPopulatingTestInterface.getNonBlockingInvocationCount());
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.data.KratuProcessor.java

public void processKratus(Long topAccountId, Date dateStart, Date dateEnd) throws InterruptedException {
    System.out.println("Processing Kratus for" + topAccountId);

    // We use a Latch so the main thread knows when all the worker threads are complete.
    final CountDownLatch latch = new CountDownLatch(1);
    Stopwatch stopwatch = Stopwatch.createStarted();

    RunnableKratu runnableKratu = createRunnableKratu(topAccountId, storageHelper, dateStart, dateEnd);

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    runnableKratu.setLatch(latch);//from  www  .  ja v  a  2  s  .  co  m
    executorService.execute(runnableKratu);

    latch.await();
    stopwatch.stop();
}

From source file:org.bpmscript.integration.spring.SpringReplyTest.java

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final int loopcount = 2;
    final CountDownLatch latch = new CountDownLatch(total + loopcount * total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {//from ww  w. j  a v a2s  . c  o  m

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/reply.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(new Object[] { loopcount });
                message.getHeader().setAttribute("definitionName", "test");
                message.getHeader().setAttribute("operation", "test");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

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 ww  w. j  a  va2 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();

}

From source file:org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils.java

public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
        boolean fireAndForgot) throws DeviceManagementException {

    String responseMsg = "";
    String urlString = ArduinoConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;

    if (log.isDebugEnabled()) {
        log.debug(urlString);/*from   w w  w .  java  2 s.com*/
    }

    if (!fireAndForgot) {
        HttpURLConnection httpConnection = getHttpConnection(urlString);

        try {
            httpConnection.setRequestMethod(HttpMethod.GET);
        } catch (ProtocolException e) {
            String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:"
                    + urlString;
            log.error(errorMsg);
            throw new DeviceManagementException(errorMsg, e);
        }

        responseMsg = readResponseFromGetRequest(httpConnection);

    } else {
        CloseableHttpAsyncClient httpclient = null;
        try {

            httpclient = HttpAsyncClients.createDefault();
            httpclient.start();
            HttpGet request = new HttpGet(urlString);
            final CountDownLatch latch = new CountDownLatch(1);
            Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
                @Override
                public void completed(HttpResponse httpResponse) {
                    latch.countDown();
                }

                @Override
                public void failed(Exception e) {
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                }
            });

            latch.await();

        } catch (InterruptedException e) {
            if (log.isDebugEnabled()) {
                log.debug("Sync Interrupted");
            }
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();

                }
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed on close");
                }
            }
        }
    }

    return responseMsg;
}

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 w w w  . j  a v  a 2s  . 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();

}