List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.griddynamics.jagger.JaggerLauncher.java
private static void launchKernel(final URL directory) { LaunchTask runKernel = new LaunchTask() { private Kernel kernel; @Override/*from www . jav a2s . c o m*/ public void run() { log.info("Starting Kernel"); ApplicationContext context = loadContext(directory, KERNEL_CONFIGURATION, environmentProperties); final CountDownLatch latch = new CountDownLatch(1); final Coordinator coordinator = (Coordinator) context.getBean("coordinator"); kernel = (Kernel) context.getBean("kernel"); toTerminate(kernel); Runnable kernelRunner = new Runnable() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } kernel.run(); } }; getExecutor().execute(kernelRunner); coordinator.waitForReady(); coordinator.waitForInitialization(); latch.countDown(); } }; builder.addBackgroundTask(runKernel); }
From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceInstance.java
private static boolean waitForListeningNotification(OSProcessHandler processHandler, Project project) { final CountDownLatch countDownLatch = new CountDownLatch(1); final Ref<Boolean> result = new Ref<>(false); ProcessAdapter listener = new ProcessAdapter() { public void onTextAvailable(ProcessEvent event, Key outputType) { if (!StringUtil.isEmpty(event.getText())) { if (outputType == ProcessOutputTypes.STDOUT || outputType == ProcessOutputTypes.SYSTEM) { if (log.isDebugEnabled()) { log.debug("Language Service response: " + event.getText()); }/*from www .java 2 s .co m*/ final String text = event.getText().trim(); if (text.startsWith("JS GraphQL listening on")) { result.set(true); countDownLatch.countDown(); } } else if (outputType == ProcessOutputTypes.STDERR) { result.set(false); countDownLatch.countDown(); JSGraphQLLanguageUIProjectService.showConsole(project); } } } public void processTerminated(ProcessEvent event) { countDownLatch.countDown(); } }; processHandler.addProcessListener(listener); processHandler.startNotify(); try { log.debug("Start waiting for ready start"); countDownLatch.await(30L, TimeUnit.SECONDS); log.debug("End waiting for process starting. Result " + result.get()); } catch (InterruptedException e) { log.debug("Process interrupted while waiting ready state", e); } processHandler.removeProcessListener(listener); return result.get(); }
From source file:com.frostwire.AzureusStarter.java
private static synchronized void azureusInit() { try {/*from w ww .j a v a 2 s . co m*/ if (isAzureusCoreStarted()) { LOG.debug("azureusInit(): core already started. skipping."); return; } } catch (Exception ignore) { } Application.setApplication( CommonUtils.getUserSettingsDir().getAbsolutePath() + File.separator + "appwork" + File.separator); File jdHome = new File( CommonUtils.getUserSettingsDir().getAbsolutePath() + File.separator + "jd_home" + File.separator); if (!jdHome.exists()) { jdHome.mkdir(); } JDUtilities.setJDHomeDirectory(jdHome); JDUtilities.getConfiguration().setProperty("DOWNLOAD_DIRECTORY", SharingSettings.TORRENT_DATA_DIR_SETTING.getValue().getAbsolutePath()); File azureusUserPath = new File( CommonUtils.getUserSettingsDir() + File.separator + "azureus" + File.separator); if (!azureusUserPath.exists()) { azureusUserPath.mkdirs(); } System.setProperty("azureus.loadplugins", "0"); // disable third party azureus plugins System.setProperty("azureus.config.path", azureusUserPath.getAbsolutePath()); System.setProperty("azureus.install.path", azureusUserPath.getAbsolutePath()); if (!AzureusCoreFactory.isCoreAvailable()) { //This does work org.gudy.azureus2.core3.util.SystemProperties.APPLICATION_NAME = "azureus"; org.gudy.azureus2.core3.util.SystemProperties.setUserPath(azureusUserPath.getAbsolutePath()); if (!SharingSettings.TORRENTS_DIR_SETTING.getValue().exists()) { SharingSettings.TORRENTS_DIR_SETTING.getValue().mkdirs(); } COConfigurationManager.setParameter("Auto Adjust Transfer Defaults", false); COConfigurationManager.setParameter("General_sDefaultTorrent_Directory", SharingSettings.TORRENTS_DIR_SETTING.getValue().getAbsolutePath()); try { AZUREUS_CORE = AzureusCoreFactory.create(); } catch (AzureusCoreException coreException) { //so we already had one eh... if (AZUREUS_CORE == null) { AZUREUS_CORE = AzureusCoreFactory.getSingleton(); } } //to guarantee a synchronous start final CountDownLatch signal = new CountDownLatch(1); AZUREUS_CORE.addLifecycleListener(new AzureusCoreLifecycleListener() { @Override public boolean syncInvokeRequired() { return false; } @Override public void stopping(AzureusCore core) { core.getGlobalManager().pauseDownloads(); } @Override public void stopped(AzureusCore core) { } @Override public boolean stopRequested(AzureusCore core) throws AzureusCoreException { return false; } @Override public void started(AzureusCore core) { signal.countDown(); } @Override public boolean restartRequested(AzureusCore core) throws AzureusCoreException { return false; } @Override public boolean requiresPluginInitCompleteBeforeStartedEvent() { return false; } @Override public void componentCreated(AzureusCore core, AzureusCoreComponent component) { } }); if (!AZUREUS_CORE.isStarted() && !AZUREUS_CORE.isRestarting()) { AZUREUS_CORE.start(); } AZUREUS_CORE.getGlobalManager().resumeDownloads(); LOG.debug("azureusInit(): core.start() waiting..."); try { signal.await(); LOG.debug("azureusInit(): core started..."); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:de.codesourcery.eve.skills.ui.utils.ParallelUITasksRunner.java
public static boolean submitParallelTasks(final ApplicationThreadManager threadManager, final UITask parent, UITask... children) {// ww w . j a v a2 s. c o m final AtomicInteger childSuccesses = new AtomicInteger(0); final AtomicInteger childFailures = new AtomicInteger(0); if (parent == null) { throw new IllegalArgumentException("parent task cannot be NULL"); } if (ArrayUtils.isEmpty(children)) { throw new IllegalArgumentException("Need to provide at least one child task"); } final CyclicBarrier startBarrier = new CyclicBarrier(children.length + 1) { @Override public void reset() { System.out.println("========== resetting start barrier =========== "); super.reset(); } }; final CountDownLatch childrenTerminated = new CountDownLatch(children.length); int submittedChildren = 0; for (final UITask child : children) { final UITask wrapped = new UITask() { @Override public void successHook() throws Exception { boolean success = false; try { child.successHook(); success = true; } finally { if (success) { childSuccesses.incrementAndGet(); } else { childFailures.incrementAndGet(); } childrenTerminated.countDown(); } } @Override public void beforeExecution() { child.beforeExecution(); // note: when this method throws an exception , #failure() is invoked } @Override public void setEnabledHook(boolean yesNo) { child.setEnabledHook(yesNo); } @Override public void failureHook(Throwable t) throws Exception { try { child.failureHook(t); } finally { childFailures.incrementAndGet(); childrenTerminated.countDown(); } } @Override public void cancellationHook() { try { child.cancellationHook(); } finally { childFailures.incrementAndGet(); childrenTerminated.countDown(); } } @Override public String getId() { return child.getId(); } @Override public void run() throws Exception { try { if (log.isTraceEnabled()) { log.trace("run(): Child task " + getId() + " is now waiting."); } startBarrier.await(); // will BrokenBarrierException if any of the child tasks could not be started, } catch (InterruptedException e) { log.error("run(): Child task " + getId() + " was interrupted"); Thread.currentThread().interrupt(); } catch (BrokenBarrierException e) { log.error("run(): Child task" + getId() + " aborted, barrier broken."); throw new RuntimeException( "Child task not started because another child task failed submitTask()"); } if (log.isTraceEnabled()) { log.trace("run(): Child task " + getId() + " is now running."); } child.run(); } }; if (null == threadManager.submitTask(wrapped, false)) { log.error("submitParallelTasks(): Failed to submit child " + child); // note: I wait for (submittedChildren-childFailures) because some // child task may have already failed before reaching their run() method while (startBarrier.getNumberWaiting() != (submittedChildren - childFailures.get())) { log.info("submitParallelTasks(): Waiting for all child tasks to reach barrier ( " + startBarrier.getNumberWaiting() + " waiting)"); try { java.lang.Thread.sleep(500); } catch (Exception e) { } ; } startBarrier.reset(); // will cause all child threads waiting on this barrier to terminate return false; } submittedChildren++; } /* * All children are submitted and waiting at the barrier. */ final boolean parentSubmitted = null != threadManager.submitTask("Control thread of " + parent.getId(), new Runnable() { @Override public void run() { try { while (true) { try { log.debug("run(): Parent task " + parent.getId() + " is waiting for it's children to start..."); startBarrier.await(5, TimeUnit.SECONDS); break; } catch (TimeoutException e) { if (childFailures.get() != 0) { runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent task " + parent.getId() + " failed to start."); return; } } } } catch (InterruptedException e) { runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " was interrupted while waiting" + " for it's children to start."); startBarrier.reset(); // let children fail. Thread.currentThread().interrupt(); return; } catch (BrokenBarrierException e) { runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " failed to wait for it's children"); throw new RuntimeException("Internal error - task " + parent.getId() + " failed to wait for it's children?"); } log.debug("run(): Task " + parent.getId() + " is waiting for it's children to finish"); try { childrenTerminated.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); runFailureHookOnEDT(parent, "Parent task " + parent.getId() + " was interrupted while waiting for it's children"); return; } log.info("run(): All children of parent task " + parent.getId() + " have finished ( success: " + childSuccesses.get() + " / failure: " + childFailures.get() + ")"); if (childFailures.get() > 0) { runFailureHookOnEDT(parent, childFailures.get() + " child tasks of parent " + parent.getId() + " have FAILED."); return; } if (null == threadManager.submitTask(parent, false)) { runFailureHookOnEDT(parent, "Failed to submit parent task " + parent.getId()); return; } } }, false); if (!parentSubmitted) { log.debug("submitParallelTasks(): Failed to submit parent task " + parent.getId() + " , terminating child tasks."); startBarrier.reset(); // aborts all child tasks with a BrokenBarrierException } return parentSubmitted; }
From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java
public static <H extends ServiceHost> void deleteAllDocuments(H host, String referrer, long timeout, TimeUnit timeUnit) throws Throwable { QueryTask.Query selfLinkClause = new QueryTask.Query() .setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK).setTermMatchValue("/photon/*") .setTermMatchType(QueryTask.QueryTerm.MatchType.WILDCARD); QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification(); querySpecification.query.addBooleanClause(selfLinkClause); QueryTask queryTask = QueryTask.create(querySpecification).setDirect(true); NodeGroupBroadcastResponse queryResponse = ServiceHostUtils.sendBroadcastQueryAndWait(host, referrer, queryTask);//from w w w . j ava 2 s. c o m Set<String> documentLinks = QueryTaskUtils.getBroadcastQueryDocumentLinks(queryResponse); if (documentLinks == null || documentLinks.size() <= 0) { return; } CountDownLatch latch = new CountDownLatch(1); OperationJoin.JoinedCompletionHandler handler = new OperationJoin.JoinedCompletionHandler() { @Override public void handle(Map<Long, Operation> ops, Map<Long, Throwable> failures) { if (failures != null && !failures.isEmpty()) { for (Throwable e : failures.values()) { logger.error("deleteAllDocuments failed", e); } } latch.countDown(); } }; Collection<Operation> deletes = new LinkedList<>(); for (String documentLink : documentLinks) { Operation deleteOperation = Operation.createDelete(UriUtils.buildUri(host, documentLink)).setBody("{}") .setReferer(UriUtils.buildUri(host, referrer)); deletes.add(deleteOperation); } OperationJoin join = OperationJoin.create(deletes); join.setCompletion(handler); join.sendWith(host); if (!latch.await(timeout, timeUnit)) { throw new TimeoutException(String .format("Deletion of all documents timed out. Timeout:{%s}, TimeUnit:{%s}", timeout, timeUnit)); } }
From source file:com.fusesource.forge.jmstest.threading.SteppablePool.java
public SteppablePool(long idleTimeout, int minPoolSize, int maxPoolSize) { this.idleTimeout = idleTimeout; this.minPoolSize = minPoolSize; this.maxPoolSize = maxPoolSize; controller = new Runnable() { public void run() { log().info("Steppable pool is started."); while (true) { if (isIdle()) { if (System.currentTimeMillis() - lastUnidle > getIdleTimeout()) { break; }/*from w ww . j ava2 s.c o m*/ } else { log.debug("Steppable pool is still busy."); } try { Thread.sleep(getIdleTimeout()); } catch (InterruptedException ie) { break; } } log().info("Steppable pool is finished."); for (CountDownLatch latch : latches) { latch.countDown(); } executor.shutdown(); } }; new Thread(controller).start(); }
From source file:com.facebook.LinkBench.LinkBenchDriver.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. */// w w w . j av a 2s .co m static long concurrentExec(final List<? extends Runnable> tasks) 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(); } doneSignal.await(); // wait for all threads to finish long endTime = System.currentTimeMillis(); return endTime - startTime.get(); }
From source file:io.fabric8.msg.jnatsd.TestLoad.java
@Test public void testLoad() throws Exception { EmbeddedConnection subConnection = new EmbeddedConnection(jNatsd); subConnection.start();// w ww.j a va 2 s.co m final int count = 1000; CountDownLatch countDownLatch = new CountDownLatch(count); subConnection.addSubscriber("foo", msg -> { countDownLatch.countDown(); }); EmbeddedConnection pubConnection = new EmbeddedConnection(jNatsd); pubConnection.start(); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { String test = "Test" + i; pubConnection.publish("foo", "bah", test.getBytes()); } countDownLatch.await(10, TimeUnit.SECONDS); Assert.assertEquals(0, countDownLatch.getCount()); long finish = System.currentTimeMillis(); long totalTime = finish - start; int messagesPerSecond = (int) ((count * 1000) / totalTime); System.err.println("Duration to pub/sub " + count + " messages = " + totalTime + " ms = " + messagesPerSecond + " msg/sec"); pubConnection.close(); subConnection.close(); }
From source file:com.fusesource.forge.jmstest.threading.LimitedTimeScheduledExecutor.java
public void release() { synchronized (lock) { if (!isRunning) { return; }//from w w w . ja v a 2 s . c o m if (executor != null) { log().debug("Closing " + getName()); executor.shutdown(); executor = null; } synchronized (waiting) { while (waiting.size() > 0) { CountDownLatch l = waiting.remove(0); l.countDown(); } } latch.countDown(); getReleaseManager().deregister(this); } }
From source file:com.watchrabbit.executor.spring.AnnotationDiscoverTest.java
@Test public void shouldCloseCircuit() throws Exception { try {//from w w w .j av a 2 s.c o m annotatedService.fastClose(() -> { throw new Exception(); }); failBecauseExceptionWasNotThrown(Exception.class); } catch (Exception ex) { } Sleep.untilTrue(Boolean.TRUE::booleanValue, 10, TimeUnit.MILLISECONDS); CountDownLatch latch = new CountDownLatch(1); annotatedService.fastClose(() -> { latch.countDown(); return "ok"; }); assertThat(latch.getCount()).isEqualTo(0); }