List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:dstrelec.nats.listener.DefaultNatsListenerContainer.java
@Override public final void stop() { final CountDownLatch latch = new CountDownLatch(1); stop(new Runnable() { @Override/* ww w . j a v a 2 s.c o m*/ public void run() { latch.countDown(); } }); try { latch.await(this.containerProperties.getShutdownTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // } }
From source file:net.javacrumbs.futureconverter.common.test.spring.SpringConvertedFutureTestHelper.java
@Override public void waitForCalculationToFinish(ListenableFuture<String> convertedFuture) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); convertedFuture.addCallback(new ListenableFutureCallback<String>() { @Override/*from ww w .ja va2 s . c o m*/ public void onSuccess(String result) { latch.countDown(); } @Override public void onFailure(Throwable t) { latch.countDown(); } }); latch.await(1, TimeUnit.SECONDS); }
From source file:io.fabric8.msg.jnatsd.TestNullPayload.java
@Test public void testNullPayload() throws Exception { Connection connection = connectionFactory.createConnection(); final int count = 100; CountDownLatch countDownLatch = new CountDownLatch(count); Subscription subscription = connection.subscribe("foo", new MessageHandler() { @Override//from ww w . ja v a 2 s. c o m public void onMessage(Message message) { countDownLatch.countDown(); } }); for (int i = 0; i < count; i++) { connection.publish("foo", null); } countDownLatch.await(10, TimeUnit.SECONDS); Assert.assertEquals(0, countDownLatch.getCount()); connection.close(); }
From source file:kidozen.client.crash.HttpSender.java
@Override public void send(CrashReportData report) throws ReportSenderException { try {/*from w ww . ja v a 2 s .co m*/ final CountDownLatch cdl = new CountDownLatch(1); IdentityManager.getInstance().GetRawToken(mApplicationKey, new ServiceEventListener() { @Override public void onFinish(ServiceEvent e) { mEvent = e; cdl.countDown(); } }); cdl.await(DEFAULT_TIMEOUT, TimeUnit.MINUTES); if (mEvent.Exception != null || mEvent.StatusCode >= HttpStatus.SC_BAD_REQUEST) throw new ReportSenderException(mEvent.Body); mToken = ((KidoZenUser) mEvent.Response).Token; String authHeaderValue = String.format("WRAP access_token=\"%s\"", mToken); Log.d(LOG_TAG, String.format("About to send log to Log V3 service: %s ", mCrashEndpoint)); JSONObject reportAsJson = report.toJSON(); String bc = new JSONArray(mBreadCrumbs).toString(); reportAsJson.put(APPLICATION_BREADCRUMB, bc); Hashtable<String, String> headers = new Hashtable<String, String>(); headers.put(Constants.AUTHORIZATION_HEADER, authHeaderValue); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON); mSniManager = new SNIConnectionManager(mCrashEndpoint, reportAsJson.toString(), headers, null, true); Hashtable<String, String> response = mSniManager.ExecuteHttp(KZHttpMethod.POST); String body = response.get("responseBody"); Integer statusCode = Integer.parseInt(response.get("statusCode")); if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) { String exceptionMessage = (body != null ? body : "Unexpected HTTP Status Code: " + statusCode); throw new Exception(exceptionMessage); } } catch (InterruptedException e) { throw new ReportSenderException("Timeout trying to send report to KidoZen services.", e); } catch (ReportSenderException e) { throw e; } catch (Exception e) { throw new ReportSenderException("Error while sending report to KidoZen services.", e); } }
From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java
@Test public void testNestedCalls() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();/* www .j av a 2s . com*/ try { client.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.EXISTS) { Stat stat = client.checkExists().forPath("/yo/yo/yo"); Assert.assertNull(stat); client.create().inBackground(event.getContext()).forPath("/what"); } else if (event.getType() == CuratorEventType.CREATE) { ((CountDownLatch) event.getContext()).countDown(); } } }); CountDownLatch latch = new CountDownLatch(1); client.checkExists().inBackground(latch).forPath("/hey"); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); } finally { IOUtils.closeQuietly(client); } }
From source file:edu.stanford.junction.provider.xmpp.JunctionProvider.java
private synchronized XMPPConnection getXMPPConnection(XMPPSwitchboardConfig config, String roomid) throws JunctionException { final CountDownLatch waitForConnect = new CountDownLatch(1); ConnectionThread t = new ConnectionThread(config, waitForConnect); t.start();// ww w . ja v a 2 s . c om boolean timedOut = false; try { timedOut = !(waitForConnect.await(config.connectionTimeout, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new JunctionException("Interrupted while waiting for connection."); } if (timedOut) { System.out.println("Connection timed out after " + config.connectionTimeout + " milliseconds."); t.interrupt(); // Thread may still be looping... String msg = "Connection attempt failed to complete within provided timeout of " + config.connectionTimeout + " milliseconds."; throw new JunctionException(msg, new ConnectionTimeoutException(msg)); } if (t.success) { if (DBG) System.out.println("Connection succeeded."); sConnections.add(t.connection); HashSet<String> set = new HashSet<String>(); set.add(roomid); sConnectionSessions.add(set); return t.connection; } else { if (t.failureReason != null) { throw new JunctionException("Connection attempt failed.", t.failureReason); } else { throw new JunctionException("Connection attempt failed for unknown reason.", t.failureReason); } } }
From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java
@Test public void collect_logs_when_one_container_is_running_and_does_not_terminate() throws IOException, InterruptedException { when(compose.ps()).thenReturn(TestContainerNames.of("db")); CountDownLatch latch = new CountDownLatch(1); when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> { OutputStream outputStream = (OutputStream) args.getArguments()[1]; IOUtils.write("log", outputStream); try {/* www .java 2 s . c o m*/ latch.await(1, TimeUnit.SECONDS); fail("Latch was not triggered"); } catch (InterruptedException e) { // Success return true; } fail("Latch was not triggered"); return false; }); logCollector.startCollecting(compose); logCollector.stopCollecting(); assertThat(logDirectory.listFiles(), arrayContaining(fileWithName("db.log"))); assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log"))); latch.countDown(); }
From source file:com.heliosapm.streams.collector.ds.JDBCDataSourceManager.java
/** * Awaits deployment of the datasource defined by the passed file * @param dsDef The datasource (or objectpool) definition file * @param timeout The await timeout// w w w. java 2 s . c o m * @param unit The await timeout unit * @return true if datasource was deployed, false otherwise */ public boolean awaitDeployment(final File dsDef, final long timeout, final TimeUnit unit) { if (dsDef == null) throw new IllegalArgumentException("The passed file was null"); final CountDownLatch latch = placeLatch(dsDef); try { final boolean complete = latch.await(timeout, unit); if (complete) { deploymentLatches.remove(dsDef, latch); } return complete; } catch (InterruptedException iex) { throw new RuntimeException("Thread interrupted while waiting for deployment of [" + dsDef + "]", iex); } }
From source file:ninja.eivind.hotsreplayuploader.ClientTest.java
@Test public void testJavaFXIsAvailable() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); Task<Void> javaFxTask = new Task<Void>() { @Override/*w ww . j av a 2 s . c om*/ protected Void call() throws Exception { latch.countDown(); return null; } }; javaFxTask.setOnSucceeded((result) -> latch.countDown()); new Thread(javaFxTask).run(); if (!latch.await(1, TimeUnit.SECONDS)) { fail("JavaFX is not available."); } }
From source file:org.onosproject.rest.resources.IntentsWebResource.java
/** * Withdraw intent./*w ww . j a v a2s. c o m*/ * Withdraws the specified intent from the system. * * @param appId application identifier * @param key intent key */ @DELETE @Path("{appId}/{key}") public void deleteIntentById(@PathParam("appId") String appId, @PathParam("key") String key) { final ApplicationId app = get(CoreService.class).getAppId(appId); Intent intent = get(IntentService.class).getIntent(Key.of(key, app)); IntentService service = get(IntentService.class); if (intent == null) { intent = service.getIntent(Key.of(Long.decode(key), app)); } if (intent == null) { // No such intent. REST standards recommend a positive status code // in this case. return; } Key k = intent.key(); // set up latch and listener to track uninstall progress CountDownLatch latch = new CountDownLatch(1); IntentListener listener = new DeleteListener(k, latch); service.addListener(listener); try { // request the withdraw service.withdraw(intent); try { latch.await(WITHDRAW_EVENT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException e) { log.info("REST Delete operation timed out waiting for intent {}", k); } // double check the state IntentState state = service.getIntentState(k); if (state == WITHDRAWN || state == FAILED) { service.purge(intent); } } finally { // clean up the listener service.removeListener(listener); } }