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. 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);
}

3. 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());
}

4. 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) {
    }
}

5. 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) {
    }
}

6. 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) {
    }
}

7. 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;
}

8. 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;
}

9. 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();
}

10. 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");
}

11. 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");
}

12. 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));
}

13. 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);
}

14. 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);
}

15. 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();
}

16. 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);
}

17. 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);
}

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. 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());
}

20. 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));
}

21. 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());
}

22. 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());
}

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. 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());
}

28. 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);
}

29. 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);
}

30. 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);
}

31. 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));
}

32. 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);
}

33. 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);
}

34. 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();
}

35. 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();
}

36. 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());
}

37. HAPolicyAutoBackupExample#waitForBackups()

View license
private static void waitForBackups(ConnectionFactory cf0, int backups) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(backups);
    ((ActiveMQConnectionFactory) cf0).getServerLocator().addClusterTopologyListener(new ClusterTopologyListener() {

        List<TransportConfiguration> backups = new ArrayList<>();

        @Override
        public void nodeUP(TopologyMember member, boolean last) {
            if (member.getBackup() != null && !backups.contains(member.getBackup())) {
                backups.add(member.getBackup());
                latch.countDown();
            }
        }

        @Override
        public void nodeDown(long eventUID, String nodeID) {
        }
    });
    latch.await(30000, TimeUnit.MILLISECONDS);
}

38. JobSchedulerTest#testAddLongStringByteSequence()

View license
@Test
public void testAddLongStringByteSequence() throws Exception {
    final int COUNT = 10;
    final CountDownLatch latch = new CountDownLatch(COUNT);
    scheduler.addListener(new JobListener() {

        @Override
        public void scheduledJob(String id, ByteSequence job) {
            latch.countDown();
        }
    });
    for (int i = 0; i < COUNT; i++) {
        String test = new String("test" + i);
        scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), 1000);
    }
    latch.await(5, TimeUnit.SECONDS);
    assertEquals(0, latch.getCount());
}

39. JobSchedulerTest#testAddLongLongIntStringByteSequence()

View license
@Test
public void testAddLongLongIntStringByteSequence() throws Exception {
    final int COUNT = 10;
    final CountDownLatch latch = new CountDownLatch(COUNT);
    scheduler.addListener(new JobListener() {

        @Override
        public void scheduledJob(String id, ByteSequence job) {
            latch.countDown();
        }
    });
    long time = 2000;
    for (int i = 0; i < COUNT; i++) {
        String test = new String("test" + i);
        scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 10, -1);
    }
    assertTrue(latch.getCount() == COUNT);
    latch.await(3000, TimeUnit.SECONDS);
    assertTrue(latch.getCount() == 0);
}

40. JobSchedulerTest#testAddStopThenDeliver()

View license
@Test
public void testAddStopThenDeliver() throws Exception {
    final int COUNT = 10;
    final CountDownLatch latch = new CountDownLatch(COUNT);
    long time = 2000;
    for (int i = 0; i < COUNT; i++) {
        String test = new String("test" + i);
        scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 1000, -1);
    }
    File directory = store.getDirectory();
    tearDown();
    startStore(directory);
    scheduler.addListener(new JobListener() {

        @Override
        public void scheduledJob(String id, ByteSequence job) {
            latch.countDown();
        }
    });
    assertTrue(latch.getCount() == COUNT);
    latch.await(3000, TimeUnit.SECONDS);
    assertTrue(latch.getCount() == 0);
}

41. JmsSendWithAsyncCallbackTest#benchmarkCallbackRate()

View license
private double benchmarkCallbackRate() throws JMSException, InterruptedException {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(getName());
    int count = 1000;
    final CountDownLatch messagesSent = new CountDownLatch(count);
    ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long start = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        producer.send(session.createTextMessage("Hello"), new AsyncCallback() {

            @Override
            public void onSuccess() {
                messagesSent.countDown();
            }

            @Override
            public void onException(JMSException exception) {
                exception.printStackTrace();
            }
        });
    }
    messagesSent.await();
    return 1000.0 * count / (System.currentTimeMillis() - start);
}

42. ExceptionListenerTest#testListenerCalledForOneConnection()

View license
@Test
public void testListenerCalledForOneConnection() throws Exception {
    Connection conn = cf.createConnection();
    CountDownLatch latch = new CountDownLatch(1);
    MyExceptionListener listener = new MyExceptionListener(latch);
    conn.setExceptionListener(listener);
    ClientSessionInternal coreSession = (ClientSessionInternal) ((ActiveMQConnection) conn).getInitialSession();
    coreSession.getConnection().fail(new ActiveMQInternalErrorException("blah"));
    latch.await(5, TimeUnit.SECONDS);
    Assert.assertEquals(1, listener.numCalls);
    conn.close();
}

43. ConnectTest#testConnectNonImmediateClose()

Project: adbcj
Source File: ConnectTest.java
View license
public void testConnectNonImmediateClose() throws DbException, InterruptedException {
    final boolean[] callbacks = { false };
    final CountDownLatch latch = new CountDownLatch(1);
    Connection connection = connectionManager.connect().get();
    assertTrue(!connection.isClosed());
    connection.close(true).addListener(new DbListener<Void>() {

        public void onCompletion(DbFuture<Void> future) throws Exception {
            // Indicate that finalizeClose callback has been invoked
            callbacks[0] = true;
            latch.countDown();
        }
    }).get();
    assertTrue(connection.isClosed());
    latch.await(1, TimeUnit.SECONDS);
    assertTrue(callbacks[0], "Callback on finalizeClose future was not invoked");
}

44. TestAbstractServiceHolder#test_that_instance_is_disposed_after_delay()

View license
@Test(timeout = 2000L)
public void test_that_instance_is_disposed_after_delay() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    ServiceDestroyer<Object> serviceDestroyer = new ServiceDestroyer<Object>() {

        public void destroy(Object instance) {
            latch.countDown();
        }

        ;
    };
    DisposableReference<Object> disposableReference = new DisposableReference<>(instance, serviceDestroyer);
    scheduler.scheduleForDisposal(disposableReference, 1000);
    latch.await();
    assertNull(disposableReference.get());
}

45. TestAbstractServiceHolder#test_disposing_multiple_instances()

View license
@Test(timeout = 2000)
public void test_disposing_multiple_instances() throws InterruptedException {
    final int numberOfInstances = 100;
    final CountDownLatch latch = new CountDownLatch(numberOfInstances);
    ServiceDestroyer<Object> serviceDestroyer = new ServiceDestroyer<Object>() {

        public void destroy(Object instance) {
            latch.countDown();
        }

        ;
    };
    for (int i = 0; i < numberOfInstances; i++) {
        scheduler.scheduleForDisposal(new DisposableReference<>(instance, serviceDestroyer), 1000);
    }
    latch.await();
}

46. ConsistencyCheckerTool#doCheck()

Project: ambry
Source File: ConsistencyCheckerTool.java
View license
private void doCheck(File[] replicas, ArrayList<String> replicasList, ConcurrentHashMap<String, BlobStatus> blobIdToStatusMap, AtomicLong totalKeysProcessed) throws IOException, InterruptedException {
    DumpData dumpData = new DumpData(outFile, fileWriter, map);
    CountDownLatch countDownLatch = new CountDownLatch(replicas.length);
    IndexStats indexStats = new IndexStats();
    for (File replica : replicas) {
        Thread thread = new Thread(new ReplicaProcessorForBlobs(replica, replicasList, blobIdToStatusMap, totalKeysProcessed, dumpData, countDownLatch, indexStats));
        thread.start();
        thread.join();
    }
    countDownLatch.await();
    logOutput("Total Keys Processed " + totalKeysProcessed.get());
    logOutput("Total Put Records " + indexStats.getTotalPutRecords().get());
    logOutput("Total Delete Records " + indexStats.getTotalDeleteRecords().get());
    logOutput("Total Duplicate Put Records " + indexStats.getTotalDuplicatePutRecords().get());
    logOutput("Total Delete before Put Records " + indexStats.getTotalDeleteBeforePutRecords().get());
    logOutput("Total Put after Delete Records " + indexStats.getTotalPutAfterDeleteRecords().get());
    logOutput("Total Duplicate Delete Records " + indexStats.getTotalDuplicateDeleteRecords().get());
}

47. QueueManagerTest#testSetValidQueueItem()

View license
@Test
public void testSetValidQueueItem() throws Exception {
    // Get a queue that contains songs with space on their title (all in our test dataset)
    List<MediaSessionCompat.QueueItem> queue = QueueHelper.getPlayingQueueFromSearch(" ", null, provider);
    int expectedItemIndex = queue.size() - 1;
    MediaSessionCompat.QueueItem expectedItem = queue.get(expectedItemIndex);
    // Latch for 3 tests
    CountDownLatch latch = new CountDownLatch(3);
    QueueManager queueManager = createQueueManagerWithValidation(latch, expectedItemIndex, queue);
    // test 1: set the current queue
    queueManager.setCurrentQueue("Queue 1", queue);
    // test 2: set queue index to the expectedItem using its queueId
    assertTrue(queueManager.setCurrentQueueItem(expectedItem.getQueueId()));
    // test 3: set queue index to the expectedItem using its mediaId
    assertTrue(queueManager.setCurrentQueueItem(expectedItem.getDescription().getMediaId()));
    latch.await(5, TimeUnit.SECONDS);
}

48. TestSetupHelper#setupMusicProvider()

View license
public static MusicProvider setupMusicProvider(MusicProviderSource source) throws Exception {
    final CountDownLatch signal = new CountDownLatch(1);
    MusicProvider provider = new MusicProvider(source);
    provider.retrieveMediaAsync(new MusicProvider.Callback() {

        @Override
        public void onMusicCatalogReady(boolean success) {
            signal.countDown();
        }
    });
    signal.await();
    return provider;
}

49. WeakHandlerTest#postDelayed()

View license
@FlakyTest
@Test
public void postDelayed() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    long startTime = SystemClock.elapsedRealtime();
    final AtomicBoolean executed = new AtomicBoolean(false);
    mHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            executed.set(true);
            latch.countDown();
        }
    }, 300);
    latch.await(1, TimeUnit.SECONDS);
    assertTrue(executed.get());
    long elapsedTime = SystemClock.elapsedRealtime() - startTime;
    assertTrue("Elapsed time should be 300, but was " + elapsedTime, elapsedTime <= 330 && elapsedTime >= 300);
}

50. WeakHandlerTest#removeCallbacks()

View license
@Test
public void removeCallbacks() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    long startTime = SystemClock.elapsedRealtime();
    final AtomicBoolean executed = new AtomicBoolean(false);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            executed.set(true);
            latch.countDown();
        }
    };
    mHandler.postDelayed(r, 300);
    mHandler.removeCallbacks(r);
    latch.await(1, TimeUnit.SECONDS);
    assertFalse(executed.get());
    long elapsedTime = SystemClock.elapsedRealtime() - startTime;
    assertTrue(elapsedTime > 300);
}

51. JDBCLoaderTest#testMysqlDBLookup()

Project: apex-malhar
Source File: JDBCLoaderTest.java
View license
@Test
public void testMysqlDBLookup() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    ArrayList<FieldInfo> lookupKeys = new ArrayList<>();
    lookupKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
    ArrayList<FieldInfo> includeKeys = new ArrayList<>();
    includeKeys.add(new FieldInfo("NAME", "NAME", FieldInfo.SupportType.STRING));
    includeKeys.add(new FieldInfo("AGE", "AGE", FieldInfo.SupportType.INTEGER));
    includeKeys.add(new FieldInfo("ADDRESS", "ADDRESS", FieldInfo.SupportType.STRING));
    testMeta.dbloader.setFieldInfo(lookupKeys, includeKeys);
    latch.await(1000, TimeUnit.MILLISECONDS);
    ArrayList<Object> keys = new ArrayList<>();
    keys.add(4);
    ArrayList<Object> columnInfo = (ArrayList<Object>) testMeta.dbloader.get(keys);
    Assert.assertEquals("NAME", "Mark", columnInfo.get(0).toString().trim());
    Assert.assertEquals("AGE", 25, columnInfo.get(1));
    Assert.assertEquals("ADDRESS", "Rich-Mond", columnInfo.get(2).toString().trim());
}

52. JDBCLoaderTest#testMysqlDBQuery()

Project: apex-malhar
Source File: JDBCLoaderTest.java
View license
@Test
public void testMysqlDBQuery() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    testMeta.dbloader.setQueryStmt("Select id, name from " + testMeta.dbloader.getTableName() + " where AGE = ? and ADDRESS = ?");
    latch.await(1000, TimeUnit.MILLISECONDS);
    ArrayList<FieldInfo> includeKeys = new ArrayList<>();
    includeKeys.add(new FieldInfo("ID", "ID", FieldInfo.SupportType.INTEGER));
    includeKeys.add(new FieldInfo("NAME", "NAME", FieldInfo.SupportType.STRING));
    testMeta.dbloader.setFieldInfo(null, includeKeys);
    ArrayList<Object> keys = new ArrayList<Object>();
    keys.add(25);
    keys.add("Texas");
    ArrayList<Object> columnInfo = (ArrayList<Object>) testMeta.dbloader.get(keys);
    Assert.assertEquals("ID", 2, columnInfo.get(0));
    Assert.assertEquals("NAME", "Allen", columnInfo.get(1).toString().trim());
}

53. IncrementalCheckpointManagerTest#testCommitted()

View license
@Test
public void testCommitted() throws IOException, InterruptedException {
    CountDownLatch latch = new CountDownLatch(5);
    MockBucketsFileSystem mockBucketsFileSystem = new MockBucketsFileSystem(latch);
    testMeta.managedStateContext.setBucketsFileSystem(mockBucketsFileSystem);
    mockBucketsFileSystem.setup(testMeta.managedStateContext);
    testMeta.checkpointManager.setup(testMeta.managedStateContext);
    Map<Long, Map<Slice, Bucket.BucketedValue>> data = ManagedStateTestUtils.getTestData(0, 5, 0);
    testMeta.checkpointManager.save(data, testMeta.operatorId, 10, false);
    testMeta.checkpointManager.committed(testMeta.operatorId, 10);
    latch.await();
    testMeta.checkpointManager.teardown();
    Thread.sleep(500);
    for (int i = 0; i < 5; i++) {
        ManagedStateTestUtils.transferBucketHelper(testMeta.managedStateContext.getFileAccess(), i, data.get((long) i), 1);
    }
}

54. TimeBucketAssignerTest#testSlidingOnlyBetweenWindow()

View license
@Test
public void testSlidingOnlyBetweenWindow() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger timesCalled = new AtomicInteger();
    testMeta.timeBucketAssigner.setPurgeListener(new TimeBucketAssigner.PurgeListener() {

        @Override
        public void purgeTimeBucketsLessThanEqualTo(long timeBucket) {
            timesCalled.getAndIncrement();
            latch.countDown();
        }
    });
    testMeta.timeBucketAssigner.setup(testMeta.mockManagedStateContext);
    testMeta.timeBucketAssigner.beginWindow(0);
    latch.await();
    testMeta.timeBucketAssigner.endWindow();
    int valueBeforeSleep = timesCalled.get();
    Thread.sleep(1000);
    Assert.assertEquals("value should not change", valueBeforeSleep, timesCalled.get());
    testMeta.timeBucketAssigner.teardown();
}

55. BasicMetricsTest#before()

Project: apiman
Source File: BasicMetricsTest.java
View license
@Before
public void before() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    client = new OkHttpClient();
    Map<String, String> promConfig = new HashMap<>();
    promConfig.put("port", "9876");
    this.prometheusMetrics = new PrometheusScrapeMetrics(promConfig,  result -> latch.countDown());
    prometheusMetrics.setComponentRegistry(null);
    latch.await();
}

56. BasicMetricsTest#after()

Project: apiman
Source File: BasicMetricsTest.java
View license
@After
public void after() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    prometheusMetrics.close( result -> {
        if (result.failed())
            throw new RuntimeException(result.cause());
        latch.countDown();
    });
    latch.await();
}

57. HttpServiceTest#testCreateWithAppInit()

Project: apollo
Source File: HttpServiceTest.java
View license
@Test
public void testCreateWithAppInit() throws Exception {
    final InstanceWaiter waiter = new InstanceWaiter();
    final CountDownLatch closed = new CountDownLatch(1);
    final AppInit appInit =  env -> {
        counter.incrementAndGet();
        env.closer().register(closed::countDown);
    };
    new Thread(() -> {
        try {
            HttpService.boot(appInit, "test", waiter, "run", "foo");
        } catch (LoadingException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
    }).start();
    final Service.Instance instance = waiter.waitForInstance();
    instance.getSignaller().signalShutdown();
    instance.waitForShutdown();
    closed.await(5000, TimeUnit.SECONDS);
    assertEquals(1, counter.get());
}

58. RuntimeServer#stop()

View license
public void stop() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    this.serviceContainer.addTerminateListener( info -> latch.countDown());
    this.serviceContainer.shutdown();
    latch.await();
    this.deployer.stop();
    this.serviceContainer = null;
    this.client = null;
    this.deployer = null;
}

59. GracefulShutdownIntegrationTest#waitsForRequestToComplete()

View license
@Test(timeout = 10000L)
public void waitsForRequestToComplete() throws Exception {
    startServer();
    SleepService.Iface client = newClient();
    AtomicBoolean completed = new AtomicBoolean(false);
    CountDownLatch latch = new CountDownLatch(1);
    new Thread(() -> {
        try {
            latch.countDown();
            client.sleep(1000L);
            completed.set(true);
        } catch (Throwable t) {
            fail("Shouldn't happen: " + t);
        }
    }).start();
    // Wait for the latch to make sure the request has been sent before shutting down.
    latch.await();
    stopServer(true);
    assertTrue(completed.get());
}

60. FeatureCustomView#setCustomView()

Project: astrid
Source File: FeatureCustomView.java
View license
public void setCustomView() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            getSupportActionBar().setDisplayShowCustomEnabled(false);
            customView = new TextView(FeatureCustomView.this);
            customView.setText("Custom View!");
            customView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            getSupportActionBar().setCustomView(customView);
            latch.countDown();
        }
    });
    latch.await();
}

61. Issue0030#performFindItem()

Project: astrid
Source File: Issue0030.java
View license
public MenuItem performFindItem() throws InterruptedException {
    performFindItem = true;
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            invalidateOptionsMenu();
            latch.countDown();
        }
    });
    latch.await();
    performFindItem = false;
    return findItemResult;
}

62. Issue0030#performRemoveItem()

Project: astrid
Source File: Issue0030.java
View license
public void performRemoveItem() throws InterruptedException {
    performRemoveItem = true;
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            invalidateOptionsMenu();
            latch.countDown();
        }
    });
    latch.await();
    performRemoveItem = false;
}

63. Issue0033#hideVisibleMenuItems()

Project: astrid
Source File: Issue0033.java
View license
public void hideVisibleMenuItems() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            menuItemActionVisible.setVisible(false);
            menuItemNativeVisible.setVisible(false);
            latch.countDown();
        }
    });
    latch.await();
}

64. Issue0036#getSubMenuItemParent()

Project: astrid
Source File: Issue0036.java
View license
public Object getSubMenuItemParent() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            invalidateOptionsMenu();
            latch.countDown();
        }
    });
    latch.await();
    return subMenuItemParent;
}

65. Issue0042#setTitleResource()

Project: astrid
Source File: Issue0042.java
View license
public String setTitleResource() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            setTitle(R.string.issue0042_title);
            latch.countDown();
        }
    });
    latch.await();
    return getString(R.string.issue0042_title);
}

66. Issue0042#getSupportActionBarTitle()

Project: astrid
Source File: Issue0042.java
View license
public CharSequence getSupportActionBarTitle() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            supportActionBarTitle = getSupportActionBar().getTitle();
            latch.countDown();
        }
    });
    latch.await();
    return supportActionBarTitle;
}

67. Issue0045#getMenuItemSubMenu()

Project: astrid
Source File: Issue0045.java
View license
public Object getMenuItemSubMenu() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            invalidateOptionsMenu();
            latch.countDown();
        }
    });
    latch.await();
    return mMenuItemSubMenu;
}

68. ListenableFutureTest#testListenableFutureAfterCompletion()

View license
@Test
public void testListenableFutureAfterCompletion() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    try (AsyncHttpClient ahc = asyncHttpClient()) {
        final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute();
        future.get();
        future.addListener(() -> latch.countDown(), Runnable::run);
    }
    latch.await(10, TimeUnit.SECONDS);
}

69. ListenableFutureTest#testListenableFutureBeforeAndAfterCompletion()

View license
@Test
public void testListenableFutureBeforeAndAfterCompletion() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    try (AsyncHttpClient ahc = asyncHttpClient()) {
        final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute();
        future.addListener(() -> latch.countDown(), Runnable::run);
        future.get();
        future.addListener(() -> latch.countDown(), Runnable::run);
    }
    latch.await(10, TimeUnit.SECONDS);
}

70. GroupTest#testSessionExpirationTriggersOnLoseMembership()

Project: aurora
Source File: GroupTest.java
View license
@Test
public void testSessionExpirationTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = 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();
}

71. GroupTest#testNodeDeleteTriggersOnLoseMembership()

Project: aurora
Source File: GroupTest.java
View license
@Test
public void testNodeDeleteTriggersOnLoseMembership() throws Exception {
    final CountDownLatch lostMembership = new CountDownLatch(1);
    Command onLoseMembership = 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();
}

72. CronIT#testJobsAreScheduled()

Project: aurora
Source File: CronIT.java
View license
@Test
public void testJobsAreScheduled() throws Exception {
    auroraCronJob.execute(isA(JobExecutionContext.class));
    control.replay();
    final Scheduler scheduler = injector.getInstance(Scheduler.class);
    storage.write((NoResult.Quiet)  storeProvider -> storeProvider.getCronJobStore().saveAcceptedJob(CRON_JOB));
    final CountDownLatch cronRan = new CountDownLatch(1);
    scheduler.getListenerManager().addTriggerListener(new CountDownWhenComplete(cronRan));
    Service service = boot();
    cronRan.await();
    service.stopAsync().awaitTerminated();
}

73. SlaModuleTest#testSchedulingOnEvent()

Project: aurora
Source File: SlaModuleTest.java
View license
@Test
public void testSchedulingOnEvent() throws Exception {
    assertNotNull(module);
    final CountDownLatch latch = new CountDownLatch(1);
    StatsProvider untracked = createMock(StatsProvider.class);
    expect(statsProvider.untracked()).andReturn(untracked).anyTimes();
    expect(untracked.makeGauge(EasyMock.anyString(), EasyMock.anyObject())).andReturn(EasyMock.anyObject()).andAnswer(() -> {
        latch.countDown();
        return null;
    }).anyTimes();
    storageUtil.expectTaskFetch(Query.unscoped(), SlaTestUtil.makeTask(ImmutableMap.of(clock.nowMillis() - 1000, PENDING), 0)).anyTimes();
    storageUtil.expectOperations();
    control.replay();
    injector.getInstance(SlaUpdater.class).startAsync().awaitRunning();
    latch.await();
}

74. AwaitilityTest#awaitUsingCallToMultipleThreads_githubIssue28()

Project: awaitility
Source File: AwaitilityTest.java
View license
@Test(timeout = 5000)
public void awaitUsingCallToMultipleThreads_githubIssue28() throws Exception {
    final AtomicInteger errorCount = new AtomicInteger(0);
    int threadsCount = 16;
    final CountDownLatch allThreadsDone = new CountDownLatch(threadsCount);
    for (int i = 0; i < threadsCount; i++) {
        new Thread() {

            public void run() {
                try {
                    await().untilCall(to(fakeRepository).getValue(), equalTo(0));
                } catch (IllegalStateException ex) {
                    if (ex.getMessage().contains("No method call has been recorded. Perhaps the method was final?")) {
                        errorCount.incrementAndGet();
                    }
                } finally {
                    allThreadsDone.countDown();
                }
            }
        }.start();
    }
    allThreadsDone.await();
    assertTrue("Racy method recording got mixed up: " + errorCount.get() + " errors", errorCount.get() == 0);
}

75. ProgressListenerTest#throwErrorWithAsyncListener()

View license
// Listener is executed asynchronously
@Test
public void throwErrorWithAsyncListener() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    ProgressListener asyncListener = new ProgressListener() {

        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            throw new Error();
        }
    };
    ExceptionReporter reporter = new ExceptionReporter(asyncListener) {

        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            super.progressChanged(progressEvent);
            latch.countDown();
        }
    };
    publishProgress(reporter, ProgressEventType.CLIENT_REQUEST_STARTED_EVENT);
    latch.await();
    assertNotNull(reporter.getCause());
    try {
        reporter.throwExceptionIfAny();
        fail();
    } catch (AmazonClientException ex) {
    }
}

76. SimpleEventSchedulerTest#testScheduleJob()

View license
@Test
public void testScheduleJob() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer( invocation -> {
        latch.countDown();
        return null;
    }).when(eventBus).publish(isA(EventMessage.class));
    Saga mockSaga = mock(Saga.class);
    when(mockSaga.getSagaIdentifier()).thenReturn(UUID.randomUUID().toString());
    testSubject.schedule(Duration.ofMillis(30), new Object());
    latch.await(1, TimeUnit.SECONDS);
    verify(eventBus).publish(isA(EventMessage.class));
}

77. SimpleEventSchedulerTest#testCancelJob()

View license
@Test
public void testCancelJob() throws SchedulerException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer( invocation -> {
        latch.countDown();
        return null;
    }).when(eventBus).publish(isA(EventMessage.class));
    Saga mockSaga = mock(Saga.class);
    when(mockSaga.getSagaIdentifier()).thenReturn(UUID.randomUUID().toString());
    EventMessage<Object> event1 = createEvent();
    final EventMessage<Object> event2 = createEvent();
    ScheduleToken token1 = testSubject.schedule(Duration.ofMillis(100), event1);
    testSubject.schedule(Duration.ofMillis(120), event2);
    testSubject.cancelSchedule(token1);
    latch.await(1, TimeUnit.SECONDS);
    verify(eventBus, never()).publish(event1);
    verify(eventBus).publish(argThat(new EqualPayloadMatcher(event2)));
    executorService.shutdown();
    assertTrue("Executor refused to shutdown within a second", executorService.awaitTermination(1, TimeUnit.SECONDS));
}

78. QuartzEventSchedulerTest#testScheduleJob()

View license
@Test
public void testScheduleJob() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer( invocation -> {
        latch.countDown();
        return null;
    }).when(eventBus).publish(isA(EventMessage.class));
    Saga mockSaga = mock(Saga.class);
    when(mockSaga.getSagaIdentifier()).thenReturn(UUID.randomUUID().toString());
    ScheduleToken token = testSubject.schedule(Duration.ofMillis(30), new StubEvent());
    assertTrue(token.toString().contains("Quartz"));
    assertTrue(token.toString().contains(GROUP_ID));
    latch.await(1, TimeUnit.SECONDS);
    verify(eventBus).publish(isA(EventMessage.class));
}

79. QuartzEventSchedulerTest#testScheduleJob_TransactionalUnitOfWork()

View license
@SuppressWarnings("unchecked")
@Test
public void testScheduleJob_TransactionalUnitOfWork() throws InterruptedException, SchedulerException {
    Transaction mockTransaction = mock(Transaction.class);
    final TransactionManager transactionManager = mock(TransactionManager.class);
    when(transactionManager.startTransaction()).thenReturn(mockTransaction);
    testSubject.setTransactionManager(transactionManager);
    testSubject.initialize();
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer( invocation -> {
        latch.countDown();
        return null;
    }).when(eventBus).publish(isA(EventMessage.class));
    Saga mockSaga = mock(Saga.class);
    when(mockSaga.getSagaIdentifier()).thenReturn(UUID.randomUUID().toString());
    ScheduleToken token = testSubject.schedule(Duration.ofMillis(30), new StubEvent());
    assertTrue(token.toString().contains("Quartz"));
    assertTrue(token.toString().contains(GROUP_ID));
    latch.await(1, TimeUnit.SECONDS);
    InOrder inOrder = inOrder(transactionManager, eventBus, mockTransaction);
    inOrder.verify(transactionManager).startTransaction();
    inOrder.verify(eventBus).publish(isA(EventMessage.class));
    inOrder.verify(mockTransaction).commit();
}

80. ParallelEvaluatorTest#twoErrors()

Project: bazel
Source File: ParallelEvaluatorTest.java
View license
@Test
public void twoErrors() throws Exception {
    graph = new InMemoryGraphImpl();
    SkyKey firstError = GraphTester.toSkyKey("error1");
    SkyKey secondError = GraphTester.toSkyKey("error2");
    CountDownLatch firstStart = new CountDownLatch(1);
    CountDownLatch secondStart = new CountDownLatch(1);
    tester.getOrCreate(firstError).setBuilder(new ChainedFunction(firstStart, secondStart, /*notifyFinish=*/
    null, /*waitForException=*/
    false, /*value=*/
    null, ImmutableList.<SkyKey>of()));
    tester.getOrCreate(secondError).setBuilder(new ChainedFunction(secondStart, firstStart, /*notifyFinish=*/
    null, /*waitForException=*/
    false, /*value=*/
    null, ImmutableList.<SkyKey>of()));
    EvaluationResult<StringValue> result = eval(/*keepGoing=*/
    false, firstError, secondError);
    assertTrue(result.toString(), result.hasError());
    // With keepGoing=false, the eval call will terminate with exactly one error (the first one
    // thrown). But the first one thrown here is non-deterministic since we synchronize the
    // builders so that they run at roughly the same time.
    assertThat(ImmutableSet.of(firstError, secondError)).contains(Iterables.getOnlyElement(result.errorMap().keySet()));
}

81. ZkUtils#createFullPathOptimistic()

Project: bookkeeper
Source File: ZkUtils.java
View license
/**
     * Create zookeeper path recursively and optimistically. This method can throw
     * any of the KeeperExceptions which can be thrown by ZooKeeper#create.
     * KeeperException.NodeExistsException will only be thrown if the full path specified
     * by _path_ already exists. The existence of any parent znodes is not an error
     * condition.
     *
     * @param zkc
     *            - ZK instance
     * @param path
     *            - znode path
     * @param data
     *            - znode data
     * @param acl
     *            - Acl of the zk path
     * @param createMode
     *            - Create mode of zk path
     * @throws KeeperException
     *             if the server returns a non-zero error code, or invalid ACL
     * @throws InterruptedException
     *             if the transaction is interrupted
     */
public static void createFullPathOptimistic(ZooKeeper zkc, String path, byte[] data, final List<ACL> acl, final CreateMode createMode) throws KeeperException, InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger rc = new AtomicInteger(Code.OK.intValue());
    asyncCreateFullPathOptimistic(zkc, path, data, acl, createMode, new StringCallback() {

        @Override
        public void processResult(int rc2, String path, Object ctx, String name) {
            rc.set(rc2);
            latch.countDown();
        }
    }, null);
    latch.await();
    if (rc.get() != Code.OK.intValue()) {
        throw KeeperException.create(Code.get(rc.get()));
    }
}

82. BookKeeperTest#testConstructionZkDelay()

Project: bookkeeper
Source File: BookKeeperTest.java
View license
@Test
public void testConstructionZkDelay() throws Exception {
    ClientConfiguration conf = new ClientConfiguration().setZkServers(zkUtil.getZooKeeperConnectString()).setZkTimeout(20000);
    CountDownLatch l = new CountDownLatch(1);
    zkUtil.sleepServer(5, l);
    l.await();
    BookKeeper bkc = new BookKeeper(conf);
    bkc.createLedger(digestType, "testPasswd".getBytes()).close();
    bkc.close();
}

83. BookKeeperTest#testConstructionNotConnectedExplicitZk()

Project: bookkeeper
Source File: BookKeeperTest.java
View license
@Test
public void testConstructionNotConnectedExplicitZk() throws Exception {
    ClientConfiguration conf = new ClientConfiguration().setZkServers(zkUtil.getZooKeeperConnectString()).setZkTimeout(20000);
    CountDownLatch l = new CountDownLatch(1);
    zkUtil.sleepServer(5, l);
    l.await();
    ZooKeeper zk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), 10000, new Watcher() {

        @Override
        public void process(WatchedEvent event) {
        }
    });
    assertFalse("ZK shouldn't have connected yet", zk.getState().isConnected());
    try {
        BookKeeper bkc = new BookKeeper(conf, zk);
        fail("Shouldn't be able to construct with unconnected zk");
    } catch (KeeperException.ConnectionLossException cle) {
    }
}

84. BookKeeperTest#testAsyncReadWithError()

Project: bookkeeper
Source File: BookKeeperTest.java
View license
/**
     * Tests that when trying to use a closed BK client object we get
     * a callback error and not an InterruptedException.
     * @throws Exception
     */
@Test(timeout = 60000)
public void testAsyncReadWithError() throws Exception {
    LedgerHandle lh = bkc.createLedger(3, 3, DigestType.CRC32, "testPasswd".getBytes());
    bkc.close();
    final AtomicInteger result = new AtomicInteger(0);
    final CountDownLatch counter = new CountDownLatch(1);
    // Try to write, we shoud get and error callback but not an exception
    lh.asyncAddEntry("test".getBytes(), new AddCallback() {

        public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
            result.set(rc);
            counter.countDown();
        }
    }, null);
    counter.await();
    Assert.assertTrue(result.get() != 0);
}

85. LocalBookKeeperTest#testUseLocalBookie()

Project: bookkeeper
Source File: LocalBookKeeperTest.java
View license
@Test
public void testUseLocalBookie() throws Exception {
    ClientConfiguration conf = new ClientConfiguration().setZkServers(zkUtil.getZooKeeperConnectString()).setZkTimeout(20000);
    CountDownLatch l = new CountDownLatch(1);
    zkUtil.sleepServer(5, l);
    l.await();
    BookKeeper bkc = new BookKeeper(conf);
    LedgerHandle h = bkc.createLedger(1, 1, digestType, "testPasswd".getBytes());
    h.addEntry("test".getBytes());
    h.close();
    bkc.close();
}

86. TestAddEntryQuorumTimeout#testLedgerClosedAfterTimeout()

View license
@Test(timeout = 60000)
public void testLedgerClosedAfterTimeout() throws Exception {
    BookKeeperTestClient bkc = new BookKeeperTestClient(baseClientConf);
    LedgerHandle lh = bkc.createLedger(3, 3, 3, digestType, testPasswd);
    List<BookieSocketAddress> curEns = lh.getLedgerMetadata().currentEnsemble;
    byte[] data = "foobar".getBytes();
    CountDownLatch b0latch = sleepBookie(curEns.get(0), 5);
    try {
        lh.addEntry(data);
        Assert.fail("should have thrown");
    } catch (BKException.BKAddEntryQuorumTimeoutException ex) {
    }
    b0latch.await();
    try {
        lh.addEntry(data);
        Assert.fail("should have thrown");
    } catch (BKException.BKLedgerClosedException ex) {
    }
}

87. TestBookieWatcher#testBookieWatcherDieWhenSessionExpired()

Project: bookkeeper
Source File: TestBookieWatcher.java
View license
@Test(timeout = 10000)
public void testBookieWatcherDieWhenSessionExpired() throws Exception {
    final int timeout = 2000;
    final CountDownLatch connectLatch = new CountDownLatch(1);
    ZooKeeper zk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), timeout, new Watcher() {

        @Override
        public void process(WatchedEvent watchedEvent) {
            if (EventType.None == watchedEvent.getType() && KeeperState.SyncConnected == watchedEvent.getState()) {
                connectLatch.countDown();
            }
        }
    });
    connectLatch.await();
    try {
        runBookieWatcherWhenSessionExpired(zk, timeout, false);
    } finally {
        zk.close();
    }
}

88. AuditorLedgerCheckerTest#addEntry()

View license
private void addEntry(int numEntriesToWrite, LedgerHandle lh) throws InterruptedException, BKException {
    final CountDownLatch completeLatch = new CountDownLatch(numEntriesToWrite);
    final AtomicInteger rc = new AtomicInteger(BKException.Code.OK);
    for (int i = 0; i < numEntriesToWrite; i++) {
        ByteBuffer entry = ByteBuffer.allocate(4);
        entry.putInt(rng.nextInt(Integer.MAX_VALUE));
        entry.position(0);
        lh.asyncAddEntry(entry.array(), new AddCallback() {

            public void addComplete(int rc2, LedgerHandle lh, long entryId, Object ctx) {
                rc.compareAndSet(BKException.Code.OK, rc2);
                completeLatch.countDown();
            }
        }, null);
    }
    completeLatch.await();
    if (rc.get() != BKException.Code.OK) {
        throw BKException.create(rc.get());
    }
}

89. AndroidPayTest#isReadyToPay_returnsFalseWhenAndroidPayIsNotEnabled()

View license
@Test(timeout = 1000)
@SmallTest
public void isReadyToPay_returnsFalseWhenAndroidPayIsNotEnabled() throws InvalidArgumentException, InterruptedException {
    Configuration configuration = new TestConfigurationBuilder().androidPay(new TestAndroidPayConfigurationBuilder().enabled(false)).buildConfiguration();
    BraintreeFragment fragment = getMockFragment(mActivityTestRule.getActivity(), configuration);
    when(fragment.getAuthorization()).thenReturn(Authorization.fromString(TOKENIZATION_KEY));
    final CountDownLatch latch = new CountDownLatch(1);
    AndroidPay.isReadyToPay(fragment, new BraintreeResponseListener<Boolean>() {

        @Override
        public void onResponse(Boolean isReadyToPay) {
            assertFalse(isReadyToPay);
            latch.countDown();
        }
    });
    latch.await();
}

90. AndroidPayTest#injectFakeGoogleApiClient()

View license
/* helpers */
private void injectFakeGoogleApiClient(final BraintreeFragment fragment) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    fragment.waitForConfiguration(new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            fragment.mGoogleApiClient = new GoogleApiClient.Builder(mActivityTestRule.getActivity()).addApi(Wallet.API, new Wallet.WalletOptions.Builder().setEnvironment(AndroidPay.getEnvironment(configuration.getAndroidPay())).setTheme(WalletConstants.THEME_LIGHT).build()).build();
            latch.countDown();
        }
    });
    latch.await();
}

91. CardTest#tokenize_failsWithTokenizationKeyAndValidateTrue()

Project: braintree_android
Source File: CardTest.java
View license
@Test(timeout = 10000)
public void tokenize_failsWithTokenizationKeyAndValidateTrue() throws InterruptedException, InvalidArgumentException {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    BraintreeFragment fragment = BraintreeFragment.newInstance(mActivityTestRule.getActivity(), TOKENIZATION_KEY);
    fragment.addListener(new BraintreeErrorListener() {

        @Override
        public void onError(Exception error) {
            assertTrue(error instanceof AuthorizationException);
            assertEquals("Tokenization key authorization not allowed for this endpoint. Please use an authentication method with upgraded permissions", error.getMessage());
            countDownLatch.countDown();
        }
    });
    CardBuilder cardBuilder = new CardBuilder().cardNumber(VISA).expirationDate("08/20").validate(true);
    Card.tokenize(fragment, cardBuilder);
    countDownLatch.await();
}

92. CardTest#assertTokenizationSuccessful()

Project: braintree_android
Source File: CardTest.java
View license
private void assertTokenizationSuccessful(String authorization, CardBuilder cardBuilder) throws InterruptedException, InvalidArgumentException {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    BraintreeFragment fragment = BraintreeFragment.newInstance(mActivityTestRule.getActivity(), authorization);
    fragment.addListener(new PaymentMethodNonceCreatedListener() {

        @Override
        public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) {
            assertEquals("11", ((CardNonce) paymentMethodNonce).getLastTwo());
            countDownLatch.countDown();
        }
    });
    Card.tokenize(fragment, cardBuilder);
    countDownLatch.await();
}

93. ConfigurationManagerTest#isFetchingConfiguration_isFalseInSuccessCallback()

View license
@Test(timeout = 1000)
public void isFetchingConfiguration_isFalseInSuccessCallback() throws InterruptedException {
    final BraintreeFragment fragment = getMockFragment();
    stubConfigurationFromGateway(fragment, stringFromFixture("configuration_with_analytics.json"));
    final CountDownLatch latch = new CountDownLatch(1);
    ConfigurationManager.getConfiguration(fragment, new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            assertFalse(ConfigurationManager.isFetchingConfiguration());
            latch.countDown();
        }
    }, new BraintreeResponseListener<Exception>() {

        @Override
        public void onResponse(Exception e) {
            fail(e.getMessage());
        }
    });
    latch.await();
}

94. ConfigurationManagerTest#getConfiguration_getsConfigFromCacheWhenTimeoutHasNotExpired()

View license
@Test(timeout = 1000)
public void getConfiguration_getsConfigFromCacheWhenTimeoutHasNotExpired() throws InterruptedException {
    BraintreeFragment fragment = getMockFragment();
    writeMockConfiguration(mTokenizationKey.getConfigUrl(), stringFromFixture("configuration.json"));
    final CountDownLatch latch = new CountDownLatch(1);
    ConfigurationManager.getConfiguration(fragment, new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            assertEquals(stringFromFixture("configuration.json"), configuration.toJson());
            latch.countDown();
        }
    }, new BraintreeResponseListener<Exception>() {

        @Override
        public void onResponse(Exception e) {
            fail(e.getMessage());
        }
    });
    latch.await();
}

95. ConfigurationManagerTest#getConfiguration_fetchesConfigFromGatewayWhenCacheIsEmpty()

View license
@Test(timeout = 1000)
public void getConfiguration_fetchesConfigFromGatewayWhenCacheIsEmpty() throws InterruptedException {
    final BraintreeFragment fragment = getMockFragment();
    stubConfigurationFromGateway(fragment, stringFromFixture("configuration_with_analytics.json"));
    final CountDownLatch latch = new CountDownLatch(1);
    ConfigurationManager.getConfiguration(fragment, new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            assertEquals(stringFromFixture("configuration_with_analytics.json"), configuration.toJson());
            latch.countDown();
        }
    }, new BraintreeResponseListener<Exception>() {

        @Override
        public void onResponse(Exception e) {
            fail(e.getMessage());
        }
    });
    latch.await();
}

96. ConfigurationManagerTest#getConfiguration_fetchesConfigurationFromGatewayWhenCachedConfigIsInvalid()

View license
@Test(timeout = 1000)
public void getConfiguration_fetchesConfigurationFromGatewayWhenCachedConfigIsInvalid() throws InterruptedException {
    BraintreeFragment fragment = getMockFragment();
    writeMockConfiguration(mTokenizationKey.getConfigUrl(), "not a config");
    stubConfigurationFromGateway(fragment, stringFromFixture("configuration.json"));
    final CountDownLatch latch = new CountDownLatch(1);
    ConfigurationManager.getConfiguration(fragment, new ConfigurationListener() {

        @Override
        public void onConfigurationFetched(Configuration configuration) {
            assertEquals(stringFromFixture("configuration.json"), configuration.toJson());
            latch.countDown();
        }
    }, new BraintreeResponseListener<Exception>() {

        @Override
        public void onResponse(Exception e) {
            fail(e.getMessage());
        }
    });
    latch.await();
}

97. PaymentMethodTest#getPaymentMethodNonces_getsPaymentMethodsFromServer()

View license
@Test(timeout = 10000)
public void getPaymentMethodNonces_getsPaymentMethodsFromServer() throws InterruptedException, InvalidArgumentException {
    final CountDownLatch latch = new CountDownLatch(1);
    final String clientToken = new TestClientTokenBuilder().build();
    BraintreeFragment fragment = BraintreeFragment.newInstance(mActivity, clientToken);
    getInstrumentation().waitForIdleSync();
    fragment.addListener(new PaymentMethodNoncesUpdatedListener() {

        @Override
        public void onPaymentMethodNoncesUpdated(List<PaymentMethodNonce> paymentMethodNonces) {
            assertEquals(1, paymentMethodNonces.size());
            assertEquals("11", ((CardNonce) paymentMethodNonces.get(0)).getLastTwo());
            latch.countDown();
        }
    });
    tokenize(fragment, new CardBuilder().cardNumber(VISA).expirationMonth("04").expirationYear("17"));
    PaymentMethod.getPaymentMethodNonces(fragment);
    latch.await();
}

98. UnsuccessfulResultTest#assertExceptionIsReturned()

View license
private void assertExceptionIsReturned(final int resultCode, final Exception exception) throws InterruptedException {
    waitForAddPaymentFormHeader().check(matches(isDisplayed()));
    final CountDownLatch latch = new CountDownLatch(1);
    mActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            mFragment.postCallback(exception);
            waitForActivityToFinish(mActivity);
            Map<String, Object> result = getActivityResult(mActivity);
            assertEquals(resultCode, result.get("resultCode"));
            assertEquals(exception, ((Intent) result.get("resultData")).getSerializableExtra(BraintreePaymentActivity.EXTRA_ERROR_MESSAGE));
            latch.countDown();
        }
    });
    latch.await();
}

99. PaymentButtonTest#callsOnClickListener()

View license
@Test
public void callsOnClickListener() throws InvalidArgumentException, InterruptedException {
    PaymentButton paymentButton = getPaymentButton(new PaymentRequest().tokenizationKey(TOKENIZATION_KEY));
    final CountDownLatch latch = new CountDownLatch(1);
    paymentButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            latch.countDown();
        }
    });
    paymentButton.onClick(paymentButton.getView());
    latch.await();
}

100. ResourceRegistrarTest#testFindXAResourceHolderDelegatesAndDoesNotCallUninitialized()

Project: btm
Source File: ResourceRegistrarTest.java
View license
@Test
public void testFindXAResourceHolderDelegatesAndDoesNotCallUninitialized() throws Exception {
    final XAResource resource = mock(XAResource.class);
    final XAResourceProducer uninitializedProducer = createMockProducer("uninitialized");
    CountDownLatch border = new CountDownLatch(1);
    Future future = registerBlockingProducer(uninitializedProducer, border);
    ResourceRegistrar.findXAResourceHolder(resource);
    verify(producer, times(1)).findXAResourceHolder(resource);
    verify(uninitializedProducer, times(0)).findXAResourceHolder(resource);
    border.countDown();
    future.get();
    ResourceRegistrar.findXAResourceHolder(resource);
    verify(producer, times(2)).findXAResourceHolder(resource);
    verify(uninitializedProducer, times(1)).findXAResourceHolder(resource);
}