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.bt.aloha.batchtest.v2.TestRunner.java

@SuppressWarnings("unchecked")
public ResultTotals run() {
    log.info("= Summary =============================================================");
    log.info("Number of scenario runs: " + testRunnerConfig.getNumberOfRuns());
    log.info("Number of scenario types: " + scenarioBeanNameAndWeightMap.size());
    log.info("Size of executor pool (core): " + taskExecutor.getCorePoolSize());
    log.info("Size of executor pool (max): " + taskExecutor.getMaxPoolSize());

    Vector v = (Vector) applicationContext.getBean("allScenarioLifecycleListeners");
    if (v != null && v.get(0) != null)
        log.info("Using Stack Manager of type " + v.get(0).getClass());
    log.info("=======================================================================");

    normalizeWeightsToNumberOfConcurrentStarts();
    CountDownLatch latch = new CountDownLatch(testRunnerConfig.getNumberOfRuns());
    Vector<String> sNames = new Vector<String>();
    for (String s : scenarioBeanNameAndWeightMap.keySet()) {
        Integer weight = scenarioBeanNameAndWeightMap.get(s);
        for (int run = 0; run < weight; run++) {
            sNames.add(s);//from  w  ww . j av  a 2s.  c  om
        }
    }
    // shuffle names so that they can be executed randomly and not in a prefixed order
    Collections.shuffle(sNames, new Random(System.currentTimeMillis()));

    for (String s : sNames) {
        Scenario scenario = (Scenario) applicationContext.getBean(s);
        // it's a prototype - so has to be extracted from the app ctx every time
        ScenarioRunner sRunner = (ScenarioRunner) applicationContext.getBean("scenarioRunner");
        sRunner.setCountdownLatch(latch);
        sRunner.setScenario(scenario);
        // note that scenario lifecycle listeners (needed for start/stop stack) are set in the app context
        taskExecutor.execute(sRunner);
    }

    taskExecutor.shutdown();
    try {
        // waits for all runners to finish
        latch.await();
    } catch (InterruptedException e) {
        log.warn("Unable to wait for latch to get to 0", e);
    }
    resultLogger.logResultEntries();
    return resultLogger.logResultsSummary();
}

From source file:com.fusesource.forge.jmstest.threading.SteppablePool.java

public void waitUntilFinished() {
    CountDownLatch latch = new CountDownLatch(1);
    latches.add(latch);/*from  ww w.j av  a 2 s  . c om*/
    try {
        latch.await();
    } catch (InterruptedException ie) {
    }
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java

@Test
protected void test_try_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);

    final DistributedReentrantLock lock = new DistributedReentrantLock(dir);
    for (int i = 0; i < count; i++) {
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    while (lock.tryLock() == false) {
                        Thread.sleep(100 + RandomUtils.nextInt(100));
                    }/*from   www  .ja  v  a 2  s  . co m*/

                    System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        lock.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}

From source file:org.zodiark.publisher.PublisherTest.java

@Test(enabled = false)
public void createSessionTest() throws IOException, InterruptedException {
    final AtomicReference<PublisherResults> answer = new AtomicReference<>();
    final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build();
    final CountDownLatch latch = new CountDownLatch(1);

    publisherClient.handler(new OnEnvelopHandler() {
        @Override//  w w w  . ja va2  s.  c o  m
        public boolean onEnvelop(Envelope e) throws IOException {
            answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class));
            latch.countDown();
            return true;
        }
    }).open();

    Envelope createSessionMessage = Envelope
            .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE),
                    mapper.writeValueAsString(new UserPassword("foo", "bar"))));
    createSessionMessage.setFrom(new From(ActorValue.PUBLISHER));
    publisherClient.send(createSessionMessage);
    latch.await();
    assertEquals("OK", answer.get().getResults());
}

From source file:com.microsoft.office.core.EventsAsyncTestCase.java

@Test(timeout = 60000)
public void readTest() throws Exception {
    prepareEvent();//from  w  ww . ja  va 2s  . c o m
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                readAndCheck();
                removeEvent();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    counter.await();
}

From source file:com.github.sdbg.debug.core.internal.webkit.protocol.WebkitRemoteObject.java

/**
 * Return the length of the list if this object is a list.
 * //from w w  w .  java2s .  co m
 * @param webkitConnection
 * @return
 */
public int getListLength(WebkitConnection connection) {
    if (listLength == -1) {
        final CountDownLatch latch = new CountDownLatch(1);

        try {
            connection.getRuntime().callListLength(objectId, new WebkitCallback<Integer>() {
                @Override
                public void handleResult(WebkitResult<Integer> result) {
                    if (result.isError()) {
                        listLength = 0;
                    } else if (result.getResult() == null) {
                        listLength = 0;
                    } else {
                        listLength = result.getResult().intValue();
                    }

                    latch.countDown();
                }
            });
        } catch (IOException e) {
            listLength = 0;
            latch.countDown();
        }

        try {
            latch.await(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {

        }
    }

    return listLength;
}

From source file:com.brienwheeler.apps.main.ContextMainTest.java

@Test
public void testShutdownCommand() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    TestContextMain main = new TestContextMain(new String[] { N, C, TestDataConstants.RMAP_CTX_CLASSPATH },
            latch);/*www . j av a  2 s  . com*/
    TestRunner testRunner = new TestRunner(main);
    testRunner.start();

    latch.await();

    assertLaunchCount(main, 1);

    main.shutdown();
    testRunner.join();
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedLockTest.java

@Test
protected void test_try_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);

    final DistributedLock[] nodes = new DistributedLock[count];
    for (int i = 0; i < count; i++) {
        final DistributedLock node = new DistributedLock(dir);
        nodes[i] = node;/*  w  w  w  .j av a2 s  .com*/
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    while (node.tryLock() == false) {
                        Thread.sleep(100 + RandomUtils.nextInt(100));
                    }

                    System.out.println("id: " + node.getId() + " is leader: " + node.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        node.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}

From source file:org.elasticsearch.client.BulkProcessorIT.java

public void testThatBulkProcessorCountIsCorrect() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    BulkProcessorTestListener listener = new BulkProcessorTestListener(latch);

    int numDocs = randomIntBetween(10, 100);
    try (BulkProcessor processor = initBulkProcessorBuilder(listener)
            //let's make sure that the bulk action limit trips, one single execution will index all the documents
            .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs)
            .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
            .build()) {//from w  ww.ja  v  a2 s. com

        MultiGetRequest multiGetRequest = indexDocs(processor, numDocs);

        latch.await();

        assertThat(listener.beforeCounts.get(), equalTo(1));
        assertThat(listener.afterCounts.get(), equalTo(1));
        assertThat(listener.bulkFailures.size(), equalTo(0));
        assertResponseItems(listener.bulkItems, numDocs);
        assertMultiGetResponse(highLevelClient().multiGet(multiGetRequest), numDocs);
    }
}

From source file:com.ericsson.gerrit.plugins.highavailability.cache.ProjectListIT.java

@Test
@UseLocalDisk//from   w w w  . ja  v a  2  s  . com
@GlobalPluginConfig(pluginName = "high-availability", name = "peerInfo.static.url", value = URL)
@GlobalPluginConfig(pluginName = "high-availability", name = "http.retryInterval", value = "100")
public void addToProjectListAreForwarded() throws Exception {
    String createdProjectEncoded = Url.encode("org-a/some-project");
    String expectedRequest = "/plugins/high-availability/cache/" + Constants.PROJECT_LIST + "/"
            + createdProjectEncoded;
    CountDownLatch expectedRequestLatch = new CountDownLatch(1);
    wireMockRule.addMockServiceRequestListener((request, response) -> {
        if (request.getAbsoluteUrl().contains(expectedRequest)) {
            expectedRequestLatch.countDown();
        }
    });

    adminRestSession.put("/projects/" + createdProjectEncoded).assertCreated();
    assertThat(expectedRequestLatch.await(5, TimeUnit.SECONDS)).isTrue();
    verify(postRequestedFor(urlEqualTo(expectedRequest)));
}