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.microsoft.office.core.FolderAsyncTestCase.java

private void createAndCheck() throws Exception {
    prepareFolder();//from   www . ja va2 s  .  co  m
    final CountDownLatch cdl = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable t) {
            reportError(t);
            cdl.countDown();
        }

        @Override
        public void onSuccess(Void result) {
            try {
                assertTrue(StringUtils.isNotEmpty(folder.getId()));
            } catch (Throwable t) {
                reportError(t);
            }

            cdl.countDown();
        }
    });
    cdl.await();
}

From source file:de.jackwhite20.japs.client.cache.impl.PubSubCacheImpl.java

@Override
public Future<Boolean> has(String key) {

    if (key == null || key.isEmpty()) {
        throw new IllegalArgumentException("key cannot be null or empty");
    }//www  . ja va 2s. co m

    return executorService.submit(() -> {

        int id = CALLBACK_COUNTER.getAndIncrement();

        AtomicBoolean has = new AtomicBoolean(false);

        CountDownLatch countDownLatch = new CountDownLatch(1);

        callbacks.put(id, new Consumer<JSONObject>() {

            @Override
            public void accept(JSONObject jsonObject) {

                has.set(jsonObject.getBoolean("has"));

                countDownLatch.countDown();
            }
        });

        JSONObject jsonObject = new JSONObject().put("op", OpCode.OP_CACHE_HAS.getCode()).put("key", key)
                .put("id", id);

        write(jsonObject);

        countDownLatch.await();

        return has.get();
    });
}

From source file:ufo.remote.calls.benchmark.client.caller.activemq.ActiveMQTester.java

@Override
protected void startTest(final TesterResult result) {

    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.setExecutorService(Executors.newFixedThreadPool(20));

    String url = ActiveMQApacheCamelConfig.JMS_NAME
            + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false";
    AtomicInteger failures = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(result.totalCalls);

    for (int i = 0; i < result.totalCalls; i++) {
        producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() {

            @Override/*w ww  .j  ava2 s. c o m*/
            public void onFailure(final Exchange exchange) {
                failures.incrementAndGet();
                latch.countDown();
            }

            @Override
            public void onComplete(final Exchange exchange) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Received message [{}]", exchange.getIn().getBody());
                }
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();

}

From source file:ufo.remote.calls.benchmark.client.caller.hornetq.HornetQTester.java

@Override
protected void startTest(final TesterResult result) {

    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
    producerTemplate.setExecutorService(Executors.newFixedThreadPool(20));

    String url = HornetQApacheCamelConfig.JMS_NAME
            + ":queue:echo?deliveryPersistent=false&replyToDeliveryPersistent=false";
    AtomicInteger failures = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(result.totalCalls);

    for (int i = 0; i < result.totalCalls; i++) {
        producerTemplate.asyncCallbackRequestBody(url, result.message, new Synchronization() {

            @Override//from   www .j  a  va 2 s.co  m
            public void onFailure(final Exchange exchange) {
                failures.incrementAndGet();
                latch.countDown();
            }

            @Override
            public void onComplete(final Exchange exchange) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Received message [{}]", exchange.getIn().getBody());
                }
                latch.countDown();
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    result.failures = failures.get();

}

From source file:com.alibaba.druid.benckmark.pool.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);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    final TableOperator operator = new TableOperator();
    operator.setDataSource(dataSource);/*  w ww  .  ja  v  a  2 s .  co m*/
    operator.createTable();
    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) {
                        operator.insert();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);

    dumpLatch.countDown();
    operator.dropTable();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    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 + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount));

}

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

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    //ThreadUtils.doSleep(600000);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[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  ww  w . ja v  a2s  .  com
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);
    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    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 + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

From source file:org.wso2.devicemgt.raspberry.agent.SidhdhiQuery.java

/**
 * Make http call to specified endpoint with events
 * @param inEvents/* w  w  w .j  av a  2  s  .c  o m*/
 * @param bulbEP
 * @param logText
 */
private void performHTTPCall(Event[] inEvents, String bulbEP, String logText) {
    if (inEvents != null && inEvents.length > 0) {
        EventPrinter.print(inEvents);
        String url = constants.prop.getProperty(bulbEP);

        CloseableHttpAsyncClient httpclient = null;

        httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        HttpGet request = new HttpGet(url);
        log.info("Bulb Status : " + logText);
        final CountDownLatch latch = new CountDownLatch(1);
        Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse httpResponse) {
                latch.countDown();
            }

            @Override
            public void failed(Exception e) {
                latch.countDown();
            }

            @Override
            public void cancelled() {
                latch.countDown();
            }
        });

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

From source file:com.turn.ttorrent.common.TorrentCreator.java

/**
 * Return the concatenation of the SHA-1 hashes of a file's pieces.
 *
 * <p>//from   www . j  a  v  a 2  s.c o  m
 * Hashes the given file piece by piece using the default Torrent piece
 * length (see {@link #PIECE_LENGTH}) and returns the concatenation of
 * these hashes, as a string.
 * </p>
 *
 * <p>
 * This is used for creating Torrent meta-info structures from a file.
 * </p>
 *
 * @param file The file to hash.
 */
public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes,
        int pieceLength) throws InterruptedException, IOException {
    int npieces = (int) Math.ceil((double) nbytes / pieceLength);
    byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces];
    CountDownLatch latch = new CountDownLatch(npieces);

    ByteBuffer buffer = ByteBuffer.allocate(pieceLength);

    long start = System.nanoTime();
    int piece = 0;
    for (File file : files) {
        logger.info("Hashing data from {} ({} pieces)...",
                new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) });

        FileInputStream fis = FileUtils.openInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.flip();
                    executor.execute(new ChunkHasher(out, piece, latch, buffer));
                    buffer = ByteBuffer.allocate(pieceLength);
                    piece++;
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    logger.info("  ... {}% complete", step);
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.flip();
        executor.execute(new ChunkHasher(out, piece, latch, buffer));
        piece++;
    }

    // Wait for hashing tasks to complete.
    latch.await();
    long elapsed = System.nanoTime() - start;

    logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.",
            new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) });

    return out;
}

From source file:org.martus.client.swingui.PureFxMainWindow.java

public void runInUiThreadAndWait(final Runnable toRun) throws InterruptedException, InvocationTargetException {
    if (Platform.isFxApplicationThread()) {
        toRun.run();/* w ww .  j  ava 2s  .c  om*/
        return;
    }

    final CountDownLatch doneLatch = new CountDownLatch(1);
    Platform.runLater(() -> {
        try {
            toRun.run();
        } finally {
            doneLatch.countDown();
        }
    });

    doneLatch.await();
}

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

@Test
public void multipleFortressUserRequestsThreaded() throws Exception {
    String uname = "mike";
    // Assume the user has now logged in.
    //org.neo4j.graphdb.Transaction t = graphDatabaseService.beginTx();
    String company = "MFURT";
    registrationService.registerSystemUser(new RegistrationBean(company, uname, "password"));
    SecurityContextHolder.getContext().setAuthentication(authA);
    CompanyUser nonAdmin = registrationService.addCompanyUser(uname, company);
    assertNotNull(nonAdmin);//from w  w  w .j a v  a2  s.co  m

    Fortress fortress = fortressService.registerFortress("auditbucket");
    //t.success();
    assertNotNull(fortress);

    CountDownLatch latch = new CountDownLatch(3);
    // Run threaded tests
    FuAction fua1 = new FuAction(fortress, "mike", latch);
    FuAction fua2 = new FuAction(fortress, "mike", latch);
    FuAction fua3 = new FuAction(fortress, "mike", latch);

    Thread fu1 = new Thread(fua1);
    Thread fu2 = new Thread(fua2);
    Thread fu3 = new Thread(fua3);

    fu1.start();
    fu2.start();
    fu3.start();

    latch.await();

    // Check we only get one back
    FortressUser fu = fortressService.getFortressUser(fortress, uname);
    assertNotNull(fu);
    assertFalse(fua1.isFailed());
    assertFalse(fua2.isFailed());
    assertFalse(fua3.isFailed());

}