List of usage examples for java.util.concurrent CountDownLatch await
public void await() throws InterruptedException
From source file:org.smartfrog.services.anubis.Node.java
public void start() { Thread daemon = new Thread(new Runnable() { @Override//from w ww . j a v a 2 s. c o m public void run() { try { startLatch.countDown(); startLatch.await(); Thread.sleep(500); } catch (InterruptedException e1) { return; } for (int counter = 0; counter < messagesToSend; counter++) { try { Thread.sleep(RANDOM.nextInt(maxSleep)); } catch (InterruptedException e) { return; } SendHistory sent = new SendHistory(System.currentTimeMillis(), counter); send(counter); sendHistory.add(sent); } try { for (CountDownLatch latch : msgReceivedLatches.values()) { latch.await(); } endLatch.countDown(); endLatch.await(); Thread.sleep(500); } catch (InterruptedException e) { return; } } }, "Run Thread for: " + context.getBean(Identity.class).toString()); daemon.setDaemon(true); daemon.start(); }
From source file:adb4j.executor.CmdExecutor.java
/** * Runs a general command and wait for it to exit. * * @param command The command you want to run * @return//from w w w . j a va 2s. c o m * @throws IOException * @see CmdResult * @see runAsync */ public CmdResult run(String command) throws IOException { CountDownLatch countDownLatch = new CountDownLatch(1); defaultHandler.countDownLatch = Optional.of(countDownLatch); runAsync(command, defaultHandler, false); try { countDownLatch.await(); } catch (InterruptedException ex) { } return new CmdResult(exitValue, exception, defaultHandler.getOutputStream(), defaultHandler.getErrorStream()); }
From source file:com.playhaven.android.diagnostic.test.PHTestCase.java
protected void waitForReady(Object toTest) { CountDownLatch latch = latches.get(toTest.getClass().getSimpleName()); if (latch != null) { try {//from w w w .ja v a2 s.c o m latch.await(); } catch (InterruptedException e) { /* no-op */ } } }
From source file:com.fusesource.forge.jmstest.threading.LimitedTimeScheduledExecutor.java
public void waitUntilFinished() { synchronized (lock) { if (!isRunning) { return; }//from w w w .j a v a 2 s .co m } CountDownLatch latch = new CountDownLatch(1); synchronized (waiting) { waiting.add(latch); } try { latch.await(); } catch (InterruptedException e) { } }
From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java
/** * updateComment updates the text field of a comment * @throws InterruptedException //from w w w. ja v a 2 s .c om */ public static void updateComment(final Comment comment, final String str) throws ClientProtocolException, IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread() { @SuppressWarnings("hiding") @Override public void run() { HttpPost updateRequest = new HttpPost(updateAddress + comment.getUuid() + "/_update/"); String query = "{\"script\" : \"ctx._source." + str + "}"; StringEntity stringentity; try { stringentity = new StringEntity(query); updateRequest.setHeader("Accept", "application/json"); updateRequest.setEntity(stringentity); latch.countDown(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }; thread.start(); latch.await(); }
From source file:org.springframework.cloud.stream.FluxTest.java
@Test public void testSimpleSubscriber() throws Exception { final CountDownLatch latch = new CountDownLatch(10); emitter.subscribe(s -> {//from www . j a v a 2s.c o m System.out.println(s); latch.countDown(); }); latch.await(); }
From source file:org.neo4j.ogm.integration.TransactionRequestHandlerTest.java
@Test public void shouldBeAbleToStartMultipleConcurrentLongRunningTransactions() throws InterruptedException { SessionFactory sessionFactory = new SessionFactory(); session = sessionFactory.openSession(neo4jRule.url()); int numThreads = 100; ExecutorService executor = Executors.newFixedThreadPool(numThreads); CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { executor.submit(new TransactionStarter(latch)); }//from w w w. j a v a 2s . c om latch.await(); // pause until the count reaches 0 System.out.println("all threads running"); executor.shutdownNow(); }
From source file:com.facebook.LinkBench.LinkBenchDriverInj.java
/** * Start all runnables at the same time. Then block till all * tasks are completed. Returns the elapsed time (in millisec) * since the start of the first task to the completion of all tasks. *///from w w w .j av a2 s .c om static long concurrentExec(final List<? extends Runnable> tasks, boolean runReq, Random rng) throws Throwable { final CountDownLatch startSignal = new CountDownLatch(tasks.size()); final CountDownLatch doneSignal = new CountDownLatch(tasks.size()); final AtomicLong startTime = new AtomicLong(0); for (final Runnable task : tasks) { new Thread(new Runnable() { @Override public void run() { /* * Run a task. If an uncaught exception occurs, bail * out of the benchmark immediately, since any results * of the benchmark will no longer be valid anyway */ try { startSignal.countDown(); startSignal.await(); long now = System.currentTimeMillis(); startTime.compareAndSet(0, now); task.run(); } catch (Throwable e) { Logger threadLog = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER); threadLog.error("Unrecoverable exception in worker thread:", e); Runtime.getRuntime().halt(1); } doneSignal.countDown(); } }).start(); } if (runReq) { /* Do logic with injection rate. All tasks above should be waiting on tasks */ long reqTime_ns = System.nanoTime(); double requestrate_ns = ((double) requestrate) / 1e9; long numRequests = ConfigUtil.getLong(props, Config.NUM_REQUESTS); System.out.println("Processing Requests:" + genQueue); try { long runStartTime = System.currentTimeMillis(); long curTime = runStartTime; for (int i = 0; i < numRequests; i++) { reqTime_ns = Timer.waitExpInterval(rng, reqTime_ns, requestrate_ns); // System.out.println("Request time: "+System.currentTimeMillis()); genQueue.put(System.nanoTime()); curTime = System.currentTimeMillis(); if (curTime > runStartTime + maxTime * 1000) { System.out.println("Time limit elapsed"); break; } } // Send stop signal to all requesters for (int i = 0; i < nrequesters; i++) { genQueue.put((long) 0); } } catch (Exception e) { e.printStackTrace(); } } doneSignal.await(); // wait for all threads to finish long endTime = System.currentTimeMillis(); return endTime - startTime.get(); }
From source file:jp.realglobe.util.uploader.DelayedWatcherTest.java
/** * ?????????/*from ww w.j av a2 s . co m*/ * @throws Exception */ @Test public void testLatestOnly() throws Exception { final long delay = 1_000L; final CountDownLatch stopper = new CountDownLatch(1); final DelayedWatcher watcher = new DelayedWatcher(this.directory, delay, true, path -> { stopper.await(); this.detected.offer(path); }); this.executor.submit(watcher); Thread.sleep(1_000L); Files.createFile(this.directory.resolve("0")); Thread.sleep(1_000L + delay); // 0 ?? final int n = 10; for (int i = 1; i < n; i++) { Files.createFile(this.directory.resolve("" + i)); } Thread.sleep(1_000L); // 1,...,9 ??? stopper.countDown(); // 0 ???? Assert.assertEquals(this.directory.resolve("0"), this.detected.poll(1_000L, TimeUnit.MILLISECONDS)); Assert.assertEquals(this.directory.resolve("9"), this.detected.poll(1_000L + delay, TimeUnit.MILLISECONDS)); Assert.assertNull(this.detected.poll(1_000L, TimeUnit.MILLISECONDS)); }
From source file:com.jolbox.benchmark.BenchmarkTests.java
/** * Helper function./*w ww .j av a 2s . co m*/ * * @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 (int i = 0; i <= threads; i++) { // create and start threads ecs.submit(new ThreadTesterUtil(startSignal, doneSignal, cpds, workDelay, doPreparedStatement)); } startSignal.countDown(); // START TEST! 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; }