List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.rabbitmq.client3.test.performance.ScalabilityTest.java
private float timeRouting(Channel channel, String[] routingKeys) throws IOException, InterruptedException { boolean mandatory = true; boolean immdediate = true; final CountDownLatch latch = new CountDownLatch(params.messageCount); channel.addReturnListener(new ReturnListener() { public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException { latch.countDown(); }//w w w .ja v a 2 s. c o m }); final long start = System.nanoTime(); // route some messages Random r = new Random(); int size = routingKeys.length; for (int n = 0; n < params.messageCount; n++) { String key = routingKeys[r.nextInt(size)]; channel.basicPublish("amq.direct", key, mandatory, immdediate, MessageProperties.MINIMAL_BASIC, null); } // wait for the returns to come back latch.await(); // Compute the roundtrip time final long finish = System.nanoTime(); final long wallclock = finish - start; return (params.messageCount == 0) ? (float) 0.0 : wallclock / (float) params.messageCount / 1000; }
From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java
@Test public void subscribeConcurrentlyToPlainPipelineOutputs() throws InterruptedException, JSONException { firstStep = newPipelineWithResponseBody("{id:123}"); // use a synchronized set to collect the pipeline output from multiple threads Set<JsonPipelineOutput> distinctOutputs = Collections.synchronizedSet(new HashSet<JsonPipelineOutput>()); // create multiple simultaneous threads that subscribe to the same pipeline output // and use a CountDownLatch to delay the subscription until all threads have been started ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch countDown = new CountDownLatch(100); while (countDown.getCount() > 0) { executorService.submit(() -> { countDown.await();/*from ww w .ja v a 2s . c om*/ distinctOutputs.add(firstStep.getOutput().toBlocking().single()); return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions }); countDown.countDown(); } executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); // ensure all threads received the same JsonPipelineOutput instance with the expected JSON output assertEquals(1, distinctOutputs.size()); JSONAssert.assertEquals("{id: 123}", firstStep.getStringOutput().toBlocking().first(), JSONCompareMode.STRICT); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentApiTest.java
@Test public void testPauseSystemAsync() throws IOException, InterruptedException { final Task responseTask = getExpectedTaskResponse(); DeploymentApi deploymentApi = new DeploymentApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.pauseSystemAsync("deploymentId1", new FutureCallback<Task>() { @Override//w w w . ja v a 2 s. co m public void onSuccess(Task result) { assertEquals(result, responseTask); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java
@Test public void testPauseSystemAsync() throws IOException, InterruptedException { final Task responseTask = getExpectedTaskResponse(); DeploymentApi deploymentApi = new DeploymentRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.pauseSystemAsync("deploymentId1", new FutureCallback<Task>() { @Override//from ww w . j av a 2s.c o m public void onSuccess(Task result) { assertEquals(result, responseTask); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentApiTest.java
@Test public void testResumeSystemAsync() throws Exception { Task responseTask = getExpectedTaskResponse(); DeploymentApi deploymentApi = new DeploymentApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.resumeSystemAsync("deploymentId1", new FutureCallback<Task>() { @Override/*from w ww .ja v a 2s.c om*/ public void onSuccess(Task result) { assertEquals(result, responseTask); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:com.vmware.photon.controller.api.client.resource.DeploymentRestApiTest.java
@Test public void testResumeSystemAsync() throws Exception { Task responseTask = getExpectedTaskResponse(); DeploymentApi deploymentApi = new DeploymentRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); deploymentApi.resumeSystemAsync("deploymentId1", new FutureCallback<Task>() { @Override/* ww w . java2 s. c o m*/ public void onSuccess(Task result) { assertEquals(result, responseTask); latch.countDown(); } @Override public void onFailure(Throwable t) { fail(t.toString()); latch.countDown(); } }); assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true)); }
From source file:info.archinnov.achilles.test.integration.tests.AsyncEventInterceptorIT.java
@Test public void should_apply_persist_interceptors() throws Exception { CompleteBean entity = builder().randomId().name("DuyHai").label("label").version(incr(2L)).buid(); final CountDownLatch latch = new CountDownLatch(1); asyncManager.insert(entity, withAsyncListeners(new FutureCallback<Object>() { @Override//ww w. j a v a2s . c o m public void onSuccess(Object result) { latch.countDown(); } @Override public void onFailure(Throwable t) { } })); latch.await(); assertThat(entity.getName()).isEqualTo("prePersist"); assertThat(entity.getLabel()).isEqualTo("postPersist : label"); Row row = session.execute("select name,label from CompleteBean where id = " + entity.getId()).one(); assertThat(row.getString("name")).isEqualTo("prePersist"); assertThat(row.getString("label")).isEqualTo("label"); }
From source file:com.kurento.kmf.jsonrpcconnector.client.JsonRpcClientWebSocket.java
private synchronized void connectIfNecessary() throws IOException { if (wsSession == null) { final CountDownLatch latch = new CountDownLatch(1); TextWebSocketHandler webSocketHandler = new TextWebSocketHandler() { @Override//from w w w .jav a 2 s .c o m public void afterConnectionEstablished(WebSocketSession wsSession2) throws Exception { wsSession = wsSession2; rs = new WebSocketResponseSender(wsSession); latch.countDown(); } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { handleWebSocketTextMessage(message); } @Override public void afterConnectionClosed(WebSocketSession s, CloseStatus status) throws Exception { // TODO Call this when you can't reconnect or close is // issued by client. handlerManager.afterConnectionClosed(session, status.getReason()); log.debug("WebSocket closed due to: {}", status); wsSession = null; // TODO Start a timer to force reconnect in x millis // For the moment we are going to force it sending another // message. } }; WebSocketConnectionManager connectionManager = new WebSocketConnectionManager( new StandardWebSocketClient(), webSocketHandler, url); connectionManager.setHeaders(headers); connectionManager.start(); try { latch.await(); if (session == null) { session = new ClientSession(null, null, JsonRpcClientWebSocket.this); handlerManager.afterConnectionEstablished(session); } else { String result = rsHelper.sendRequest(JsonRpcConstants.METHOD_RECONNECT, String.class); log.info("Reconnection result: {}", result); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderLatch.java
@Test public void testLostConnection() throws Exception { final int PARTICIPANT_QTY = 10; List<LeaderLatch> latches = Lists.newArrayList(); final Timing timing = new Timing(); final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {/*from w w w .j av a2s .c om*/ client.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { countDownLatch.countDown(); } } }); for (int i = 0; i < PARTICIPANT_QTY; ++i) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.start(); latches.add(latch); } waitForALeader(latches, timing); server.stop(); Assert.assertTrue(timing.awaitLatch(countDownLatch)); timing.forWaiting().sleepABit(); Assert.assertEquals(getLeaders(latches).size(), 0); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertEquals(waitForALeader(latches, timing).size(), 1); // should reconnect } finally { for (LeaderLatch latch : latches) { IOUtils.closeQuietly(latch); } IOUtils.closeQuietly(client); } }
From source file:io.undertow.server.handlers.GracefulShutdownTestCase.java
@Test public void gracefulShutdownListenerTestCase() throws IOException, InterruptedException { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path"); TestHttpClient client = new TestHttpClient(); try {/*from ww w . java 2 s . c om*/ HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); shutdown.shutdown(); result = client.execute(get); Assert.assertEquals(StatusCodes.SERVICE_UNAVAILABLE, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); shutdown.start(); result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); CountDownLatch latch = new CountDownLatch(1); latch2.set(latch); latch1.set(new CountDownLatch(1)); Thread t = new Thread(new RequestTask()); t.start(); latch1.get().await(); ShutdownListener listener = new ShutdownListener(); shutdown.shutdown(); shutdown.addShutdownListener(listener); Assert.assertFalse(listener.invoked); latch.countDown(); long end = System.currentTimeMillis() + 5000; while (!listener.invoked && System.currentTimeMillis() < end) { Thread.sleep(10); } Assert.assertTrue(listener.invoked); } finally { client.getConnectionManager().shutdown(); } }