Example usage for java.util.concurrent CountDownLatch await

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

Introduction

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

Prototype

public void await() throws InterruptedException 

Source Link

Document

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted .

Usage

From source file:com.yahoo.gondola.container.client.ZookeeperShardManagerClientTest.java

@BeforeMethod
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    servers = new HashMap<>();
    shardManagers = new HashMap<>();
    for (String hostId : config.getHostIds()) {
        Gondola gondola = mock(Gondola.class);
        when(gondola.getHostId()).thenReturn(hostId);
        when(gondola.getConfig()).thenReturn(config);
        ShardManager shardManager = mock(ShardManager.class);
        ZookeeperShardManagerServer server = new ZookeeperShardManagerServer("foo",
                zookeeperServer.getConnectString(), gondola, shardManager);
        shardManagers.put(hostId, shardManager);
        servers.put(hostId, server);//from   ww  w  .j  av  a2 s .c o m
    }

    client = new ZookeeperShardManagerClient("foo", "fooClientName", zookeeperServer.getConnectString(),
            config);
    stats = (PathChildrenCache) Whitebox.getInternalState(client, "stats");
    CountDownLatch latch = new CountDownLatch(1);
    this.stats.getListenable().addListener((curatorFramework, pathChildrenCacheEvent) -> {
        if (this.stats.getCurrentData().size() == config.getMembers().size()) {
            latch.countDown();
        }
    });
    latch.await();
}

From source file:com.manpowergroup.cn.icloud.util.Case1.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();/*from   w  w w .  j a va  2s .  co m*/
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);

}

From source file:com.yahoo.sshd.authentication.file.TestPKUpdating.java

private TestContext setup() throws IOException, InterruptedException {
    TestContext testContext = new TestContext();

    // first build dirs.

    if (homeDir.exists()) {
        FileUtils.forceDelete(homeDir);//from w w  w  .j  av a  2 s. c om
    }

    FileUtils.forceMkdir(homeDir);

    // build user directories.
    User[] dirs = new User[normalUsers.length + notUsers.length];
    System.arraycopy(normalUsers, 0, dirs, 0, normalUsers.length);
    System.arraycopy(notUsers, 0, dirs, normalUsers.length, notUsers.length);

    buildSshDirs(homeDir, dirs);

    // this point everyone in users has a public key, so we can load it, and
    // check for them.
    CountDownLatch waiter = new CountDownLatch(1);
    testContext.publickeyAuthenticator = new HomeDirectoryScanningPKAuthenticator(waiter, homeDir,
            Arrays.asList(new Path[] { new File(homeDir, "y").toPath() }));
    testContext.publickeyAuthenticator.start();

    waiter.await();

    checkExist(testContext, normalUsers);
    checkDoesntExist(testContext, notUsers);

    return testContext;
}

From source file:org.callimachusproject.script.ConcurrentResponseTest.java

public void testResponseConcurrent() throws Throwable {
    int n = Runtime.getRuntime().availableProcessors() * 4;
    final CountDownLatch up = new CountDownLatch(1);
    final CountDownLatch down = new CountDownLatch(n);
    final List<Throwable> errors = new ArrayList<Throwable>(n);
    for (int i = 0; i < n; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    up.await();
                    for (int i = 0; i < 100; i++) {
                        testJsonResponse();
                    }/*from  ww w.j a  v  a2  s . co  m*/
                } catch (Throwable e) {
                    e.printStackTrace();
                    synchronized (errors) {
                        errors.add(e);
                    }
                } finally {
                    down.countDown();
                }
            }
        }).start();
    }
    up.countDown();
    down.await();
    synchronized (errors) {
        if (!errors.isEmpty()) {
            throw errors.get(0);
        }
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestQueueSharder.java

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

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    QueueSharder<String, DistributedQueue<String>> sharder = null;
    try {/*from w w w  .  j a  v a2  s.  c  o m*/
        client.start();

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

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

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

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

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

From source file:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL");
                        ResultSet rs = stmt.executeQuery();
                        rs.next();/* w  w  w.j  a v a  2s  .co m*/
                        rs.getInt(1);
                        rs.close();
                        stmt.close();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

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

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

    CountDownLatch latch = new CountDownLatch(count * workers);

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

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

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

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

        listener.onMessage(hzQueue.take());
    }//w  w  w. j av  a 2s .co  m

    latch.await();

    writeTimerData(readsTimer);

}

From source file:hws.util.ZkDataMonitor.java

public ZkClient(String serverAddr, int sessionTimeout) throws IOException, InterruptedException {
    final CountDownLatch connectedSignal = new CountDownLatch(1);
    this.zk = new ZooKeeper(serverAddr, sessionTimeout, new Watcher() {
        @Override//  w  w  w  .ja v  a2  s .c  o m
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                connectedSignal.countDown();
            }
        }
    });
    connectedSignal.await();
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkController.java

@Override
synchronized public void stop() {

    coordinator.release();//from   w  w w.  ja v a2s  .  co  m
    super.stop();

    log().info("BenchmarkController going down in 5 Seconds");

    final CountDownLatch brokerStopLatch = new CountDownLatch(1);
    final ScheduledThreadPoolExecutor waiter = new ScheduledThreadPoolExecutor(1);
    waiter.schedule(new Runnable() {
        public void run() {
            brokerStopLatch.countDown();
            waiter.shutdown();
        }
    }, 5, TimeUnit.SECONDS);

    try {
        brokerStopLatch.await();
    } catch (InterruptedException e1) {
    }

    if (broker != null) {
        log().info("Stopping embedded broker for Benchmark framework: ");
        try {
            broker.stop();
        } catch (Exception e) {
            // log().error("Embedded broker could not be stopped.", e);
        }
    }
}

From source file:com.auditbucket.test.functional.TestCallerRef.java

/**
 * Multi threaded test that tests to make sure duplicate Doc Types and Headers are not created
 *
 * @throws Exception//from  w  w  w.j a v a  2 s . c o  m
 */
@Test
public void duplicateCallerRefKeysAndDocTypesNotCreated() throws Exception {
    cleanUpGraph(); // No transaction so need to clear down the graph
    regService.registerSystemUser(new RegistrationBean(monowai, mike, "bah"));

    Fortress fortress = fortressEP
            .registerFortress(new FortressInputBean("auditTest" + System.currentTimeMillis()), null).getBody();

    String docType = "TestAuditX";
    String callerRef = "ABC123X";

    CountDownLatch latch = new CountDownLatch(3);

    CallerRefRunner ta = addRunner(fortress, docType, callerRef, latch);
    CallerRefRunner tb = addRunner(fortress, docType, callerRef, latch);
    CallerRefRunner tc = addRunner(fortress, docType, callerRef, latch);
    latch.await();
    Assert.assertNotNull(trackService.findByCallerRef(fortress, docType, callerRef));
    assertEquals(true, ta.isWorking());
    assertEquals(true, tb.isWorking());
    assertEquals(true, tc.isWorking());

}