java.util.concurrent.CountDownLatch

Here are the examples of the java api class java.util.concurrent.CountDownLatch taken from open source projects.

1. TimeoutXATest#setUp()

Project: activemq-artemis
Source File: TimeoutXATest.java
View license
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    server = createServer(createDefaultNettyConfig());
    server.getConfiguration().setTransactionTimeout(1000);
    server.getConfiguration().setTransactionTimeoutScanPeriod(1100);
    server.getConfiguration().setJournalSyncNonTransactional(false);
    server.start();
    server.createQueue(SimpleString.toSimpleString("jms.queue.Queue1"), SimpleString.toSimpleString("jms.queue.Queue1"), null, true, false);
    removingTXEntered0 = new CountDownLatch(1);
    removingTXAwait0 = new CountDownLatch(1);
    removingTXEntered1 = new CountDownLatch(1);
    removingTXAwait1 = new CountDownLatch(1);
    entered = 0;
    enteredRollback = 0;
    enteredRollbackLatch = new CountDownLatch(1);
    waitingRollbackLatch = new CountDownLatch(1);
}

2. JobTest#buildNumberSynchronization()

Project: Jenkins2
Source File: JobTest.java
View license
@Test
public void buildNumberSynchronization() throws Exception {
    AbstractProject project = j.createFreeStyleProject();
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch stopLatch = new CountDownLatch(2);
    BuildNumberSyncTester test1 = new BuildNumberSyncTester(project, startLatch, stopLatch, true);
    BuildNumberSyncTester test2 = new BuildNumberSyncTester(project, startLatch, stopLatch, false);
    new Thread(test1).start();
    new Thread(test2).start();
    startLatch.countDown();
    stopLatch.await();
    assertTrue(test1.message, test2.passed);
    assertTrue(test2.message, test2.passed);
}

3. CacheTemporaryMemorizerTest#launchCodeInParallelThreads()

View license
public static void launchCodeInParallelThreads(final int nThreads, final Runnable task) throws InterruptedException {
    final CountDownLatch startGate = new CountDownLatch(1);
    final CountDownLatch endGate = new CountDownLatch(nThreads);
    for (int i = 0; i < nThreads; i++) {
        Thread t = new Thread() {

            public void run() {
                try {
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
    startGate.countDown();
    endGate.await();
}

4. CountDownLatchTest#testAwait()

Project: openjdk
Source File: CountDownLatchTest.java
View license
/**
     * await returns after countDown to zero, but not before
     */
public void testAwait() {
    final CountDownLatch l = new CountDownLatch(2);
    final CountDownLatch pleaseCountDown = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            assertEquals(2, l.getCount());
            pleaseCountDown.countDown();
            l.await();
            assertEquals(0, l.getCount());
        }
    });
    await(pleaseCountDown);
    assertEquals(2, l.getCount());
    l.countDown();
    assertEquals(1, l.getCount());
    assertThreadStaysAlive(t);
    l.countDown();
    assertEquals(0, l.getCount());
    awaitTermination(t);
}

5. CountDownLatchTest#testTimedAwait()

Project: openjdk
Source File: CountDownLatchTest.java
View license
/**
     * timed await returns after countDown to zero
     */
public void testTimedAwait() {
    final CountDownLatch l = new CountDownLatch(2);
    final CountDownLatch pleaseCountDown = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            assertEquals(2, l.getCount());
            pleaseCountDown.countDown();
            assertTrue(l.await(LONG_DELAY_MS, MILLISECONDS));
            assertEquals(0, l.getCount());
        }
    });
    await(pleaseCountDown);
    assertEquals(2, l.getCount());
    l.countDown();
    assertEquals(1, l.getCount());
    assertThreadStaysAlive(t);
    l.countDown();
    assertEquals(0, l.getCount());
    awaitTermination(t);
}

6. JobTest#buildNumberSynchronization()

Project: hudson
Source File: JobTest.java
View license
@Test
public void buildNumberSynchronization() throws Exception {
    AbstractProject project = j.createFreeStyleProject();
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch stopLatch = new CountDownLatch(2);
    BuildNumberSyncTester test1 = new BuildNumberSyncTester(project, startLatch, stopLatch, true);
    BuildNumberSyncTester test2 = new BuildNumberSyncTester(project, startLatch, stopLatch, false);
    new Thread(test1).start();
    new Thread(test2).start();
    startLatch.countDown();
    stopLatch.await();
    assertTrue(test1.message, test2.passed);
    assertTrue(test2.message, test2.passed);
}

7. AckDeadlineRenewerTest#testAddOneMessage()

View license
@Test
public void testAddOneMessage() throws InterruptedException {
    EasyMock.reset(pubsub);
    final CountDownLatch firstLatch = new CountDownLatch(1);
    final CountDownLatch secondLatch = new CountDownLatch(1);
    final AtomicLong firstRenewal = new AtomicLong();
    final AtomicLong secondRenewal = new AtomicLong();
    EasyMock.expect(pubsub.modifyAckDeadlineAsync(SUBSCRIPTION1, MIN_DEADLINE_MILLIS, TimeUnit.MILLISECONDS, ImmutableList.of(ACK_ID1))).andAnswer(createAnswer(firstLatch, firstRenewal));
    EasyMock.expect(pubsub.modifyAckDeadlineAsync(SUBSCRIPTION1, MIN_DEADLINE_MILLIS, TimeUnit.MILLISECONDS, ImmutableList.of(ACK_ID1))).andAnswer(createAnswer(secondLatch, secondRenewal));
    EasyMock.replay(pubsub);
    long addTime = System.currentTimeMillis();
    ackDeadlineRenewer.add(SUBSCRIPTION1, ACK_ID1);
    firstLatch.await();
    assertTrue(firstRenewal.get() < (addTime + MIN_DEADLINE_MILLIS));
    secondLatch.await();
    assertTrue(secondRenewal.get() < (firstRenewal.get() + MIN_DEADLINE_MILLIS));
}

8. TestAbstractTask#testWaitWhileRunning()

Project: datacollector
Source File: TestAbstractTask.java
View license
@Test
public void testWaitWhileRunning() throws Exception {
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final Task task = new AbstractTask("name") {
    };
    task.init();
    Thread waiter = new Thread() {

        @Override
        public void run() {
            try {
                latch1.await();
                latch2.countDown();
                task.waitWhileRunning();
            } catch (InterruptedException ex) {
            }
        }
    };
    waiter.start();
    task.run();
    latch1.countDown();
    latch2.await();
    task.stop();
    waiter.join();
}

9. TestZooKeeperClient#testAclAuthSpansExpiration()

View license
@Test(timeout = 60000)
public void testAclAuthSpansExpiration() throws Exception {
    ZooKeeperClient zkcAuth = buildAuthdClient("test");
    zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);
    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);
    expireZooKeeperSession(zkcAuth.get(), 2000);
    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);
    zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);
    rmAll(zkcAuth, "/test");
}

10. TestZooKeeperClient#testAclAuthSpansExpirationNonRetryableClient()

View license
@Test(timeout = 60000)
public void testAclAuthSpansExpirationNonRetryableClient() throws Exception {
    ZooKeeperClient zkcAuth = clientBuilder().retryPolicy(null).zkAclId("test").build();
    zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);
    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);
    expireZooKeeperSession(zkcAuth.get(), 2000);
    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);
    zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);
    rmAll(zkcAuth, "/test");
}

11. CommonTestUtils#startThreadTest()

Project: bonecp
Source File: CommonTestUtils.java
View license
/**
	 * Helper function.
	 *
	 * @param threads
	 * @param connections
	 * @param cpds
	 * @param workDelay
	 * @param doPreparedStatement 
	 * @return time taken
	 * @throws InterruptedException
	 */
public static long startThreadTest(int threads, long connections, DataSource cpds, int workDelay, boolean doPreparedStatement) throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(threads);
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    for (// create and start threads
    int i = 0; // create and start threads
    i < threads; // create and start threads
    i++) {
        pool.execute(new ThreadTester(startSignal, doneSignal, cpds, connections, workDelay, doPreparedStatement));
    }
    long start = System.currentTimeMillis();
    // START TEST!
    startSignal.countDown();
    doneSignal.await();
    long end = (System.currentTimeMillis() - start);
    pool.shutdown();
    return end;
}

12. BenchmarkTests#startThreadTest()

Project: bonecp
Source File: BenchmarkTests.java
View license
/**
	 * Helper function.
	 *
	 * @param threads
	 * @param cpds
	 * @param workDelay
	 * @param doPreparedStatement 
	 * @return time taken
	 * @throws InterruptedException
	 */
public static long startThreadTest(int threads, DataSource cpds, int workDelay, boolean doPreparedStatement) throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(threads);
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    ExecutorCompletionService<Long> ecs = new ExecutorCompletionService<Long>(pool);
    for (// create and start threads
    int i = 0; // create and start threads
    i <= threads; // create and start threads
    i++) {
        ecs.submit(new ThreadTesterUtil(startSignal, doneSignal, cpds, workDelay, doPreparedStatement));
    }
    // START TEST!
    startSignal.countDown();
    doneSignal.await();
    long time = 0;
    for (int i = 0; i <= threads; i++) {
        try {
            time = time + ecs.take().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    pool.shutdown();
    return time;
}

13. StorageTransactionTest#testConcurrentReaders()

Project: aurora
Source File: StorageTransactionTest.java
View license
@Test
public void testConcurrentReaders() throws Exception {
    // Validate that a slow read does not block another read.
    CountDownLatch slowReadStarted = new CountDownLatch(1);
    CountDownLatch slowReadFinished = new CountDownLatch(1);
    Future<String> future = executor.submit(() -> storage.read( storeProvider -> {
        slowReadStarted.countDown();
        try {
            slowReadFinished.await();
        } catch (InterruptedException e) {
            fail(e.getMessage());
        }
        return "slowResult";
    }));
    slowReadStarted.await();
    String fastResult = storage.read( storeProvider -> "fastResult");
    assertEquals("fastResult", fastResult);
    slowReadFinished.countDown();
    assertEquals("slowResult", future.get());
}

14. PessimisticLockFactoryTest#testDeadlockDetected_TwoThreadsInVector()

View license
@Test(timeout = 5000)
public void testDeadlockDetected_TwoThreadsInVector() throws InterruptedException {
    final PessimisticLockFactory lock = new PessimisticLockFactory();
    final CountDownLatch starter = new CountDownLatch(1);
    final CountDownLatch cdl = new CountDownLatch(1);
    final AtomicBoolean deadlockInThread = new AtomicBoolean(false);
    Thread t1 = createThread(starter, cdl, deadlockInThread, lock, "id1", lock, "id2");
    t1.start();
    lock.obtainLock("id2");
    starter.await();
    cdl.countDown();
    try {
        lock.obtainLock("id1");
        assertTrue(deadlockInThread.get());
    } catch (DeadlockException e) {
    }
}

15. PessimisticLockFactoryTest#testDeadlockDetected_TwoDifferentLockInstances()

View license
@Test(timeout = 5000)
public void testDeadlockDetected_TwoDifferentLockInstances() throws InterruptedException {
    final PessimisticLockFactory lock1 = new PessimisticLockFactory();
    final PessimisticLockFactory lock2 = new PessimisticLockFactory();
    final CountDownLatch starter = new CountDownLatch(1);
    final CountDownLatch cdl = new CountDownLatch(1);
    final AtomicBoolean deadlockInThread = new AtomicBoolean(false);
    Thread t1 = createThread(starter, cdl, deadlockInThread, lock1, "id1", lock2, "id1");
    t1.start();
    lock2.obtainLock("id1");
    starter.await();
    cdl.countDown();
    try {
        lock1.obtainLock("id1");
        assertTrue(deadlockInThread.get());
    } catch (DeadlockException e) {
    }
}

16. PessimisticLockFactoryTest#testDeadlockDetected_ThreeThreadsInVector()

View license
@Test(timeout = 5000)
public void testDeadlockDetected_ThreeThreadsInVector() throws InterruptedException {
    final PessimisticLockFactory lock = new PessimisticLockFactory();
    final CountDownLatch starter = new CountDownLatch(3);
    final CountDownLatch cdl = new CountDownLatch(1);
    final AtomicBoolean deadlockInThread = new AtomicBoolean(false);
    Thread t1 = createThread(starter, cdl, deadlockInThread, lock, "id1", lock, "id2");
    Thread t2 = createThread(starter, cdl, deadlockInThread, lock, "id2", lock, "id3");
    Thread t3 = createThread(starter, cdl, deadlockInThread, lock, "id3", lock, "id4");
    t1.start();
    t2.start();
    t3.start();
    lock.obtainLock("id4");
    starter.await();
    cdl.countDown();
    try {
        lock.obtainLock("id1");
        assertTrue(deadlockInThread.get());
    } catch (DeadlockException e) {
    }
}

17. BlockingChannelConnectionPoolTest#underSubscriptionTest()

View license
private void underSubscriptionTest(Properties props, String host, Port port, int underSubscriptionCount) throws Exception {
    AtomicReference<Exception> exception = new AtomicReference<Exception>();
    BlockingChannelInfo channelInfo = new BlockingChannelInfo(new ConnectionPoolConfig(new VerifiableProperties(props)), host, port, new MetricRegistry(), sslSocketFactory, sslConfig);
    CountDownLatch channelCount = new CountDownLatch(underSubscriptionCount);
    CountDownLatch shouldRelease = new CountDownLatch(1);
    CountDownLatch releaseComplete = new CountDownLatch(underSubscriptionCount);
    for (int i = 0; i < underSubscriptionCount; i++) {
        BlockingChannelInfoThread infoThread = new BlockingChannelInfoThread(channelInfo, channelCount, shouldRelease, releaseComplete, true, exception);
        Thread t = new Thread(infoThread);
        t.start();
    }
    shouldRelease.countDown();
    awaitCountdown(releaseComplete, 2000, exception, "Timed out while waiting for channels to be released");
    Assert.assertEquals(channelInfo.getNumberOfConnections(), underSubscriptionCount);
    channelInfo.getBlockingChannel(1000);
    Assert.assertEquals(channelInfo.getNumberOfConnections(), underSubscriptionCount);
    channelInfo.cleanup();
    Assert.assertEquals(channelInfo.getNumberOfConnections(), 0);
}

18. EJBUtil#makeNewServiceObject()

Project: axis2-java
Source File: EJBUtil.java
View license
/**
     * Return a object which implements the service.
     *
     * @param msgContext the message context
     * @return an object that implements the service
     * @throws AxisFault if fails
     */
protected static Object makeNewServiceObject(MessageContext msgContext) throws AxisFault {
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch stopLatch = new CountDownLatch(1);
    EJBClientWorker worker = new EJBClientWorker(msgContext, startLatch, stopLatch);
    workerPool.execute(worker);
    startLatch.countDown();
    try {
        stopLatch.await();
    } catch (InterruptedException e) {
        throw AxisFault.makeFault(e);
    }
    if (worker.getException() != null) {
        throw AxisFault.makeFault(worker.getException());
    }
    return worker.getReturnedValue();
}

19. TestZKTransaction#testProcessNullResults()

View license
@Test(timeout = 60000)
public void testProcessNullResults() throws Exception {
    ZooKeeperClient zkc = mock(ZooKeeperClient.class);
    ZKTransaction transaction = new ZKTransaction(zkc);
    int numOps = 3;
    final CountDownLatch commitLatch = new CountDownLatch(numOps);
    final CountDownLatch abortLatch = new CountDownLatch(numOps);
    for (int i = 0; i < numOps; i++) {
        transaction.addOp(new CountDownZKOp(commitLatch, abortLatch));
    }
    transaction.processResult(KeeperException.Code.CONNECTIONLOSS.intValue(), "test-path", null, null);
    abortLatch.await();
    assertEquals(0, abortLatch.getCount());
    assertEquals(numOps, commitLatch.getCount());
}

20. TestZKTransaction#testAbortTransaction()

View license
@Test(timeout = 60000)
public void testAbortTransaction() throws Exception {
    ZooKeeperClient zkc = mock(ZooKeeperClient.class);
    ZKTransaction transaction = new ZKTransaction(zkc);
    int numOps = 3;
    final CountDownLatch commitLatch = new CountDownLatch(numOps);
    final CountDownLatch abortLatch = new CountDownLatch(numOps);
    for (int i = 0; i < numOps; i++) {
        transaction.addOp(new CountDownZKOp(commitLatch, abortLatch));
    }
    transaction.abort(new DLIllegalStateException("Illegal State"));
    abortLatch.await();
    assertEquals(0, abortLatch.getCount());
    assertEquals(numOps, commitLatch.getCount());
}

21. TestBasicConfigurationBuilder#testGetConfigurationConcurrently()

View license
/**
     * Tests whether the builder can be accessed by multiple threads and that
     * only a single result object is produced.
     */
@Test
public void testGetConfigurationConcurrently() throws Exception {
    final int threadCount = 32;
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch endLatch = new CountDownLatch(threadCount);
    ConfigurationBuilder<?> builder = new BasicConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class);
    AccessBuilderThread[] threads = new AccessBuilderThread[threadCount];
    for (int i = 0; i < threadCount; i++) {
        threads[i] = new AccessBuilderThread(startLatch, endLatch, builder);
        threads[i].start();
    }
    startLatch.countDown();
    assertTrue("Timeout", endLatch.await(5, TimeUnit.SECONDS));
    Set<Object> results = new HashSet<Object>();
    for (AccessBuilderThread t : threads) {
        results.add(t.result);
    }
    assertEquals("Wrong number of result objects", 1, results.size());
}

22. InProcessSideInputContainerTest#isReadyForEmptyWindowTrue()

View license
@Test
public void isReadyForEmptyWindowTrue() throws Exception {
    CountDownLatch onComplete = new CountDownLatch(1);
    immediatelyInvokeCallback(mapView, GlobalWindow.INSTANCE);
    CountDownLatch latch = invokeLatchedCallback(singletonView, GlobalWindow.INSTANCE, onComplete);
    ReadyCheckingSideInputReader reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView));
    assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(true));
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false));
    latch.countDown();
    if (!onComplete.await(1500L, TimeUnit.MILLISECONDS)) {
        fail("Callback to set empty values did not complete!");
    }
    // The cached value was false, so it continues to be true
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false));
    // A new reader for the same container gets a fresh look
    reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView));
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true));
}

23. PromiseTest#basics_blocking()

Project: golo-lang
Source File: PromiseTest.java
View license
@Test(timeOut = 5000, invocationCount = 100)
public void basics_blocking() throws InterruptedException {
    final Promise p = new Promise();
    final CountDownLatch latch = new CountDownLatch(2);
    new Thread() {

        @Override
        public void run() {
            try {
                latch.countDown();
                latch.await();
                p.set("Yes!");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }.start();
    latch.countDown();
    latch.await();
    Object result = p.blockingGet();
    assertThat(result, is((Object) "Yes!"));
}

24. FakeTickerTest#runConcurrentTest()

Project: guava
Source File: FakeTickerTest.java
View license
/**
   * Runs {@code callable} concurrently {@code numberOfThreads} times.
   */
// concurrency
@GwtIncompatible
private void runConcurrentTest(int numberOfThreads, final Callable<Void> callable) throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
    final CountDownLatch startLatch = new CountDownLatch(numberOfThreads);
    final CountDownLatch doneLatch = new CountDownLatch(numberOfThreads);
    for (int i = numberOfThreads; i > 0; i--) {
        executorService.submit(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                startLatch.countDown();
                startLatch.await();
                callable.call();
                doneLatch.countDown();
                return null;
            }
        });
    }
    doneLatch.await();
}

25. SideInputContainerTest#isReadyForEmptyWindowTrue()

View license
@Test
public void isReadyForEmptyWindowTrue() throws Exception {
    CountDownLatch onComplete = new CountDownLatch(1);
    immediatelyInvokeCallback(mapView, GlobalWindow.INSTANCE);
    CountDownLatch latch = invokeLatchedCallback(singletonView, GlobalWindow.INSTANCE, onComplete);
    ReadyCheckingSideInputReader reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView));
    assertThat(reader.isReady(mapView, GlobalWindow.INSTANCE), is(true));
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false));
    latch.countDown();
    if (!onComplete.await(1500L, TimeUnit.MILLISECONDS)) {
        fail("Callback to set empty values did not complete!");
    }
    // The cached value was false, so it continues to be true
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(false));
    // A new reader for the same container gets a fresh look
    reader = container.createReaderForViews(ImmutableList.of(mapView, singletonView));
    assertThat(reader.isReady(singletonView, GlobalWindow.INSTANCE), is(true));
}

26. TrackingProcessEventListener#clear()

View license
public void clear() {
    nodesTriggered.clear();
    nodesLeft.clear();
    processesStarted.clear();
    processesCompleted.clear();
    processesAborted.clear();
    variablesChanged.clear();
    processesStartedLatch = new CountDownLatch(numberOfCountDownsNeeded);
    processesAbortedLatch = new CountDownLatch(numberOfCountDownsNeeded);
    processesCompletedLatch = new CountDownLatch(numberOfCountDownsNeeded);
    nodeTriggeredLatchMap.clear();
    nodeLeftLatchMap.clear();
}

27. WicketFilterTest#parallelCheckRedirect()

Project: wicket
Source File: WicketFilterTest.java
View license
/**
	 * Starts {@code threadCount} threads which try to check whether a redirect is required and
	 * initialize {@link WicketFilter#filterPathLength}
	 * 
	 * @param threadCount
	 *            the number of simultaneous threads
	 */
private void parallelCheckRedirect(int threadCount) {
    WicketFilter filter = new WicketFilter();
    filter.setFilterPath("filter/");
    AtomicInteger successCount = new AtomicInteger(0);
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch finishLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; i++) {
        new Thread(new CheckRedirectWorker(filter, startLatch, finishLatch, successCount)).start();
    }
    startLatch.countDown();
    try {
        finishLatch.await(2, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        fail();
    }
    assertEquals("all threads finished", 0, finishLatch.getCount());
    assertEquals("all redirects correct", threadCount, successCount.get());
}

28. AnnotationsInMemoryDsTest#multiThreadedSyncOnBuildingsTest()

View license
@Test
@Ignore
public void multiThreadedSyncOnBuildingsTest() throws Exception {
    final EdmEntitySet edmEntitySet = createMockedEdmEntitySet("Buildings");
    CountDownLatch latch;
    List<Thread> threads = new ArrayList<Thread>();
    int max = 500;
    latch = new CountDownLatch(max);
    for (int i = 0; i < max; i++) {
        threads.add(createBuildingThread(latch, datasource, edmEntitySet, String.valueOf("10")));
    }
    for (Thread thread : threads) {
        thread.start();
    }
    latch.await(60, TimeUnit.SECONDS);
    DataStore<Building> ds = datasource.getDataStore(Building.class);
    Collection<Building> buildings = ds.read();
    Assert.assertEquals(max, buildings.size());
}

29. FutureTaskTest#testCancelNoInterrupt()

Project: openjdk
Source File: FutureTaskTest.java
View license
/**
     * cancel(false) does not interrupt a running task
     */
public void testCancelNoInterrupt() {
    final CountDownLatch pleaseCancel = new CountDownLatch(1);
    final CountDownLatch cancelled = new CountDownLatch(1);
    final PublicFutureTask task = new PublicFutureTask(new CheckedCallable<Boolean>() {

        public Boolean realCall() {
            pleaseCancel.countDown();
            await(cancelled);
            assertFalse(Thread.interrupted());
            return Boolean.TRUE;
        }
    });
    Thread t = newStartedThread(task);
    await(pleaseCancel);
    assertTrue(task.cancel(false));
    assertTrue(task.isCancelled());
    cancelled.countDown();
    awaitTermination(t);
    assertEquals(1, task.runCount());
    assertEquals(1, task.setCount());
    assertEquals(0, task.setExceptionCount());
    tryToConfuseDoneTask(task);
    checkCancelled(task);
}

30. FileWatcherDiscoveryTest#setUp()

View license
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    connected = new CountDownLatch(1);
    interrupted = new CountDownLatch(1);
    restored = new CountDownLatch(1);
    primaryBrokerList = folder.newFile("primaryBrokerURIsFile.txt");
    secondaryBrokerList = folder.newFile("secondaryBrokerURIsFile.txt");
    LOG.info("Broker URIs going to file: {}", primaryBrokerList);
    writeOutBrokerURIsToFile(primaryBrokerList);
}

31. JmsAmqpDiscoveryTest#setUp()

Project: qpid-jms
Source File: JmsAmqpDiscoveryTest.java
View license
@Override
@Before
public void setUp() throws Exception {
    // Check assumptions *before* trying to start
    // the broker, which may fail otherwise
    assumeTrue("Multicast does not seem to be working, skip!", multicastWorking);
    super.setUp();
    connected = new CountDownLatch(1);
    interrupted = new CountDownLatch(1);
    restored = new CountDownLatch(1);
}

32. TestCachedLoggerFactory#testCaching()

Project: parseq
Source File: TestCachedLoggerFactory.java
View license
@Test
public void testCaching() throws Exception {
    CountingLoggerFactory loggerFactory = new CountingLoggerFactory();
    final ILoggerFactory cachedFactory = new CachedLoggerFactory(loggerFactory);
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    CountDownLatch startRace = new CountDownLatch(1);
    CountDownLatch stopRace = new CountDownLatch(5);
    for (int i = 0; i < 5; i++) {
        executorService.submit(() -> {
            try {
                startRace.await();
                cachedFactory.getLogger("com.linkedin.parseq.Task");
                stopRace.countDown();
            } catch (Exception e) {
                Assert.fail();
            }
        });
    }
    // start race
    startRace.countDown();
    assertTrue(stopRace.await(5000, TimeUnit.MILLISECONDS));
    Assert.assertEquals(loggerFactory.getCount(), 1);
}

33. TestAsyncDispatcher#testBasic()

Project: tez
Source File: TestAsyncDispatcher.java
View license
@SuppressWarnings("unchecked")
@Test(timeout = 5000)
public void testBasic() throws Exception {
    CountDownLatch latch = new CountDownLatch(4);
    CountDownEventHandler.latch = latch;
    AsyncDispatcher central = new AsyncDispatcher("Type1");
    central.register(TestEventType1.class, new TestEventHandler1());
    central.registerAndCreateDispatcher(TestEventType2.class, new TestEventHandler2(), "Type2");
    central.registerAndCreateDispatcher(TestEventType3.class, new TestEventHandler3(), "Type3");
    central.init(new Configuration());
    central.start();
    central.getEventHandler().handle(new TestEvent1(TestEventType1.TYPE1));
    central.getEventHandler().handle(new TestEvent2(TestEventType2.TYPE2));
    central.getEventHandler().handle(new TestEvent3(TestEventType3.TYPE3));
    latch.countDown();
    latch.await();
    central.close();
}

34. ThreadGroupRunner#tick()

Project: uPortal
Source File: ThreadGroupRunner.java
View license
/**
     * Effectively a count down latch where all threads in the group must reach the specified
     * tick before any are allowed to proceed.
     * 
     * @param includeMainThread If true all threads in the group AND the main thread must call tick
     */
public void tick(int index, boolean includeMainThread) throws InterruptedException {
    if (running != State.RUNNING) {
        throw new IllegalStateException("Can only be called after start() and before join() returns");
    }
    CountDownLatch latch = latchMap.get(index);
    if (latch == null) {
        final int latchCount = this.threads.size() + (includeMainThread ? 1 : 0);
        final CountDownLatch newLatch = new CountDownLatch(latchCount);
        latch = ConcurrentMapUtils.putIfAbsent(latchMap, index, newLatch);
        if (newLatch == latch) {
            logger.debug("created tick({}) = {}", index, latchCount);
        }
    }
    latch.countDown();
    logger.debug("tick({}) = {}", index, latch.getCount());
    latch.await();
}

35. MercuryTestController#resetCounters()

View license
public void resetCounters() {
    minSystemLatency = Double.MAX_VALUE;
    maxSystemLatency = 0;
    maxSystemConsRate = 0.0;
    minSystemConsRate = Double.MAX_VALUE;
    maxSystemProdRate = 0.0;
    minSystemProdRate = Double.MAX_VALUE;
    totalMsgCount = 0;
    receivedConsStats = new CountDownLatch(consumerCount);
    receivedProdStats = new CountDownLatch(producerCount);
    receivedEndMsg = new CountDownLatch(producerCount);
}

36. ThreadPoolUtilsTest#testShutdownGracefulWithStuckTask()

Project: qpid-jms
Source File: ThreadPoolUtilsTest.java
View license
@Test(timeout = 10000)
public void testShutdownGracefulWithStuckTask() throws Exception {
    final CountDownLatch started = new CountDownLatch(1);
    final CountDownLatch finish = new CountDownLatch(1);
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {

        @Override
        public void run() {
            try {
                started.countDown();
                finish.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
            }
        }
    });
    assertTrue(started.await(5, TimeUnit.SECONDS));
    ThreadPoolUtils.shutdownGraceful(service, 100);
    assertTrue(service.isShutdown());
    finish.countDown();
    assertTrue(ThreadPoolUtils.awaitTermination(service, 1000));
}

37. GraphVisualizationPanel#show()

View license
public static <V, E> void show(final Graph<V, E> graph) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread() {

        @SuppressWarnings("unchecked")
        public void run() {
            try {
                GraphVisualizationPanel.createFrame(graph).setVisible(true);
            } finally {
                latch.countDown();
            }
        }
    };
    t.setDaemon(true);
    t.start();
    latch.await();
}

38. TestImportStatistics#pushDataToImporters()

Project: voltdb
Source File: TestImportStatistics.java
View license
private void pushDataToImporters(int count, int loops, boolean goSlow) throws Exception {
    CountDownLatch latch = new CountDownLatch(3 * loops);
    List<SocketDataPusher> socketDataPushers = new ArrayList<>();
    for (int i = 0; i < loops; i++) {
        SocketDataPusher socketPusher = new SocketDataPusher("localhost", 7001, "TestImportStatistics$TestStatsProcedure7", count, latch, 7, goSlow);
        socketDataPushers.add(socketPusher);
        socketPusher.start();
        // second socket importer
        socketPusher = new SocketDataPusher("localhost", 7002, "TestImportStatistics$TestStatsProcedure11", count, latch, 11, goSlow);
        socketDataPushers.add(socketPusher);
        socketPusher.start();
        (new Log4jDataPusher(count, latch, 11)).start();
        ;
    }
    latch.await();
    for (SocketDataPusher pusher : socketDataPushers) {
        String procName = pusher.getProcName();
        Long currValue = m_expectedSocketFailures.get(procName);
        long newValue = ((currValue == null) ? 0 : currValue.longValue()) + pusher.getExpectedFailures();
        m_expectedSocketFailures.put(procName, newValue);
    }
}

39. TestAntiCacheManagerDistributedTxn#testQueueingOfDistributedTransaction()

View license
@Test
public void testQueueingOfDistributedTransaction() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final RpcCallback<UnevictDataResponse> callback = new RpcCallback<UnevictDataResponse>() {

        @Override
        public void run(UnevictDataResponse parameter) {
            // do nothing
            latch.countDown();
        }
    };
    hstore_sites[0].getCoordinator().setUnevictCallback(callback);
    AntiCacheManager manager = hstore_sites[0].getAntiCacheManager();
    int block_ids[] = new int[] { 1111 };
    int tuple_offsets[] = new int[] { 0 };
    // different from the base partition. This means the exception was 
    // thrown by a remote site
    this.hstore_conf.site.anticache_profiling = false;
    LocalTransaction txn = MockHStoreSite.makeLocalTransaction(hstore_sites[0]);
    //workaround
    txn.setOldTransactionId(txn.getTransactionId());
    int partition_id = CollectionUtil.first(this.hstore_sites[1].getLocalPartitionIds());
    assertTrue(manager.queue(txn, partition_id, catalog_tbl, block_ids, tuple_offsets));
    latch.await();
}

40. QueueSupport#dispatchApply()

Project: hawtdispatch
Source File: QueueSupport.java
View license
public static void dispatchApply(DispatchQueue queue, int iterations, final Task task) throws InterruptedException {
    final CountDownLatch done = new CountDownLatch(iterations);
    Task wrapper = new Task() {

        public void run() {
            try {
                task.run();
            } finally {
                done.countDown();
            }
        }
    };
    for (int i = 0; i < iterations; i++) {
        queue.execute(wrapper);
    }
    done.await();
}

41. CascadedValidationTest#testCascadedValidationMultiThreaded()

View license
/**
	 * To be executed manually. Not part of the JMeter tests for now.
	 */
@Test
public void testCascadedValidationMultiThreaded() throws Exception {
    CountDownLatch startLatch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(SIZE_OF_THREAD_POOL);
    for (int i = 0; i <= NUMBER_OF_RUNNABLES; i++) {
        Runnable run = new TestRunner(startLatch);
        executor.execute(run);
    }
    executor.shutdown();
    //start!
    startLatch.countDown();
    executor.awaitTermination(600, TimeUnit.SECONDS);
}

42. HRegion#releaseRowLock()

Project: hindex
Source File: HRegion.java
View license
/**
   * Release the row lock!
   * @param lockId  The lock ID to release.
   */
public void releaseRowLock(final Integer lockId) {
    // null lock id, do nothing
    if (lockId == null)
        return;
    HashedBytes rowKey = lockIds.remove(lockId);
    if (rowKey == null) {
        LOG.warn("Release unknown lockId: " + lockId);
        return;
    }
    CountDownLatch rowLatch = lockedRows.remove(rowKey);
    if (rowLatch == null) {
        LOG.error("Releases row not locked, lockId: " + lockId + " row: " + rowKey);
        return;
    }
    rowLatch.countDown();
}

43. TestCompaction#testTrackingCompactionRequest()

Project: hindex
Source File: TestCompaction.java
View license
/**
   * Create a custom compaction request and be sure that we can track it through the queue, knowing
   * when the compaction is completed.
   */
public void testTrackingCompactionRequest() throws Exception {
    // setup a compact/split thread on a mock server
    HRegionServer mockServer = Mockito.mock(HRegionServer.class);
    Mockito.when(mockServer.getConfiguration()).thenReturn(r.getConf());
    CompactSplitThread thread = new CompactSplitThread(mockServer);
    Mockito.when(mockServer.getCompactSplitThread()).thenReturn(thread);
    // simple stop for the metrics - we ignore any updates in the test
    RegionServerMetrics mockMetrics = Mockito.mock(RegionServerMetrics.class);
    Mockito.when(mockServer.getMetrics()).thenReturn(mockMetrics);
    // setup a region/store with some files
    Store store = r.getStore(COLUMN_FAMILY);
    createStoreFile(r);
    for (int i = 0; i < MAX_FILES_TO_COMPACT + 1; i++) {
        createStoreFile(r);
    }
    CountDownLatch latch = new CountDownLatch(1);
    TrackableCompactionRequest request = new TrackableCompactionRequest(r, store, latch);
    thread.requestCompaction(r, store, "test custom comapction", Store.PRIORITY_USER, request);
    // wait for the latch to complete.
    latch.await();
    thread.interruptIfNecessary();
}

44. TextClientTest#runIt()

Project: http-kit
Source File: TextClientTest.java
View license
private void runIt(String[] urls) throws URISyntaxException, UnknownHostException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(urls.length);
    ExecutorService pool = Executors.newCachedThreadPool();
    for (String url : urls) {
        IResponseHandler handler = new IResponseHandler() {

            public void onThrowable(Throwable t) {
                t.printStackTrace();
            }

            public void onSuccess(int status, Map<String, Object> headers, Object body) {
                System.out.println(body);
            }
        };
        client.exec(url, new RequestConfig(), null, new RespListener(handler, IFilter.ACCEPT_ALL, pool, 1));
    }
    latch.await();
}

45. JenkinsRule#createOnlineSlave()

Project: hudson
Source File: JenkinsRule.java
View license
/**
     * Create a new slave on the local host and wait for it to come online
     * before returning
     */
@SuppressWarnings({ "deprecation" })
public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    ComputerListener waiter = new ComputerListener() {

        @Override
        public void onOnline(Computer C, TaskListener t) {
            latch.countDown();
            unregister();
        }
    };
    waiter.register();
    DumbSlave s = createSlave(l, env);
    latch.await();
    return s;
}

46. HudsonTestCase#createOnlineSlave()

Project: hudson-2.x
Source File: HudsonTestCase.java
View license
/**
     * Create a new slave on the local host and wait for it to come online
     * before returning
     */
public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    ComputerListener waiter = new ComputerListener() {

        @Override
        public void onOnline(Computer C, TaskListener t) {
            latch.countDown();
            unregister();
        }
    };
    waiter.register();
    DumbSlave s = createSlave(l, env);
    latch.await();
    return s;
}

47. GroupTest#testSessionExpirationTriggersOnLoseMembership()

Project: commons
Source File: GroupTest.java
View license
@Test
public void testSessionExpirationTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = new Command() {

        @Override
        public void execute() throws RuntimeException {
            lostMembership.countDown();
        }
    };
    assertEmptyMembershipObserved();
    Membership membership = joinGroup.join(onLoseMembership);
    assertMembershipObserved(membership.getMemberId());
    expireSession(zkClient);
    // Will hang this test if onLoseMembership event is not propagated.
    lostMembership.await();
}

48. GroupTest#testNodeDeleteTriggersOnLoseMembership()

Project: commons
Source File: GroupTest.java
View license
@Test
public void testNodeDeleteTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = new Command() {

        @Override
        public void execute() throws RuntimeException {
            lostMembership.countDown();
        }
    };
    assertEmptyMembershipObserved();
    Membership membership = joinGroup.join(onLoseMembership);
    assertMembershipObserved(membership.getMemberId());
    membership.cancel();
    // Will hang this test if onLoseMembership event is not propagated.
    lostMembership.await();
}

49. TestCombinedConfigurationBuilder#testConcurrentReadAccessWithoutSynchronizer()

View license
/**
     * Tests whether a newly created instance can be read concurrently without a
     * special synchronizer.
     */
@Test
public void testConcurrentReadAccessWithoutSynchronizer() throws ConfigurationException {
    builder.configure(createParameters().setFile(TEST_FILE));
    CombinedConfiguration config = builder.getConfiguration();
    final int threadCount = 32;
    CountDownLatch startLatch = new CountDownLatch(1);
    ReadThread[] threads = new ReadThread[threadCount];
    for (int i = 0; i < threadCount; i++) {
        threads[i] = new ReadThread(config, startLatch);
        threads[i].start();
    }
    startLatch.countDown();
    for (ReadThread t : threads) {
        t.verify();
    }
}

50. FileUtilsWaitForTestCase#testWaitForInterrupted()

View license
@Test
public void testWaitForInterrupted() throws InterruptedException {
    final AtomicBoolean wasInterrupted = new AtomicBoolean(false);
    final CountDownLatch started = new CountDownLatch(1);
    Runnable thread = new Runnable() {

        @Override
        public void run() {
            started.countDown();
            FileUtils.waitFor(new File(""), 2);
            wasInterrupted.set(Thread.currentThread().isInterrupted());
        }
    };
    Thread thread1 = new Thread(thread);
    thread1.start();
    started.await();
    thread1.interrupt();
    thread1.join();
    assertTrue(wasInterrupted.get());
}

51. TimedSemaphoreTest#testAcquireNoLimit()

View license
/**
     * Tests the acquire() method if no limit is set. A test thread is started
     * that calls the semaphore a large number of times. Even if the semaphore's
     * period does not end, the thread should never block.
     *
     * @throws java.lang.InterruptedException so we don't have to catch it
     */
@Test
public void testAcquireNoLimit() throws InterruptedException {
    final ScheduledExecutorService service = EasyMock.createMock(ScheduledExecutorService.class);
    final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
    prepareStartTimer(service, future);
    EasyMock.replay(service, future);
    final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service, PERIOD, UNIT, TimedSemaphore.NO_LIMIT);
    final int count = 1000;
    final CountDownLatch latch = new CountDownLatch(count);
    final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
    t.start();
    latch.await();
    EasyMock.verify(service, future);
}

52. TimedSemaphoreTest#testAcquireMultiplePeriods()

View license
/**
     * Tests a bigger number of invocations that span multiple periods. The
     * period is set to a very short time. A background thread calls the
     * semaphore a large number of times. While it runs at last one end of a
     * period should be reached.
     *
     * @throws java.lang.InterruptedException so we don't have to catch it
     */
@Test
public void testAcquireMultiplePeriods() throws InterruptedException {
    final int count = 1000;
    final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD / 10, TimeUnit.MILLISECONDS, 1);
    semaphore.setLimit(count / 4);
    final CountDownLatch latch = new CountDownLatch(count);
    final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
    t.start();
    latch.await();
    semaphore.shutdown();
    assertTrue("End of period not reached", semaphore.getPeriodEnds() > 0);
}

53. BackwardsCompatibleNotificationBrokerTest#testNotifSubscriptionForwarded()

View license
@Test
public void testNotifSubscriptionForwarded() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final TwoLevelListChanged testData = createTestData();
    final NotifTestListenerChild testNotifListener = new NotifTestListenerChild(latch);
    final ListenerRegistration<NotificationListener> listenerRegistration = notificationProviderService.registerNotificationListener(testNotifListener);
    notificationProviderService.publish(testData);
    latch.await(500L, TimeUnit.MILLISECONDS);
    assertTrue(testNotifListener.getReceivedNotifications().size() == 1);
    assertEquals(testData, testNotifListener.getReceivedNotifications().get(0));
    listenerRegistration.close();
}

54. ForwardedNotificationAdapterTest#testNotifSubscription()

View license
@Test
public void testNotifSubscription() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final TwoLevelListChanged testData = createTestData();
    final TestNotifListener testNotifListener = new TestNotifListener(latch);
    final ListenerRegistration<TestNotifListener> listenerRegistration = getNotificationService().registerNotificationListener(testNotifListener);
    getNotificationPublishService().putNotification(testData);
    latch.await();
    assertTrue(testNotifListener.getReceivedNotifications().size() == 1);
    assertEquals(testData, testNotifListener.getReceivedNotifications().get(0));
    listenerRegistration.close();
}

55. ForwardedNotificationAdapterTest#testNotifSubscription2()

View license
@Test
public void testNotifSubscription2() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final TwoLevelListChanged testData = createTestData();
    final TestNotifListener testNotifListener = new TestNotifListener(latch);
    final ListenerRegistration<TestNotifListener> listenerRegistration = getNotificationService().registerNotificationListener(testNotifListener);
    try {
        getNotificationPublishService().offerNotification(testData).get(1, TimeUnit.SECONDS);
    } catch (ExecutionExceptionTimeoutException |  e) {
        LOG.error("Notification delivery failed", e);
        Assert.fail("notification should be delivered");
    }
    latch.await();
    assertTrue(testNotifListener.getReceivedNotifications().size() == 1);
    assertEquals(testData, testNotifListener.getReceivedNotifications().get(0));
    listenerRegistration.close();
}

56. ForwardedNotificationAdapterTest#testNotifSubscription3()

View license
@Test
public void testNotifSubscription3() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final TwoLevelListChanged testData = createTestData();
    final TestNotifListener testNotifListener = new TestNotifListener(latch);
    final ListenerRegistration<TestNotifListener> listenerRegistration = getNotificationService().registerNotificationListener(testNotifListener);
    assertNotSame(NotificationPublishService.REJECTED, getNotificationPublishService().offerNotification(testData, 5, TimeUnit.SECONDS));
    latch.await();
    assertTrue(testNotifListener.getReceivedNotifications().size() == 1);
    assertEquals(testData, testNotifListener.getReceivedNotifications().get(0));
    listenerRegistration.close();
}

57. MajorCompactionTest#testMajorCompaction()

Project: copycat
Source File: MajorCompactionTest.java
View license
/**
   * Tests compacting the log.
   */
public void testMajorCompaction() throws Throwable {
    writeEntries(31);
    assertEquals(log.length(), 31L);
    for (long index = 21; index < 28; index++) {
        log.release(index);
    }
    log.commit(31).compactor().minorIndex(31).majorIndex(31);
    CountDownLatch latch = new CountDownLatch(1);
    log.compactor().compact(Compaction.MAJOR).thenRun(latch::countDown);
    latch.await();
    assertEquals(log.length(), 31L);
    for (long index = 21; index < 28; index++) {
        assertTrue(log.lastIndex() >= index);
        assertFalse(log.contains(index));
        try (TestEntry entry = log.get(index)) {
            assertNull(entry);
        }
    }
}

58. TestBasicTokenManager#testMultiThreadSafety()

View license
@Test
public void testMultiThreadSafety() {
    int numThreads = 10;
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch finishLatch = new CountDownLatch(numThreads);
    BasicTokenManger<TestToken> manager = new BasicTokenManger<TestToken>();
    for (int i = 0; i < numThreads; ++i) {
        assertTrue(manager.addTokenToPool(new TestToken(String.valueOf(i))));
    }
    for (int i = 0; i < numThreads; ++i) {
        executor.submit(new TestThread(manager, startLatch, finishLatch, numThreads));
    }
    try {
        //sleep for 2 seconds so other threads can initialize
        Thread.sleep(2000);
        startLatch.countDown();
        finishLatch.await();
        assertTrue("No errors were thrown during thead safe check", true);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
    } catch (Throwable t) {
        fail("Error occured durring thread safe test : " + t.getMessage());
    }
}

59. TransactionServiceMain#doMain()

View license
/**
   * The main method. It simply call methods in the same sequence
   * as if the program is started by jsvc.
   */
public void doMain(final String[] args) throws Exception {
    final CountDownLatch shutdownLatch = new CountDownLatch(1);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            try {
                try {
                    TransactionServiceMain.this.stop();
                } finally {
                    try {
                        TransactionServiceMain.this.destroy();
                    } finally {
                        shutdownLatch.countDown();
                    }
                }
            } catch (Throwable t) {
                LOG.error("Exception when shutting down: " + t.getMessage(), t);
            }
        }
    });
    init(args);
    start();
    shutdownLatch.await();
}

60. FindManagerTest#runAsyncTest()

View license
private void runAsyncTest(String text, FindModel findModel) throws InterruptedException {
    final Ref<FindResult> result = new Ref<>();
    final CountDownLatch progressStarted = new CountDownLatch(1);
    final ProgressIndicatorBase progressIndicatorBase = new ProgressIndicatorBase();
    final Thread thread = new Thread(() -> ProgressManager.getInstance().runProcess(() -> {
        try {
            progressStarted.countDown();
            result.set(myFindManager.findString(text, 0, findModel, new LightVirtualFile("foo.java")));
        } catch (ProcessCanceledException ex) {
            result.set(new FindResultImpl());
        }
    }, progressIndicatorBase), "runAsyncTest");
    thread.start();
    progressStarted.await();
    thread.join(100);
    progressIndicatorBase.cancel();
    thread.join(500);
    assertNotNull(result.get());
    assertTrue(!result.get().isStringFound());
    thread.join();
}

61. VcsRepositoryManagerTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    cd(myProjectRoot);
    myVcs = new MockAbstractVcs(myProject);
    myProjectLevelVcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(myProject);
    myProjectLevelVcsManager.registerVcs(myVcs);
    READY_TO_READ = new CountDownLatch(1);
    CONTINUE_MODIFY = new CountDownLatch(1);
    myMockCreator = createMockRepositoryCreator();
    ExtensionPoint<VcsRepositoryCreator> point = getExtensionPoint();
    point.registerExtension(myMockCreator);
    myGlobalRepositoryManager = new VcsRepositoryManager(myProject, myProjectLevelVcsManager);
    myGlobalRepositoryManager.initComponent();
}

62. ConsoleViewImplTest#testConsolePrintsSomethingAfterDoubleClear()

View license
public void testConsolePrintsSomethingAfterDoubleClear() throws Exception {
    ConsoleViewImpl console = myConsole;
    Alarm alarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
    CountDownLatch latch = new CountDownLatch(1);
    alarm.addRequest(() -> {
        console.clear();
        console.clear();
        console.print("Test", ConsoleViewContentType.NORMAL_OUTPUT);
        latch.countDown();
    }, 0);
    latch.await();
    while (console.hasDeferredOutput()) {
        UIUtil.dispatchAllInvocationEvents();
        TimeoutUtil.sleep(5);
    }
    assertEquals("Test", console.getText());
}

63. LinkedTransferQueueTest#testWaitingConsumer()

Project: j2objc
Source File: LinkedTransferQueueTest.java
View license
/**
     * timed poll() or take() increments the waiting consumer count;
     * offer(e) decrements the waiting consumer count
     */
public void testWaitingConsumer() throws InterruptedException {
    final LinkedTransferQueue q = new LinkedTransferQueue();
    assertEquals(0, q.getWaitingConsumerCount());
    assertFalse(q.hasWaitingConsumer());
    final CountDownLatch threadStarted = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            threadStarted.countDown();
            assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
            assertEquals(0, q.getWaitingConsumerCount());
            assertFalse(q.hasWaitingConsumer());
        }
    });
    threadStarted.await();
    waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
    assertEquals(1, q.getWaitingConsumerCount());
    assertTrue(q.hasWaitingConsumer());
    assertTrue(q.offer(one));
    assertEquals(0, q.getWaitingConsumerCount());
    assertFalse(q.hasWaitingConsumer());
    awaitTermination(t, MEDIUM_DELAY_MS);
}

64. LinkedTransferQueueTest#testTransfer2()

Project: j2objc
Source File: LinkedTransferQueueTest.java
View license
/**
     * transfer waits until a poll occurs. The transfered element
     * is returned by this associated poll.
     */
public void testTransfer2() throws InterruptedException {
    final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
    final CountDownLatch threadStarted = new CountDownLatch(1);
    Thread t = newStartedThread(new CheckedRunnable() {

        public void realRun() throws InterruptedException {
            threadStarted.countDown();
            q.transfer(five);
            checkEmpty(q);
        }
    });
    threadStarted.await();
    waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
    assertEquals(1, q.size());
    assertSame(five, q.poll());
    checkEmpty(q);
    awaitTermination(t, MEDIUM_DELAY_MS);
}

65. RepositoryManagerTest#executorSetup()

View license
@Test
public void executorSetup() throws Exception {
    registerRequiredServices();
    context.registerInjectActivateService(new RepositoryManager());
    Executor executor = context.getService(Executor.class);
    assertNotNull("Repository initialization should have registered an Executor", executor);
    final AtomicBoolean invoked = new AtomicBoolean();
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(new Runnable() {

        @Override
        public void run() {
            invoked.set(true);
            latch.countDown();
        }
    });
    latch.await(5, TimeUnit.SECONDS);
    assertTrue(invoked.get());
}

66. SegmentListTest#testAppend()

Project: jafka
Source File: SegmentListTest.java
View license
/**
     * Test method for
     * {@link com.sohu.jafka.log.SegmentList#append(com.sohu.jafka.log.LogSegment)}.
     */
@Test
public void testAppend() throws Exception {
    final int count = 100;
    final SegmentList segmentList = createSegmentList(count);
    final CountDownLatch latch = new CountDownLatch(count);
    for (int i = 0; i < count; i++) {
        new Thread() {

            public void run() {
                try {
                    segmentList.append(new LogSegment(null, null, 0));
                } finally {
                    latch.countDown();
                }
            }
        }.start();
    }
    latch.await();
    assertEquals(count + count, segmentList.getView().size());
}

67. SegmentListTest#testTrunc()

Project: jafka
Source File: SegmentListTest.java
View license
/**
     * Test method for {@link com.sohu.jafka.log.SegmentList#trunc(int)}.
     */
@Test
public void testTrunc() throws Exception {
    final int count = 100;
    final int del = 2;
    final SegmentList segmentList = createSegmentList(count * (del + 1));
    final int totalCount = segmentList.getView().size();
    final CountDownLatch latch = new CountDownLatch(count);
    final AtomicInteger deletedCount = new AtomicInteger();
    for (int i = 0; i < count; i++) {
        new Thread() {

            public void run() {
                try {
                    deletedCount.addAndGet(segmentList.trunc(del).size());
                } finally {
                    latch.countDown();
                }
            }
        }.start();
    }
    latch.await();
    assertEquals(totalCount - deletedCount.get(), segmentList.getView().size());
    assertEquals(count * del, deletedCount.get());
}

68. EventDebouncerTest#should_reset_timer_if_n_events_received_within_same_window()

Project: java-driver
Source File: EventDebouncerTest.java
View license
@Test(groups = "unit")
public void should_reset_timer_if_n_events_received_within_same_window() throws InterruptedException {
    final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 50, 50, DEFAULT_MAX_QUEUED_EVENTS);
    debouncer.start();
    final CountDownLatch latch = new CountDownLatch(50);
    ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    pool.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            if (latch.getCount() > 0) {
                MockEvent event = new MockEvent(0);
                debouncer.eventReceived(event);
                latch.countDown();
            }
        }
    }, 0, 5, MILLISECONDS);
    latch.await();
    pool.shutdownNow();
    callback.awaitEvents(50);
    assertThat(callback.getEvents()).hasSize(50);
}

69. ConcurrentHumanTaskTest#testConcurrentInvocationsIncludingUserTasks()

Project: jbpm
Source File: ConcurrentHumanTaskTest.java
View license
@Test(timeout = 10000)
public void testConcurrentInvocationsIncludingUserTasks() throws Exception {
    CountDownLatch latch = new CountDownLatch(THREADS);
    for (int i = 0; i < THREADS; i++) {
        ProcessRunner pr = new ProcessRunner(i, getEmf(), latch);
        Thread t = new Thread(pr, i + "-process-runner");
        t.start();
    }
    latch.await();
    AuditLogService logService = new JPAAuditLogService(getEmf());
    List<? extends ProcessInstanceLog> logs = logService.findProcessInstances("com.sample.humantask.concurrent");
    assertEquals(2, logs.size());
    for (ProcessInstanceLog log : logs) {
        assertEquals(ProcessInstance.STATE_COMPLETED, log.getStatus().intValue());
    }
    logService.dispose();
}

70. InfiniteValidationLoopTest#main()

View license
public static void main(String[] args) {
    latch = new CountDownLatch(1);
    InfiniteValidationLoopTest t1 = new InfiniteValidationLoopTest();
    t1.pack();
    t1.setSize(200, 200);
    t1.setVisible(true);
    try {
        latch.await();
    } catch (InterruptedException ex) {
    }
    t1.dispose();
    latch = new CountDownLatch(1);
    t1 = new InfiniteValidationLoopTest();
    t1.pack();
    t1.setSize(50, 50);
    t1.setVisible(true);
    try {
        latch.await();
    } catch (InterruptedException ex) {
    }
    t1.dispose();
    if (failed) {
        throw new RuntimeException("Failed: infinite validattion loop detected");
    }
    System.out.println("Test PASSED");
}

71. ZBeaconTest#test()

Project: jeromq
Source File: ZBeaconTest.java
View license
@Test
public void test() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    byte[] beacon = new byte[] { 'H', 'Y', 'D', 'R', 'A', 0x01, 0x12, 0x34 };
    byte[] prefix = new byte[] { 'H', 'Y', 'D', 'R', 'A', 0x01 };
    ZBeacon zbeacon = new ZBeacon("255.255.255.255", 5670, beacon, false);
    zbeacon.setPrefix(prefix);
    zbeacon.setListener(new Listener() {

        @Override
        public void onBeacon(InetAddress sender, byte[] beacon) {
            latch.countDown();
        }
    });
    zbeacon.start();
    latch.await(20, TimeUnit.SECONDS);
    assertEquals(latch.getCount(), 0);
    zbeacon.stop();
}

72. RequestTableTest#testConcurrentRemoval()

Project: JGroups
Source File: RequestTableTest.java
View license
public void testConcurrentRemoval() throws Exception {
    RequestTable<Integer> table = create(4, 0, 1000);
    List<Integer> tmp = new ArrayList<>(1000);
    for (int i = 0; i < 1000; i++) tmp.add(i);
    Collections.shuffle(tmp);
    ConcurrentLinkedQueue<Integer> list = new ConcurrentLinkedQueue<>(tmp);
    Remover[] removers = new Remover[10];
    final CountDownLatch latch = new CountDownLatch(1);
    for (int i = 0; i < removers.length; i++) {
        removers[i] = new Remover(table, latch, list);
        removers[i].start();
    }
    int total_removed = 0;
    latch.countDown();
    for (Remover remover : removers) {
        remover.join();
        total_removed += remover.num_removed;
    }
    System.out.printf("table: %s, total removed=%d\n", table, total_removed);
    assertBounds(table, 1024, 0);
    assert table.low() == 1000 && table.high() == 1000;
    assert total_removed == 1000;
}

73. RingBundlerTestLockless#testSimpleSend()

View license
public void testSimpleSend() throws Exception {
    RingBufferBundlerLockless bundler = new RingBufferBundlerLockless(16);
    RingBundlerTest.MockTransport transport = new RingBundlerTest.MockTransport();
    bundler.init(transport);
    final CountDownLatch latch = new CountDownLatch(1);
    Sender[] senders = new Sender[20];
    for (int i = 0; i < senders.length; i++) {
        senders[i] = new Sender(latch, bundler);
        senders[i].start();
    }
    latch.countDown();
    for (Sender sender : senders) sender.join();
    System.out.println("bundler = " + bundler);
    bundler._readMessages();
    System.out.println("bundler = " + bundler);
}

74. RingBundlerTestLockless2#testSimpleSend()

View license
public void testSimpleSend() throws Exception {
    RingBufferBundlerLockless2 bundler = new RingBufferBundlerLockless2(16);
    RingBundlerTest.MockTransport transport = new RingBundlerTest.MockTransport();
    bundler.init(transport);
    final CountDownLatch latch = new CountDownLatch(1);
    Sender[] senders = new Sender[20];
    for (int i = 0; i < senders.length; i++) {
        senders[i] = new Sender(latch, bundler);
        senders[i].start();
    }
    latch.countDown();
    for (Sender sender : senders) sender.join();
    System.out.println("bundler = " + bundler);
    bundler._readMessages();
    System.out.println("bundler = " + bundler);
}

75. NioClientTest#sendMessages()

Project: JGroups
Source File: NioClientTest.java
View license
protected void sendMessages(InetAddress host, boolean direct, int num_threads) throws Exception {
    total_msgs.set(0);
    total_bytes_sent.set(0);
    senders = new Sender[num_threads];
    final CountDownLatch latch = new CountDownLatch(1);
    for (int i = 0; i < senders.length; i++) senders[i] = new Sender(host, direct, latch);
    for (Sender sender : senders) sender.start();
    latch.countDown();
    for (Sender sender : senders) sender.join();
}

76. InterceptorExecutorTest#executeAndAwait()

Project: karyon
Source File: InterceptorExecutorTest.java
View license
protected void executeAndAwait(InterceptorExecutor<ByteBuf, ByteBuf, KeyEvaluationContext> executor) throws InterruptedException {
    final CountDownLatch completionLatch = new CountDownLatch(1);
    executor.execute(Unpooled.buffer(), Unpooled.buffer(), new KeyEvaluationContext(new MockChannelHandlerContext("mock").channel())).doOnCompleted(new Action0() {

        @Override
        public void call() {
            completionLatch.countDown();
        }
    }).subscribe();
    completionLatch.await(1, TimeUnit.MINUTES);
}

77. RemotingTest#testWSJSR()

Project: kontraktor
Source File: RemotingTest.java
View license
// fixme: add connect-from-actor tests
// fixme: add minbin tests
// fixme: increase basic test coverage
@Test
@Ignore
public void testWSJSR() throws Exception {
    checkSequenceErrors = true;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    ActorServer publisher = _JSR356ServerConnector.Publish(service, "ws://localhost:8081/ws", null).await();
    RemotingTestService client = (RemotingTestService) new WebSocketConnectable(RemotingTestService.class, "ws://localhost:8081/ws").connect().await(9999999);
    CountDownLatch latch = new CountDownLatch(1);
    runWithClient(client, latch);
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

78. RemotingTest#runtHttp()

Project: kontraktor
Source File: RemotingTest.java
View license
public void runtHttp(Coding coding) throws InterruptedException {
    checkSequenceErrors = true;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    ActorServer publisher = new HttpPublisher(service, "localhost", "/lp", 8082).coding(coding).publish().await();
    RemotingTestService client = (RemotingTestService) new HttpConnectable(RemotingTestService.class, "http://localhost:8082/lp").coding(coding).connect().await(9999999);
    CountDownLatch latch = new CountDownLatch(1);
    runWithClient(client, latch);
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

79. RemotingTest#runWS()

Project: kontraktor
Source File: RemotingTest.java
View license
public void runWS(Coding coding) throws InterruptedException {
    checkSequenceErrors = true;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    ActorServer publisher = new WebSocketPublisher(service, "localhost", "/ws", 8081).coding(coding).publish().await();
    RemotingTestService client = (RemotingTestService) new WebSocketConnectable(RemotingTestService.class, "ws://localhost:8081/ws").coding(coding).connect().await(9999999);
    CountDownLatch latch = new CountDownLatch(1);
    runWithClient(client, latch);
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

80. RemotingTest#testNIOMany()

Project: kontraktor
Source File: RemotingTest.java
View license
@Test
public void testNIOMany() throws Exception {
    checkSequenceErrors = false;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    ActorServer publisher = NIOServerConnector.Publish(service, 8081, null).await();
    ExecutorService exec = Executors.newCachedThreadPool();
    CountDownLatch latch = new CountDownLatch(10);
    for (int i = 0; i < 10; i++) {
        exec.execute(() -> {
            try {
                runnitTCP(latch, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

81. RemotingTest#testBlocking()

Project: kontraktor
Source File: RemotingTest.java
View license
@Test
public void testBlocking() throws Exception {
    checkSequenceErrors = true;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    Coding coding = new Coding(SerializerType.FSTSer);
    ActorServer publisher = TCPServerConnector.Publish(service, 8081, coding).await();
    CountDownLatch latch = new CountDownLatch(1);
    runnitTCP(latch, coding);
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

82. RemotingTest#testBlockingMany()

Project: kontraktor
Source File: RemotingTest.java
View license
@Test
public void testBlockingMany() throws Exception {
    checkSequenceErrors = false;
    RemotingTestService service = Actors.AsActor(RemotingTestService.class, Q_SIZE);
    ActorServer publisher = TCPServerConnector.Publish(service, 8081, null).await();
    ExecutorService exec = Executors.newCachedThreadPool();
    CountDownLatch latch = new CountDownLatch(10);
    for (int i = 0; i < 10; i++) {
        exec.execute(() -> {
            try {
                runnitTCP(latch, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    latch.await();
    // wait for outstanding callbacks
    Thread.sleep(2000);
    publisher.close();
}

83. RxJava#remotingRxToRx()

Project: kontraktor
Source File: RxJava.java
View license
@Test
public void remotingRxToRx() throws InterruptedException {
    Observable<Integer> range = Observable.range(0, NUM_MSG / 4);
    Publisher<Integer> pub = RxReactiveStreams.toPublisher(range);
    KxReactiveStreams.get().asKxPublisher(pub).serve(new TCPNIOPublisher().port(3458));
    RateMeasure rm = new RateMeasure("events");
    KxPublisher<Integer> remoteStream = KxReactiveStreams.get().connect(Integer.class, new TCPConnectable().host("localhost").port(3458));
    CountDownLatch cnt = new CountDownLatch(NUM_MSG / 4);
    RxReactiveStreams.toObservable(remoteStream).forEach( i -> {
        rm.count();
        cnt.countDown();
    });
    cnt.await(50, TimeUnit.SECONDS);
    Assert.assertTrue(cnt.getCount() == 0);
}

84. RxJava#remotingRxToRxWebSocket()

Project: kontraktor
Source File: RxJava.java
View license
@Test
public void remotingRxToRxWebSocket() throws InterruptedException {
    Observable<Integer> range = Observable.range(0, NUM_MSG / 4);
    Publisher<Integer> pub = RxReactiveStreams.toPublisher(range);
    KxReactiveStreams.get().asKxPublisher(pub).serve(new WebSocketPublisher().hostName("localhost").port(7777).urlPath("/ws/rx"));
    RateMeasure rm = new RateMeasure("events");
    KxPublisher<Integer> remoteStream = KxReactiveStreams.get().connect(Integer.class, new WebSocketConnectable().url("ws://localhost:7777/ws/rx"));
    CountDownLatch cnt = new CountDownLatch(NUM_MSG / 4);
    RxReactiveStreams.toObservable(remoteStream).forEach( i -> {
        rm.count();
        cnt.countDown();
    });
    cnt.await(50, TimeUnit.SECONDS);
    Assert.assertTrue(cnt.getCount() == 0);
}

85. RxJava#remotingRxToRxWebSocketSampleEvent()

Project: kontraktor
Source File: RxJava.java
View license
@Test
public void remotingRxToRxWebSocketSampleEvent() throws InterruptedException {
    Observable<Integer> range = Observable.range(0, NUM_MSG / 4);
    Publisher<MyEvent> pub = RxReactiveStreams.toPublisher(range.map( i -> new MyEvent(i, Math.random(), "Hello" + i)));
    KxReactiveStreams.get().asKxPublisher(pub).serve(new WebSocketPublisher().hostName("localhost").port(7778).urlPath("/ws/rx"));
    RateMeasure rm = new RateMeasure("events");
    KxPublisher<MyEvent> remoteStream = KxReactiveStreams.get().connect(MyEvent.class, new WebSocketConnectable().url("ws://localhost:7778/ws/rx"));
    CountDownLatch cnt = new CountDownLatch(NUM_MSG / 4);
    RxReactiveStreams.toObservable(remoteStream).forEach( i -> {
        rm.count();
        cnt.countDown();
    });
    cnt.await(50, TimeUnit.SECONDS);
    Assert.assertTrue(cnt.getCount() == 0);
}

86. BuildCubeWithEngine#runTestAndAssertSucceed()

Project: kylin
Source File: BuildCubeWithEngine.java
View license
private void runTestAndAssertSucceed(String[] testCase) throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(testCase.length);
    final CountDownLatch countDownLatch = new CountDownLatch(testCase.length);
    List<Future<List<String>>> tasks = Lists.newArrayListWithExpectedSize(testCase.length);
    for (int i = 0; i < testCase.length; i++) {
        tasks.add(executorService.submit(new TestCallable(testCase[i], countDownLatch)));
    }
    countDownLatch.await();
    try {
        for (int i = 0; i < tasks.size(); ++i) {
            Future<List<String>> task = tasks.get(i);
            final List<String> jobIds = task.get();
            for (String jobId : jobIds) {
                assertJobSucceed(jobId);
            }
        }
    } catch (Exception ex) {
        logger.error(ex);
        throw ex;
    }
}

87. BuildIIWithEngine#testBuildII()

Project: kylin
Source File: BuildIIWithEngine.java
View license
@Test
public void testBuildII() throws Exception {
    String[] testCase = new String[] { "buildIIInnerJoin", "buildIILeftJoin" };
    ExecutorService executorService = Executors.newFixedThreadPool(testCase.length);
    final CountDownLatch countDownLatch = new CountDownLatch(testCase.length);
    List<Future<List<String>>> tasks = Lists.newArrayListWithExpectedSize(testCase.length);
    for (int i = 0; i < testCase.length; i++) {
        tasks.add(executorService.submit(new TestCallable(testCase[i], countDownLatch)));
    }
    countDownLatch.await();
    for (int i = 0; i < tasks.size(); ++i) {
        Future<List<String>> task = tasks.get(i);
        final List<String> jobIds = task.get();
        for (String jobId : jobIds) {
            assertJobSucceed(jobId);
        }
    }
}

88. TestEventService#testQueryStausLogger()

Project: lens
Source File: TestEventService.java
View license
@Test
public void testQueryStausLogger() throws Exception {
    System.out.println("@@@ testQueryStatusLogger");
    QueryStatusLogger logger = new QueryStatusLogger();
    service.addListenerForType(logger, StatusChange.class);
    // Catch all listener just to make sure that the query accepted and
    // query exec stat events get through
    final CountDownLatch latch = new CountDownLatch(2);
    LensEventListener<LensEvent> eventListener = queryEventListener(latch);
    service.addListenerForType(eventListener, LensEvent.class);
    QueryHandle queryHandle = new QueryHandle(UUID.randomUUID());
    QueryAccepted queryAccepted = new QueryAccepted(System.currentTimeMillis(), "beforeAccept", "afterAccept", queryHandle);
    QueryExecutionStatistics queryExecStats = new QueryExecutionStatistics(System.currentTimeMillis());
    service.notifyEvent(queryAccepted);
    service.notifyEvent(queryExecStats);
    latch.await();
    service.removeListener(eventListener);
}

89. ReactiveConnectionTest#transactional()

Project: lettuce
Source File: ReactiveConnectionTest.java
View license
@Test
public void transactional() throws Exception {
    final CountDownLatch sync = new CountDownLatch(1);
    RedisReactiveCommands<String, String> reactive = client.connect().reactive();
    reactive.multi().subscribe( multiResponse -> {
        reactive.set(key, "1").subscribe();
        reactive.incr(key).subscribe( getResponse -> {
            sync.countDown();
        });
        reactive.exec().subscribe();
    });
    sync.await(5, TimeUnit.SECONDS);
    String result = redis.get(key);
    assertThat(result).isEqualTo("2");
}

90. IgniteAtomicLongChangingTopologySelfTest#testQueueCreateNodesJoin()

View license
/**
     * @throws Exception If failed.
     */
public void testQueueCreateNodesJoin() throws Exception {
    CountDownLatch startLatch = new CountDownLatch(GRID_CNT);
    final AtomicBoolean run = new AtomicBoolean(true);
    Collection<IgniteInternalFuture<?>> futs = new ArrayList<>();
    for (int i = 0; i < GRID_CNT; i++) futs.add(startNodeAndCreaterThread(i, startLatch, run));
    startLatch.await();
    info("All nodes started.");
    Thread.sleep(10_000);
    run.set(false);
    for (IgniteInternalFuture<?> fut : futs) fut.get();
    info("Increments: " + queue.size());
    assert !queue.isEmpty();
}

91. GridCacheOffHeapValuesEvictionSelfTest#fillCache()

View license
/** Fill cache with values. */
private static void fillCache(final IgniteCache<Integer, Object> cache, long timeout) throws Exception {
    final byte[] val = new byte[VAL_SIZE];
    final AtomicInteger keyStart = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
    GridTestUtils.runMultiThreaded(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            final int start = keyStart.addAndGet(VALS_AMOUNT);
            for (int i = start; i < start + VALS_AMOUNT; i++) cache.put(i, val);
            latch.countDown();
            return null;
        }
    }, THREAD_COUNT, "test");
    latch.await(timeout, TimeUnit.MILLISECONDS);
}

92. IgniteCacheTopologySafeGetSelfTest#startBlockingTxAsync()

View license
/**
     * @return TX release future.
     * @throws Exception If failed.
     */
private IgniteInternalFuture<?> startBlockingTxAsync() throws Exception {
    final CountDownLatch lockLatch = new CountDownLatch(1);
    IgniteInternalFuture<Object> fut = GridTestUtils.runAsync(new Callable<Object>() {

        @Override
        public Object call() throws Exception {
            try (Transaction ignore = ignite(0).transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
                for (int i = 0; i < 30; i++) ignite(0).cache("tx").get("value-" + i);
                releaseLatch = new CountDownLatch(1);
                lockLatch.countDown();
                releaseLatch.await();
            }
            return null;
        }
    });
    lockLatch.await();
    return fut;
}

93. TcpClientDiscoverySpiSelfTest#testClientNodeJoin()

View license
/**
     * @throws Exception If failed.
     */
public void testClientNodeJoin() throws Exception {
    startServerNodes(3);
    startClientNodes(3);
    checkNodes(3, 3);
    srvJoinedLatch = new CountDownLatch(3);
    clientJoinedLatch = new CountDownLatch(3);
    attachListeners(3, 3);
    startClientNodes(1);
    await(srvJoinedLatch);
    await(clientJoinedLatch);
    checkNodes(3, 4);
}

94. TcpClientDiscoverySpiSelfTest#testClientNodeLeave()

View license
/**
     * @throws Exception If failed.
     */
public void testClientNodeLeave() throws Exception {
    startServerNodes(3);
    startClientNodes(3);
    checkNodes(3, 3);
    srvLeftLatch = new CountDownLatch(3);
    clientLeftLatch = new CountDownLatch(2);
    attachListeners(3, 3);
    stopGrid("client-2");
    await(srvLeftLatch);
    await(clientLeftLatch);
    checkNodes(3, 2);
}

95. TcpClientDiscoverySpiSelfTest#testClientNodeFail()

View license
/**
     * @throws Exception If failed.
     */
public void testClientNodeFail() throws Exception {
    startServerNodes(3);
    startClientNodes(3);
    checkNodes(3, 3);
    srvFailedLatch = new CountDownLatch(3);
    clientFailedLatch = new CountDownLatch(2);
    attachListeners(3, 3);
    failClient(2);
    await(srvFailedLatch);
    await(clientFailedLatch);
    checkNodes(3, 2);
}

96. AdTrackingBenchmark#connect()

Project: voltdb
Source File: AdTrackingBenchmark.java
View license
/**
     * Connect to a set of servers in parallel. Each will retry until
     * connection. This call will block until all have connected.
     *
     * @param servers A comma separated list of servers using the hostname:port
     * syntax (where :port is optional).
     * @throws InterruptedException if anything bad happens with the threads.
     */
void connect(String servers) throws InterruptedException {
    System.out.println("Connecting to VoltDB...");
    String[] serverArray = servers.split(",");
    final CountDownLatch connections = new CountDownLatch(serverArray.length);
    // use a new thread to connect to each server
    for (final String server : serverArray) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                connectToOneServerWithRetry(server);
                connections.countDown();
            }
        }).start();
    }
    // block until all have connected
    connections.await();
}

97. E2EClientRequestExecutorPoolAndFailureDetectorTest#doStressTest()

View license
public void doStressTest(int numPutters, int numGetters, int numOps) {
    int numOpers = numPutters + numGetters;
    CountDownLatch waitForStart = new CountDownLatch(numOpers);
    CountDownLatch waitForDone = new CountDownLatch(numOpers);
    for (int i = 0; i < numPutters; ++i) {
        new Thread(new Putter(waitForStart, waitForDone, numOps)).start();
    }
    for (int i = 0; i < numGetters; ++i) {
        new Thread(new Getter(waitForStart, waitForDone, numOps)).start();
    }
    try {
        waitForDone.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

98. AbstractSocketStoreTest#testThreadOverload()

View license
@Test
public void testThreadOverload() throws Exception {
    final Store<ByteArray, byte[], byte[]> store = getStore();
    int numOps = 100;
    final CountDownLatch latch = new CountDownLatch(numOps);
    Executor exec = Executors.newCachedThreadPool();
    for (int i = 0; i < numOps; i++) {
        exec.execute(new Runnable() {

            public void run() {
                store.put(TestUtils.toByteArray(TestUtils.randomString("abcdefghijklmnopqrs", 10)), new Versioned<byte[]>(TestUtils.randomBytes(8)), null);
                latch.countDown();
            }
        });
    }
    latch.await();
}

99. KeyedResourcePoolContentionTest#contendForResources()

View license
@Test
public void contendForResources() throws Exception {
    int numCheckers = POOL_SIZE * 2;
    int numChecks = 10 * 1000;
    String key = "Key";
    float invalidationRate = (float) 0.25;
    CountDownLatch waitForThreads = new CountDownLatch(numCheckers);
    CountDownLatch waitForCheckers = new CountDownLatch(numCheckers);
    for (int i = 0; i < numCheckers; ++i) {
        new Thread(new Checkers(waitForThreads, waitForCheckers, key, numChecks, invalidationRate)).start();
    }
    try {
        waitForCheckers.await();
        assertEquals(this.pool.getCheckedInResourceCount(), this.pool.getTotalResourceCount());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

100. CallCenterApp#connect()

Project: voltdb
Source File: CallCenterApp.java
View license
/**
     * Connect to a set of servers in parallel. Each will retry until
     * connection. This call will block until all have connected.
     *
     * @param servers A comma separated list of servers using the hostname:port
     * syntax (where :port is optional).
     * @throws InterruptedException if anything bad happens with the threads.
     */
void connect(String servers) throws InterruptedException {
    System.out.println("Connecting to VoltDB...");
    String[] serverArray = servers.split(",");
    final CountDownLatch connections = new CountDownLatch(serverArray.length);
    // use a new thread to connect to each server
    for (final String server : serverArray) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                connectToOneServerWithRetry(server);
                connections.countDown();
            }
        }).start();
    }
    // block until all have connected
    connections.await();
}