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.newlandframework.test.RpcParallelTest.java

public static void parallelMultiCalcTask(MultiCalculate calc, int parallel) throws InterruptedException {
    ///*w  ww.  j  a  v a 2 s  .  c  o  m*/
    StopWatch sw = new StopWatch();
    sw.start();

    CountDownLatch signal = new CountDownLatch(1);
    CountDownLatch finish = new CountDownLatch(parallel);

    for (int index = 0; index < parallel; index++) {
        MultiCalcParallelRequestThread client = new MultiCalcParallelRequestThread(calc, signal, finish, index);
        new Thread(client).start();
    }

    signal.countDown();
    finish.await();
    sw.stop();

    String tip = String.format("RPC: [%s] ", sw.getTime());
    System.out.println(tip);
}

From source file:Main.java

public static long time(Executor executor, int concurrency, final Runnable action) throws InterruptedException {
    final CountDownLatch ready = new CountDownLatch(concurrency);
    final CountDownLatch start = new CountDownLatch(1);
    final CountDownLatch done = new CountDownLatch(concurrency);

    for (int i = 0; i < concurrency; i++) {
        executor.execute(new Runnable() {
            @Override/* w  w  w . j  ava 2s . c o m*/
            public void run() {
                ready.countDown(); // Tell timer we're ready
                try {
                    start.await(); // Wait till peers are ready
                    action.run();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    done.countDown(); // Tell timer we're done
                }
            }
        });
    }

    ready.await(); // Wait for all workers to be ready
    long startNanos = System.nanoTime();
    start.countDown(); // And they're off!
    done.await(); // Wait for all workers to finish
    return System.nanoTime() - startNanos;
}

From source file:Main.java

public static void runOnMainSync(final @NonNull Runnable runnable) {
    if (isMainThread()) {
        runnable.run();/*from  w  ww .  ja v a  2  s .  co m*/
    } else {
        final CountDownLatch sync = new CountDownLatch(1);
        runOnMain(new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {
                    sync.countDown();
                }
            }
        });
        try {
            sync.await();
        } catch (InterruptedException ie) {
            throw new AssertionError(ie);
        }
    }
}

From source file:io.undertow.server.handlers.GracefulShutdownTestCase.java

@BeforeClass
public static void setup() {

    shutdown = Handlers.gracefulShutdown(new HttpHandler() {
        @Override/*from   w ww .  java 2  s . c  o  m*/
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            final CountDownLatch countDownLatch = latch2.get();
            final CountDownLatch latch = latch1.get();
            if (latch != null) {
                latch.countDown();
            }
            if (countDownLatch != null) {
                countDownLatch.await();
            }
        }
    });
    DefaultServer.setRootHandler(shutdown);
}

From source file:Main.java

public static CountDownLatch execute(int threadCount, final Runnable task) {
    final CountDownLatch startSignal = new CountDownLatch(1);
    final CountDownLatch startedSignal = new CountDownLatch(threadCount);
    final CountDownLatch doneSignal = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; i++) {
        Thread t = new Thread() {
            public void run() {
                startedSignal.countDown();
                try {
                    startSignal.await();
                } catch (InterruptedException e) {
                    //ignore
                }//ww  w.j av  a2  s  .  c  o  m

                try {
                    task.run();
                } finally {
                    doneSignal.countDown();
                }

            }
        };

        t.start();
    }

    try {
        startedSignal.await();
    } catch (InterruptedException e) {
        //ignore
    }
    startSignal.countDown();
    return doneSignal;
}

From source file:it.stilo.g.util.WeightedZIPFianGenerator.java

public static void generate(WeightedDirectedGraph g, double exponent, int degree, int runner) {

    long time = System.currentTimeMillis();
    final CountDownLatch latch = new CountDownLatch(runner);

    ZipfDistribution dist = new ZipfDistribution(g.size, exponent);
    Thread[] workers = new Thread[runner];
    for (int i = 0; i < runner; i++) {
        workers[i] = new Thread(new WeightedZIPFianGenerator(g, latch, dist, degree, i, runner));
        workers[i].setName("" + i);
        workers[i].start();/*  www.ja  v a  2  s  .  com*/
    }

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

    logger.info(WeightedZIPFianGenerator.class.getName() + "\t" + ((System.currentTimeMillis() - time) / 1000d)
            + "s");
}

From source file:io.servicecomb.foundation.vertx.VertxUtils.java

public static <VERTICLE extends AbstractVerticle> boolean blockDeploy(Vertx vertx, Class<VERTICLE> cls,
        DeploymentOptions options) throws InterruptedException {
    Holder<Boolean> result = new Holder<>();

    CountDownLatch latch = new CountDownLatch(1);
    vertx.deployVerticle(cls.getName(), options, ar -> {
        result.value = ar.succeeded();/* ww  w  .ja v a2  s . co  m*/

        if (ar.failed()) {
            LOGGER.error("deploy vertx failed, cause ", ar.cause());
        }

        latch.countDown();
    });

    latch.await();

    return result.value;
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateBbox() {

    try {/*w  w  w. j a  va 2 s . c  o m*/
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where bbox is null limit 200000;";
        logger.info("loading bbox ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String[]> data = new LinkedBlockingQueue<String[]>();
        while (rs1.next()) {
            data.put(new String[] { rs1.getString("pid") });
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        BboxThread[] threads = new BboxThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new BboxThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateArea(String fid) {

    try {//ww  w . j  a  v a2s.co m
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where area_km is null and st_geometrytype(the_geom) <> 'Point'";
        if (fid != null) {
            sql = sql + " and fid = '" + fid + "'";
        }

        sql = sql + " limit 200000;";

        System.out.println("loading area_km ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String> data = new LinkedBlockingQueue<String>();
        while (rs1.next()) {
            data.put(rs1.getString("pid"));
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        AreaThread[] threads = new AreaThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new AreaThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        rs1.close();
        s1.close();
        conn.close();
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:com.cyberway.issue.crawler.frontier.RecoveryJournal.java

/**
 * Utility method for scanning a recovery journal and applying it to
 * a Frontier.//  ww  w  .  j  a v  a 2 s.c  om
 * 
 * @param source Recover log path.
 * @param frontier Frontier reference.
 * @param retainFailures
 * @throws IOException
 * 
 * @see com.cyberway.issue.crawler.framework.Frontier#importRecoverLog(String, boolean)
 */
public static void importRecoverLog(final File source, final CrawlController controller,
        final boolean retainFailures) throws IOException {
    if (source == null) {
        throw new IllegalArgumentException("Passed source file is null.");
    }
    LOGGER.info("recovering frontier completion state from " + source);

    // first, fill alreadyIncluded with successes (and possibly failures),
    // and count the total lines
    final int lines = importCompletionInfoFromLog(source, controller, retainFailures);

    LOGGER.info("finished completion state; recovering queues from " + source);

    // now, re-add anything that was in old frontier and not already
    // registered as finished. Do this in a separate thread that signals
    // this thread once ENOUGH_TO_START_CRAWLING URIs have been queued. 
    final CountDownLatch recoveredEnough = new CountDownLatch(1);
    new Thread(new Runnable() {
        public void run() {
            importQueuesFromLog(source, controller, lines, recoveredEnough);
        }
    }, "queuesRecoveryThread").start();

    try {
        // wait until at least ENOUGH_TO_START_CRAWLING URIs queued
        recoveredEnough.await();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}