List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:co.paralleluniverse.photon.Photon.java
private static void spawnProgressCheckThread(final Logger log, final int duration, final int checkCycle, final CountDownLatch cdl) { if (checkCycle > 0) new Thread(() -> { try { Thread.sleep(duration * 1000); long prevCount = cdl.getCount(); while (!cdl.await(checkCycle, TimeUnit.MILLISECONDS)) { log.info("Checking progress"); final long currCount = cdl.getCount(); if (currCount == prevCount) { log.warn("No progress, exiting"); System.exit(-1); }//from ww w . j a v a 2 s . c o m prevCount = currCount; } } catch (final InterruptedException ex) { throw new RuntimeException(ex); } }).start(); }
From source file:co.paralleluniverse.photon.Photon.java
private static void spawnStatisticsThread(final int printCycle, CountDownLatch cdl, final Logger log, final Meter requestMeter, final Meter responseMeter, final Meter errorsMeter, final String testName) { if (printCycle > 0) new Thread(() -> { try { while (!cdl.await(printCycle, TimeUnit.MILLISECONDS)) { printStatisticsLine(log, requestMeter, responseMeter, errorsMeter, testName, cdl); }//from w ww. jav a2s .c o m } catch (final InterruptedException ex) { throw new RuntimeException(ex); } }).start(); }
From source file:com.kurento.kmf.media.AbstractAsyncBaseTest.java
protected static void releaseMediaObject(final MediaObject mo) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); mo.release(new Continuation<Void>() { @Override// www .jav a2 s . c o m public void onSuccess(Void result) { latch.countDown(); } @Override public void onError(Throwable cause) { throw new KurentoMediaFrameworkException(cause); } }); Assert.assertTrue(latch.await(500, MILLISECONDS)); }
From source file:org.apache.camel.component.box.internal.BoxClientHelper.java
public static void getOAuthToken(BoxConfiguration configuration, CachedBoxClient cachedBoxClient) throws AuthFatalFailureException, BoxRestException, BoxServerException, InterruptedException { final BoxClient boxClient = cachedBoxClient.getBoxClient(); synchronized (boxClient) { if (boxClient.isAuthenticated()) { return; }//from ww w.ja v a2 s. c om LOG.debug("Getting OAuth token for {}...", cachedBoxClient); final IAuthSecureStorage authSecureStorage = cachedBoxClient.getSecureStorage(); if (authSecureStorage != null && authSecureStorage.getAuth() != null) { LOG.debug("Using secure storage for {}", cachedBoxClient); // authenticate using stored refresh token boxClient.authenticateFromSecureStorage(authSecureStorage); } else { LOG.debug("Using OAuth {}", cachedBoxClient); // authorize App for user, and create OAuth token with refresh token final IAuthFlowUI authFlowUI = new LoginAuthFlowUI(configuration, boxClient); final CountDownLatch latch = new CountDownLatch(1); final LoginAuthFlowListener listener = new LoginAuthFlowListener(latch); boxClient.authenticate(authFlowUI, true, listener); // wait for login to finish or timeout if (!latch.await(configuration.getLoginTimeout(), TimeUnit.SECONDS)) { if (!boxClient.isAuthenticated()) { throw new RuntimeCamelException(String.format("Login timeout for %s", cachedBoxClient)); } } final Exception ex = listener.getException(); if (ex != null) { throw new RuntimeCamelException( String.format("Login error for %s: %s", cachedBoxClient, ex.getMessage()), ex); } } LOG.debug("OAuth token created for {}", cachedBoxClient); // notify the cached client listener for the first time, since BoxClient doesn't!!! cachedBoxClient.getListener().onRefresh(boxClient.getAuthData()); } }
From source file:com.twitter.distributedlog.LocalDLMEmulator.java
public static ZooKeeper connectZooKeeper(String zkHost, int zkPort, int zkTimeoutSec) throws IOException, KeeperException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final String zkHostPort = zkHost + ":" + zkPort; ZooKeeper zkc = new ZooKeeper(zkHostPort, zkTimeoutSec * 1000, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { latch.countDown();/*from ww w .ja va2s .c om*/ } } }); if (!latch.await(zkTimeoutSec, TimeUnit.SECONDS)) { throw new IOException("Zookeeper took too long to connect"); } return zkc; }
From source file:com.microsoft.office.core.EventsAsyncTestCase.java
@BeforeClass public static void retrieveCalendar() throws Exception { final ICalendars cals = Me.getCalendars(); final CountDownLatch cdl = new CountDownLatch(1); // an empty iterator will be returned for any entity set unless you call fetch() Futures.addCallback(cals.fetchAsync(), new FutureCallback<Void>() { @Override//from w ww . j a v a2 s . c om public void onFailure(Throwable t) { cdl.countDown(); } @Override public void onSuccess(Void result) { Iterator<ICalendar> iterator = cals.iterator(); if (iterator.hasNext()) { calendar = iterator.next(); } cdl.countDown(); } }); cdl.await(60000, TimeUnit.MILLISECONDS); if (calendar == null) { fail("No calendar found"); } }
From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java
/** * Runs a number of threads which generate metrics. *//* www. ja v a 2s. c om*/ public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period, final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads) throws Exception { final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads); final CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { final int id = i; final int halfPeriod = (period / 2); Runnable task = new Runnable() { private long executions = 0; final Random r = new Random(); @Override public void run() { if (executions >= metricsToGenerate) { return; } metrics.counter("foo counter thread" + id).inc(); executions++; if (executions < metricsToGenerate) { pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit); } else { latch.countDown(); } } }; pool.schedule(task, period, periodTimeUnit); } while (!latch.await(2, TimeUnit.SECONDS)) { metrics2Reporter.printQueueDebugMessage(); } pool.shutdown(); pool.awaitTermination(5000, TimeUnit.SECONDS); }
From source file:com.frostwire.android.MediaScanner.java
private static void scanFiles(final Context context, List<String> paths, int retries) { if (paths.size() == 0) { return;/* w w w . jav a 2 s . c om*/ } LOG.info("About to scan files n: " + paths.size() + ", retries: " + retries); final LinkedList<String> failedPaths = new LinkedList<>(); final CountDownLatch finishSignal = new CountDownLatch(paths.size()); MediaScannerConnection.scanFile(context, paths.toArray(new String[0]), null, (path, uri) -> { try { boolean success = true; if (uri == null) { success = false; failedPaths.add(path); } else { // verify the stored size four faulty scan long size = getSize(context, uri); if (size == 0) { LOG.warn("Scan returned an uri but stored size is 0, path: " + path + ", uri:" + uri); success = false; failedPaths.add(path); } } if (!success) { LOG.info("Scan failed for path: " + path + ", uri: " + uri); } } finally { finishSignal.countDown(); } }); try { finishSignal.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore } if (failedPaths.size() > 0 && retries > 0) { // didn't want to do this, but there is a serious timing issue with the SD // and storage in general SystemClock.sleep(2000); scanFiles(context, failedPaths, retries - 1); } }
From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java
/** * Function used to wait for a service to be available. * * @param host//from w w w .ja va 2s . c o m * @param timeout * @param serviceLinks * @throws Throwable */ public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks) throws Throwable { final CountDownLatch latch = new CountDownLatch(serviceLinks.length); final Throwable error = new Throwable("Error: registerForAvailability returned errors"); Operation.CompletionHandler handler = new Operation.CompletionHandler() { @Override public void handle(Operation operation, Throwable throwable) { if (null != throwable) { error.addSuppressed(throwable); } latch.countDown(); } }; host.registerForServiceAvailability(handler, serviceLinks); if (!latch.await(timeout, TimeUnit.MILLISECONDS)) { throw new TimeoutException( String.format("One or several of service(s) %s not available", Utils.toJson(serviceLinks))); } if (error.getSuppressed().length > 0) { throw error; } }
From source file:io.kamax.mxisd.backend.firebase.GoogleFirebaseAuthenticator.java
private void waitOnLatch(CountDownLatch l) { try {/*from w w w . j a v a2 s . com*/ l.await(30, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("Interrupted while waiting for Firebase auth check"); } }