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.alibaba.druid.benckmark.pool.Case3.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    final AtomicInteger count = new AtomicInteger();
    final AtomicInteger errorCount = new AtomicInteger();

    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();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery(sql);
                        while (rs.next()) {
                            rs.getInt(1);
                        }//from   www  . java 2s  .c  o m
                        rs.close();
                        stmt.close();

                        conn.close();
                        count.incrementAndGet();
                    }
                } catch (Throwable ex) {
                    errorCount.incrementAndGet();
                    ex.printStackTrace();
                } finally {
                    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;

    Assert.assertEquals(LOOP_COUNT * threadCount, count.get());
    Thread.sleep(1);

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

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case4.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();

                        int mod = i % 500;

                        String sql = SQL; // + " AND ROWNUM <= " + (mod + 1);
                        PreparedStatement stmt = conn.prepareStatement(sql);
                        stmt.setInt(1, 61);
                        ResultSet rs = stmt.executeQuery();
                        int rowCount = 0;
                        while (rs.next()) {
                            rowCount++;//from   w ww.ja va  2s .  c om
                        }
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                        Assert.isTrue(conn.isClosed());
                    }
                } 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:io.kahu.hawaii.util.call.dispatch.RequestDispatcher.java

public <T> Set<Response<T>> execute(RequestFactory<T> requestFactory, boolean waitForAnswers)
        throws ServerException {
    Set<Response<T>> responses = new HashSet<>();
    CountDownLatch latch = new CountDownLatch(requestFactory.getNumberOfRequests());
    AbortableRequest<T> request = requestFactory.getNextRequest();
    while (request != null) {
        request.setLatch(latch);//from w  w w. j  av a 2s  . c  o  m
        responses.add(executeAsync(request));
        request = requestFactory.getNextRequest();
    }

    if (waitForAnswers) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return responses;
}

From source file:com.google.api.ads.adwords.awreporting.server.kratu.KratuProcessor.java

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

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

    RunnableKratu runnableKratu = createRunnableKratu(topAccountId, accountIdsSet, storageHelper, dateStart,
            dateEnd);/*from w  w w  .ja va 2 s  .  c  o m*/

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    runnableKratu.setLatch(latch);
    executorService.execute(runnableKratu);

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

From source file:com.tenforce.lodms.extractors.CkanHarvester.java

public void harvest(List<String> datasetIds)
        throws RDFHandlerException, ExtractException, DatatypeConfigurationException {
    if (datasetIds.isEmpty()) {
        throw new ExtractException("no datasets specified");
    }//ww w  .j  a  va2s. com
    if (enableProvenance)
        addCatalogProvenance();

    MapToRdfConverter converter = new MapToRdfConverter(predicatePrefix, ignoredKeys, handler);
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    CountDownLatch barrier = new CountDownLatch(datasetIds.size());
    Catalog catalog = new Catalog(baseUri, subjectPrefix);

    try {
        for (String datasetId : datasetIds) {
            executorService.execute(new DataSetHarvester(catalog, converter, handler, apiUri, datasetId,
                    barrier, warnings, httpMethod));
        }
        executorService.shutdown();
        barrier.await();
    } catch (Exception e) {
        executorService.shutdownNow();
        throw new ExtractException(e.getMessage(), e);
    }

}

From source file:com.github.dozermapper.core.DozerBeanMapperTest.java

@Test
public void shouldBeThreadSafe() throws Exception {
    Mapper mapper = DozerBeanMapperBuilder.create().withMappingFiles("mappings/testDozerBeanMapping.xml")
            .build();//from w w  w . ja v  a2  s.  c om

    final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);

    for (int i = 0; i < THREAD_COUNT; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    mapper.map(new TestObject(), TestObjectPrime.class);
                } finally {
                    latch.countDown();
                }
            }
        }).start();

    }
    latch.await();
    assertTrue(exceptions.isEmpty());
}

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

@Test
public void testAdditions() throws Exception {
    DistributedPriorityQueue<Integer> queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*w  w  w.j av a  2 s. c o m*/
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        QueueSerializer<Integer> serializer = new IntSerializer() {
            @Override
            public Integer deserialize(byte[] bytes) {
                // gets called in the Queue's event processing thread
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    // ignore
                }
                return super.deserialize(bytes);
            }
        };
        BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(
                Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, serializer, "/test").buildPriorityQueue(1);
        queue.start();

        for (int i = 0; i < 10; ++i) {
            queue.put(10, 10);
            if (i == 0) {
                queue.put(1, 1);
                latch.countDown();
            }
        }

        assertOrdering(consumer, 10);
    } finally {
        IOUtils.closeQuietly(queue);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.yahoo.gondola.container.ZookeeperRegistryClientTest.java

@Test
public void testAddListener() throws Exception {
    ArgumentCaptor<RegistryClient.Entry> args = ArgumentCaptor.forClass(RegistryClient.Entry.class);

    InetSocketAddress addr = new InetSocketAddress(1234);
    CountDownLatch latch = new CountDownLatch(1);
    registryClient.addListener(entry1 -> {
        if (entry1.gondolaAddress.equals(addr)) {
            latch.countDown();//from   ww  w  . j  a v a 2 s. co  m
        }
    });
    String hostId = registryClient.register(SITE_1_HOST_1_CLUSTER, addr,
            URI.create("https://api1.yahoo.com:4443"));
    latch.await();
    verify(listener, times(1)).accept(args.capture());
    RegistryClient.Entry entry = args.getValue();
    assertEquals(entry.hostId, hostId);
}

From source file:gov.va.isaac.workflow.engine.RemoteSynchronizer.java

/**
 * Request a remote synchronization. This call blocks until the operation is complete,
 * or the thread is interrupted./*from  w  ww. ja v  a2s . c  om*/
 * 
 * @throws InterruptedException
 */
public SynchronizeResult blockingSynchronize() throws InterruptedException {
    log.info("Queuing a blocking sync request");
    final MutableObject<SynchronizeResult> result = new MutableObject<SynchronizeResult>();
    final CountDownLatch cdl = new CountDownLatch(1);
    Consumer<SynchronizeResult> callback = new Consumer<SynchronizeResult>() {
        @Override
        public void accept(SynchronizeResult t) {
            result.setValue(t);
            cdl.countDown();
        }
    };

    synchronize(callback);
    cdl.await();
    return result.getValue();
}

From source file:com.test.database.jedis.TestJedisEvalLua.java

public static void testTryGetHongBao() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(threadCount);
    System.err.println("start:" + System.currentTimeMillis() / 1000);
    watch.start();/*from  w  w w .ja v  a  2s  .co  m*/
    for (int i = 0; i < threadCount; ++i) {
        final int temp = i;
        Thread thread = new Thread() {
            public void run() {
                String sha = null;
                Jedis jedis = new Jedis(host, port);
                sha = jedis.scriptLoad(tryGetHongBaoScript);
                if (temp == 0) {
                    System.err.println("SCRIPT SHA: " + sha);
                }
                int j = honBaoCount / threadCount * temp;
                while (true) {
                    // Object object = jedis.eval(tryGetHongBaoScript, 4,
                    // hongBaoList, hongBaoConsumedList,
                    // hongBaoConsumedMap, "" + j);
                    Object object = jedis.evalsha(sha, 4, hongBaoList, hongBaoConsumedList, hongBaoConsumedMap,
                            "" + j);
                    j++;
                    if (object != null) {
                        System.out.println("Get hongBao:" + object);
                    } else if (jedis.llen(hongBaoList) == 0) {
                        break;
                    }
                }
                latch.countDown();
                jedis.close();
            }
        };
        thread.start();
    }

    latch.await();
    watch.stop();

    System.err.println("time:" + watch.getTime() + " ms");
    System.err.println("speed:" + honBaoCount / watch.getTime());
    System.err.println("end:" + System.currentTimeMillis() / 1000);
}