List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:com.github.mrstampy.gameboot.otp.websocket.OtpWebSocketTest.java
private void sendMessage(AbstractGameBootMessage message, Session channel) throws Exception { if (channel == null || !channel.isOpen()) return;//ww w . j av a2 s. c o m CountDownLatch cdl = new CountDownLatch(1); endpoint.setResponseLatch(cdl); boolean b = endpoint.hasKey(); log.info("Sending {} to session {}: {}", (b ? "encrypted" : "unencrypted"), channel.getId(), converter.toJson(message)); endpoint.sendMessage(converter.toJsonArray(message), channel); cdl.await(1, TimeUnit.SECONDS); }
From source file:hudson.Proc.java
/** * Like {@link #join} but can be given a maximum time to wait. * @param timeout number of time units//from w w w. j av a 2s . co m * @param unit unit of time * @param listener place to send messages if there are problems, incl. timeout * @return exit code from the process * @throws IOException for the same reasons as {@link #join} * @throws InterruptedException for the same reasons as {@link #join} * @since 1.363 */ public final int joinWithTimeout(final long timeout, final TimeUnit unit, final TaskListener listener) throws IOException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); try { executor.submit(new Runnable() { public void run() { try { if (!latch.await(timeout, unit)) { listener.error( "Timeout after " + timeout + " " + unit.toString().toLowerCase(Locale.ENGLISH)); kill(); } } catch (InterruptedException x) { x.printStackTrace(listener.error("Failed to join a process")); } catch (IOException x) { x.printStackTrace(listener.error("Failed to join a process")); } catch (RuntimeException x) { x.printStackTrace(listener.error("Failed to join a process")); } } }); return join(); } finally { latch.countDown(); } }
From source file:org.jboss.aerogear.test.api.sender.SenderRequest.java
public SenderRequest send(UnifiedMessage message, String pushApplicationId, String masterSecret) { DefaultPushSender.Builder senderBuilder = DefaultPushSender .withRootServerURL(getSession().getBaseUrl().toExternalForm()).pushApplicationId(pushApplicationId) .masterSecret(masterSecret); if (customTrustStorePath != null) { senderBuilder.customTrustStore(customTrustStorePath, customTrustStoreType, customTrustStorePassword); }/*from w w w.jav a2 s. co m*/ PushSender senderClient = senderBuilder.build(); final CountDownLatch latch = new CountDownLatch(1); MessageResponseCallback callback = new MessageResponseCallback() { @Override public void onComplete() { latch.countDown(); } }; try { // The send is synchronous for now but I left the latch.await there in case the send becomes async again. senderClient.send(message, callback); latch.await(5000, TimeUnit.MILLISECONDS); } catch (PushSenderHttpException exception) { // In case we get the exception, we will assert it UnexpectedResponseException.verifyStatusCode(exception.getStatusCode(), HttpStatus.SC_ACCEPTED); } catch (InterruptedException e) { e.printStackTrace(); } return this; }
From source file:com.apachecon.camel.filesplit.FileSplitTest.java
@Test public void testFileSplitParallelProc() throws Exception { PropertiesComponent props = context.getRegistry().lookup("properties", PropertiesComponent.class); int count = Integer.parseInt(props.parseUri("{{demo.message.count}}")); CountDownLatch trigger = new CountDownLatch(count); SplitCounterProcessor splitCounter = context.getRegistry().lookup("splitCounter", SplitCounterProcessor.class); splitCounter.setCounter(trigger);//from w ww. j a v a2s . co m // file poller starts automatically when the route starts // since we created the 'fetch' route with autoStartup=false // polling won't start until we start the route log.info("Expecting to process {} messages", count); context.startRoute("fetch"); // set a timeout larger than the expected processing time int timeout = 10 * 1000; boolean success = trigger.await(timeout, TimeUnit.MILLISECONDS); long delta = success ? System.currentTimeMillis() - splitCounter.getTimeStarted() : timeout; String outcome = success ? "finished in" : "timed out after"; log.info("Processing {} {} millis", outcome, delta); assertTrue(success); }
From source file:com.onyxscheduler.domain.SchedulerIT.java
@Test public void shouldNotFireDeletedJobWithReachableFutureDate() throws Scheduler.DuplicateJobKeyException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); latchProvider.setLatch(latch);/* w ww . ja v a 2 s . com*/ CountDownJob job = buildJobWithFixedDateTrigger(buildReachableFutureDate()); scheduler.scheduleJob(job); scheduler.deleteJob(new JobKey(JOB_GROUP, JOB_NAME)); assertThat(latch.await(FIRE_THRESHOLD_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), is(false)); }
From source file:com.netflix.curator.framework.imps.TestFramework.java
@Test public void testBackgroundGetDataWithWatch() throws Exception { final byte[] data1 = { 1, 2, 3 }; final byte[] data2 = { 4, 5, 6, 7 }; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();//from www . j a v a 2s.c o m try { final CountDownLatch watchedLatch = new CountDownLatch(1); client.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if (event.getType() == CuratorEventType.GET_DATA) { Assert.assertEquals(event.getPath(), "/test"); Assert.assertEquals(event.getData(), data1); ((CountDownLatch) event.getContext()).countDown(); } else if (event.getType() == CuratorEventType.WATCHED) { if (event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged) { Assert.assertEquals(event.getPath(), "/test"); watchedLatch.countDown(); } } } }); client.create().forPath("/test", data1); CountDownLatch backgroundLatch = new CountDownLatch(1); client.getData().watched().inBackground(backgroundLatch).forPath("/test"); Assert.assertTrue(backgroundLatch.await(10, TimeUnit.SECONDS)); client.setData().forPath("/test", data2); Assert.assertTrue(watchedLatch.await(10, TimeUnit.SECONDS)); byte[] checkData = client.getData().forPath("/test"); Assert.assertEquals(checkData, data2); } finally { client.close(); } }
From source file:com.adaptris.core.jms.ActiveJmsConnectionErrorHandler.java
@Override public void init() throws CoreException { super.init(); try {/*from w ww . j av a 2 s. c o m*/ MyExceptionHandler handler = new MyExceptionHandler(); CountDownLatch verifierThreadGate = new CountDownLatch(1); verifier = new JmsConnectionVerifier(idForLogging, verifierThreadGate); Thread verifierThread = new ManagedThreadFactory(getClass().getSimpleName()).newThread(verifier); verifierThread.setName("JmsConnectionErrorHandler for " + idForLogging); verifierThread.setUncaughtExceptionHandler(handler); verifierThread.start(); boolean actuallyStarted = verifierThreadGate.await(DEFAULT_MAX_WAIT_FOR_START.toMilliseconds(), TimeUnit.MILLISECONDS); if (!actuallyStarted) { if (handler.hasError()) { ExceptionHelper.rethrowCoreException(handler.lastCaughtException); } else { throw new CoreException("Failed to start connection error handler"); } } if (additionalLogging()) { log.debug("ActiveJmsConnectionErrorHandler for {} started", idForLogging); } } catch (Exception e) { ExceptionHelper.rethrowCoreException(e); } }
From source file:at.salzburgresearch.kmt.zkconfig.ZookeeperConfiguration.java
private void zkInit() throws IOException { sync.raiseBarrier();//from w ww .j av a 2s. c o m final CountDownLatch connected = new CountDownLatch(1); log.debug("zkInit - connecting"); // if (zk != null) zk.close(); zk = new ZooKeeper(zkConnectionString, zkTimeout, new ZKWatcher(connected, sync)); log.info("zkInit - ensure root node exists"); try { if (connected.await(zkTimeout, TimeUnit.MILLISECONDS)) { for (int i = zkRoot.indexOf('/', 1); i > 0; i = zkRoot.indexOf('/', i + 1)) { final String path = zkRoot.substring(0, i); log.trace("zkInit - checking existence of {}", path); if (zk.exists(path, false) == null) { zk.create(path, new byte[] {}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } log.debug("zkInit - zkRoot {} exists", zkRoot); } else { throw new IOException("Timeout while establishing ZooKeeper connection"); } } catch (InterruptedException e) { throw new IOException("Could not connect", e); } catch (KeeperException e) { throw new IOException("Initial Connection failed - is zookeeper available?", e); } log.info("zkInit - connected"); sync.lowerBarrier(); }
From source file:com.yozio.android.YozioHelperTest.java
public void testInitializeExperimentsAsync() throws Throwable { JSONObject configs = null;//from w w w . j a v a2 s . co m try { configs = new JSONObject().put("key", "123"); fakeApiService.setExperimentConfigs(configs); } catch (JSONException e) { fail(); } final CountDownLatch signal = new CountDownLatch(1); runTestOnUiThread(new Runnable() { public void run() { helper.initializeExperimentsAsync(new InitializeExperimentsCallback() { public void onComplete() { assertEquals(123, helper.intForKey("key", 111)); signal.countDown(); } }); } }); signal.await(10, TimeUnit.SECONDS); }
From source file:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java
@Test public void testGetDhcpRelayProfile() throws IOException, InterruptedException { final DhcpRelayProfile mockResponse = new DhcpRelayProfile(); mockResponse.setId("id"); mockResponse.setResourceType(ServiceProfileResourceType.DHCP_RELAY_PROFILE); setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK); DhcpServiceApi client = new DhcpServiceApi(restClient); final CountDownLatch latch = new CountDownLatch(1); client.getDhcpRelayProfile("id", new com.google.common.util.concurrent.FutureCallback<DhcpRelayProfile>() { @Override/*w w w . ja va 2s. c o m*/ public void onSuccess(DhcpRelayProfile result) { assertEquals(result, mockResponse); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }