List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.couchbase.client.TestingClient.java
public HttpFuture<String> asyncHttpDelete(String uri) throws UnsupportedEncodingException { final CountDownLatch couchLatch = new CountDownLatch(1); final HttpFuture<String> crv = new HttpFuture<String>(couchLatch, operationTimeout); HttpRequest request = new BasicHttpRequest("DELETE", uri, HttpVersion.HTTP_1_1); HttpOperationImpl op = new TestOperationImpl(request, new TestCallback() { private String json; @Override//from ww w.ja va 2s . c om public void receivedStatus(OperationStatus status) { crv.set(json, status); } @Override public void complete() { couchLatch.countDown(); } @Override public void getData(String response) { json = response; } }); crv.setOperation(op); addOp(op); return crv; }
From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java
@Test public void testGetTransportNodeState() throws IOException, InterruptedException { final TransportNodeState mockResponse = new TransportNodeState(); mockResponse.setState(com.vmware.photon.controller.nsxclient.datatypes.TransportNodeState.SUCCESS); setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK); FabricApi client = new FabricApi(restClient); final CountDownLatch latch = new CountDownLatch(1); client.getTransportNodeState("id", new com.google.common.util.concurrent.FutureCallback<TransportNodeState>() { @Override//from w w w .j av a 2 s .com public void onSuccess(TransportNodeState 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)); }
From source file:interactivespaces.activity.component.ActivityComponentContextTest.java
/** * Test that there is a processing handler that never exits and the wait has * to exit./* w w w . ja va2s.c o m*/ */ @Test public void testWaitMultithreadedProcessingHandlers() throws Exception { final CountDownLatch latch = new CountDownLatch(2); Runnable runnable = new Runnable() { @Override public void run() { context.enterHandler(); latch.countDown(); InteractiveSpacesUtilities.delay(1000); context.exitHandler(); } }; executor.execute(runnable); executor.execute(runnable); // Make sure they have both entered before starting the wait. Assert.assertTrue(latch.await(500, TimeUnit.MILLISECONDS)); Assert.assertTrue(context.waitOnNoProcessingHandlings(500, 4000)); }
From source file:com.couchbase.lite.syncgateway.GzippedAttachmentTest.java
public void testImageAttachmentReplication() throws Exception { if (!syncgatewayTestsEnabled()) { return;/*w w w . j ava2 s . c o m*/ } URL remote = getReplicationURL(); Database pushDB = getDatabase("pushdb"); pushDB.delete(); pushDB = getDatabase("pushdb"); Database pullDB = getDatabase("pulldb"); pullDB.delete(); pullDB = getDatabase("pulldb"); // Create a document with an image attached: Map<String, Object> props = new HashMap<String, Object>(); props.put("foo", "bar"); Document doc = pushDB.createDocument(); doc.putProperties(props); UnsavedRevision newRev = doc.createRevision(); newRev.setAttachment("attachment", "image/png", getAsset("attachment.png")); newRev.save(); String docId = doc.getId(); // Push: final CountDownLatch latch1 = new CountDownLatch(1); Replication pusher = pushDB.createPushReplication(remote); pusher.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { Log.e(TAG, "push 1:" + event.toString()); if (event.getCompletedChangeCount() > 0) { latch1.countDown(); } } }); runReplication(pusher); assertTrue(latch1.await(5, TimeUnit.SECONDS)); // Pull: Replication puller = pullDB.createPullReplication(remote); final CountDownLatch latch2 = new CountDownLatch(1); puller.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { Log.e(TAG, "pull 1:" + event.toString()); if (event.getCompletedChangeCount() > 0) { latch2.countDown(); } } }); runReplication(puller); assertTrue(latch2.await(5, TimeUnit.SECONDS)); // Check document: Document pullDoc = pullDB.getDocument(docId); assertNotNull(pullDoc); assertTrue(pullDoc.getCurrentRevisionId().startsWith("2-")); // Check attachment: Attachment attachment = pullDoc.getCurrentRevision().getAttachment("attachment"); byte[] originalBytes = getBytesFromInputStream(getAsset("attachment.png")); assertEquals(originalBytes.length, attachment.getLength()); assertEquals("image/png", attachment.getContentType()); assertTrue(Arrays.equals(originalBytes, getBytesFromInputStream(attachment.getContent()))); pushDB.close(); pullDB.close(); pushDB.delete(); pullDB.delete(); }
From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java
@Test public void testRegisterFabricNode() throws IOException, InterruptedException { final FabricNode mockResponse = new FabricNode(); mockResponse.setId("id"); mockResponse.setExternalId("externalId"); setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED); FabricApi client = new FabricApi(restClient); final CountDownLatch latch = new CountDownLatch(1); client.registerFabricNode(new FabricNodeCreateSpec(), new com.google.common.util.concurrent.FutureCallback<FabricNode>() { @Override/* w w w . j a v a2s . c o m*/ public void onSuccess(FabricNode 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)); }
From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java
@Test public void subscribeConcurrentlyToTransformedPipelineOutputs() throws InterruptedException { // this test verifies that pipelines actions are only executed once, even if there are multiple concurrent subscribers firstStep = newPipelineWithResponseBody("{id:123}"); secondStep = firstStep.applyAction(action); when(action.execute(any(), any())).thenReturn(firstStep.getOutput()); // 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 CountDownLatch countDown = new CountDownLatch(100); ExecutorService executorService = Executors.newCachedThreadPool(); while (countDown.getCount() > 0) { executorService.submit(() -> { countDown.await();//from w w w. j av a 2s.c o m secondStep.getOutput().subscribe(Subscribers.empty()); 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); verify(action, times(1)).execute(any(), any()); }
From source file:com.vmware.photon.controller.nsxclient.apis.FabricApiTest.java
@Test public void testGetTransportZoneSummary() throws IOException, InterruptedException { final TransportZoneSummary mockResponse = new TransportZoneSummary(); mockResponse.setNumTransportNodes(5); setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_OK); FabricApi client = new FabricApi(restClient); final CountDownLatch latch = new CountDownLatch(1); client.getTransportZoneSummary("id", new com.google.common.util.concurrent.FutureCallback<TransportZoneSummary>() { @Override// ww w . j a v a 2s .com public void onSuccess(TransportZoneSummary 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)); }
From source file:com.vmware.photon.controller.deployer.xenon.DeployerServiceGroupTest.java
private void waitForServicesStartup(PhotonControllerXenonHost host) throws TimeoutException, InterruptedException, NoSuchFieldException, IllegalAccessException { serviceSelfLinks = ServiceHostUtils.getServiceSelfLinks( DeployerServiceGroup.FACTORY_SERVICE_FIELD_NAME_SELF_LINK, DeployerServiceGroup.FACTORY_SERVICES); serviceSelfLinks.add(DeployerServiceGroup.UPLOAD_VIB_WORK_QUEUE_SELF_LINK); final CountDownLatch latch = new CountDownLatch(serviceSelfLinks.size()); Operation.CompletionHandler handler = new Operation.CompletionHandler() { @Override// w w w.j a v a 2 s .c o m public void handle(Operation completedOp, Throwable failure) { latch.countDown(); } }; String[] links = new String[serviceSelfLinks.size()]; host.registerForServiceAvailability(handler, serviceSelfLinks.toArray(links)); if (!latch.await(10, TimeUnit.SECONDS)) { throw new TimeoutException(); } }
From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCacheInCluster.java
@Test public void testServerLoss() throws Exception { Timing timing = new Timing(); CuratorFramework client = null;//from www .j av a 2s . com PathChildrenCache cache = null; TestingCluster cluster = new TestingCluster(3); try { cluster.start(); client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test"); cache = new PathChildrenCache(client, "/test", false); cache.start(); final CountDownLatch resetLatch = new CountDownLatch(1); final CountDownLatch reconnectLatch = new CountDownLatch(1); final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>( new CountDownLatch(3)); cache.getListenable().addListener(new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) { resetLatch.countDown(); } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) { reconnectLatch.countDown(); } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { latch.get().countDown(); } } }); client.create().forPath("/test/one"); client.create().forPath("/test/two"); client.create().forPath("/test/three"); Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS)); InstanceSpec connectionInstance = cluster .findConnectionInstance(client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); Assert.assertTrue(timing.awaitLatch(reconnectLatch)); Assert.assertEquals(cache.getCurrentData().size(), 3); } finally { IOUtils.closeQuietly(cache); IOUtils.closeQuietly(client); IOUtils.closeQuietly(cluster); } }
From source file:org.kurento.repository.OneRecordingServer.java
private void prepareToDownloadVideo(RepositoryItem repositoryItem) throws InterruptedException { RepositoryHttpPlayer player = repositoryItem.createRepositoryHttpPlayer("video-download"); log.info("The video can be downloaded with GET from the URL: " + player.getURL()); player.setAutoTerminationTimeout(30 * 60 * 1000); log.info("The player will be auto-terminated 30 min after the last downloading of content (http GET)"); final CountDownLatch terminatedLatch = new CountDownLatch(1); player.addSessionStartedListener(new RepositoryHttpEventListener<HttpSessionStartedEvent>() { @Override//from w ww . j a v a2 s. c o m public void onEvent(HttpSessionStartedEvent event) { log.info("Downloading started"); } }); player.addSessionTerminatedListener(new RepositoryHttpEventListener<HttpSessionTerminatedEvent>() { @Override public void onEvent(HttpSessionTerminatedEvent event) { log.info("Downloading terminated"); terminatedLatch.countDown(); } }); try { terminatedLatch.await(); } catch (InterruptedException e) { } }