List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.twitter.hbc.httpclient.BasicClientTest.java
@Test public void testConnectionRetries() throws Exception { HttpHosts mockHttpHosts = mock(HttpHosts.class); ClientBase clientBase = new ClientBase("name", mockClient, mockHttpHosts, new RawEndpoint("/endpoint", HttpConstants.HTTP_GET), mockAuth, mockProcessor, mockReconnectionManager, mockRateTracker); BasicClient client = new BasicClient(clientBase, executorService); final CountDownLatch latch = new CountDownLatch(1); when(mockHttpHosts.nextHost()).thenReturn("http://somehost.com"); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse).thenReturn(mockResponse) .thenThrow(new IOException()).thenReturn(mockResponse); when(mockStatusLine.getStatusCode()).thenReturn(HttpConstants.Codes.UNAUTHORIZED) .thenReturn(HttpConstants.Codes.SERVICE_UNAVAILABLE).thenReturn(HttpConstants.Codes.SUCCESS); // turn off the client when we start processing doAnswer(new Answer() { @Override/*ww w. j a va 2 s. c om*/ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { latch.countDown(); return null; } }).when(mockProcessor).process(); // for 401 Unauthorized when(mockReconnectionManager.shouldReconnectOn400s()).thenReturn(true); /** for shutdown **/ when(mockClient.getConnectionManager()).thenReturn(mockConnectionManager); assertFalse(clientBase.isDone()); client.connect(); latch.await(); client.stop(); assertTrue(client.isDone()); // exponential backoff twice: once for 401 once for 503 verify(mockReconnectionManager, times(2)).handleExponentialBackoff(); // for thrown IOException verify(mockReconnectionManager).handleLinearBackoff(); // for successful connection verify(mockReconnectionManager).resetCounts(); // finally start setting up processor/processing for the last attempt that goes through verify(mockProcessor, atLeastOnce()).setup(any(InputStream.class)); verify(mockProcessor, atLeastOnce()).process(); assertEquals(EventType.STOPPED_BY_USER, clientBase.getExitEvent().getEventType()); verify(mockConnectionManager, atLeastOnce()).shutdown(); }
From source file:io.fabric8.maven.core.service.openshift.OpenshiftBuildService.java
/** * A Simple utility function to watch over pod until it gets ready * * @param podName Name of the pod/*w w w . j av a 2s . c om*/ * @param nAwaitTimeout Time in seconds upto which pod must be watched * @param log Logger object * @throws InterruptedException */ private void waitUntilPodIsReady(String podName, int nAwaitTimeout, final Logger log) throws InterruptedException { final CountDownLatch readyLatch = new CountDownLatch(1); try (Watch watch = client.pods().withName(podName).watch(new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod aPod) { if (KubernetesHelper.isPodReady(aPod)) { readyLatch.countDown(); } } @Override public void onClose(KubernetesClientException e) { // Ignore } })) { readyLatch.await(nAwaitTimeout, TimeUnit.SECONDS); } catch (KubernetesClientException | InterruptedException e) { log.error("Could not watch pod", e); } }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedLockTest.java
@Test protected void test_lock() { ExecutorService exeucotr = Executors.newCachedThreadPool(); final int count = 50; final CountDownLatch latch = new CountDownLatch(count); final DistributedLock[] nodes = new DistributedLock[count]; for (int i = 0; i < count; i++) { final DistributedLock node = new DistributedLock(dir); nodes[i] = node;/* ww w. java 2s. com*/ exeucotr.submit(new Runnable() { public void run() { try { node.lock(); Thread.sleep(100 + RandomUtils.nextInt(100)); System.out.println("id: " + node.getId() + " is leader: " + node.isOwner()); } catch (InterruptedException e) { want.fail(); } catch (KeeperException e) { want.fail(); } finally { latch.countDown(); try { node.unlock(); } catch (KeeperException e) { want.fail(); } } } }); } try { latch.await(); } catch (InterruptedException e) { want.fail(); } exeucotr.shutdown(); }
From source file:io.druid.server.initialization.JettyTest.java
@Test public void testThreadNotStuckOnException() throws Exception { final CountDownLatch latch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override/* ww w .jav a 2s . c o m*/ public void run() { try { ListenableFuture<InputStream> go = client.go( new Request(HttpMethod.GET, new URL("http://localhost:" + port + "/exception/exception")), new InputStreamResponseHandler()); StringWriter writer = new StringWriter(); IOUtils.copy(go.get(), writer, "utf-8"); } catch (IOException e) { // Expected. } catch (Throwable t) { Throwables.propagate(t); } latch.countDown(); } }); latch.await(5, TimeUnit.SECONDS); }
From source file:gobblin.tunnel.TunnelTest.java
@Test public void mustHandleMultipleConnections() throws Exception { mockExample();/* www.j a va 2 s .c om*/ Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT); int clients = 5; final CountDownLatch startSignal = new CountDownLatch(1); final CountDownLatch doneSignal = new CountDownLatch(clients); ExecutorService executor = Executors.newFixedThreadPool(clients); try { final int tunnelPort = tunnel.getPort(); List<Future<String>> results = new ArrayList<Future<String>>(); for (int i = 0; i < clients; i++) { Future<String> result = executor.submit(new Callable<String>() { @Override public String call() throws Exception { startSignal.await(); try { return fetchContent(tunnelPort); } finally { doneSignal.countDown(); } } }); results.add(result); } startSignal.countDown(); doneSignal.await(); for (Future<String> result : results) { assertNotNull(result.get()); } } finally { tunnel.close(); } }
From source file:com.vmware.photon.controller.api.client.resource.TenantsApiTest.java
@Test public void testDeleteAsync() throws IOException, InterruptedException { final Task responseTask = new Task(); responseTask.setId("12345"); responseTask.setState("QUEUED"); responseTask.setQueuedTime(Date.from(Instant.now())); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(responseTask); setupMocks(serializedTask, HttpStatus.SC_CREATED); TenantsApi tenantsApi = new TenantsApi(restClient); final CountDownLatch latch = new CountDownLatch(1); tenantsApi.deleteAsync("foo", new FutureCallback<Task>() { @Override/*from w w w . j a va 2 s . c om*/ public void onSuccess(@Nullable 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.TenantsRestApiTest.java
@Test public void testDeleteAsync() throws IOException, InterruptedException { final Task responseTask = new Task(); responseTask.setId("12345"); responseTask.setState("QUEUED"); responseTask.setQueuedTime(Date.from(Instant.now())); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(responseTask); setupMocks(serializedTask, HttpStatus.SC_CREATED); TenantsApi tenantsApi = new TenantsRestApi(restClient); final CountDownLatch latch = new CountDownLatch(1); tenantsApi.deleteAsync("foo", new FutureCallback<Task>() { @Override/*from w w w . java 2 s .c o m*/ public void onSuccess(@Nullable 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:org.kitodo.data.index.elasticsearch.RestClientImplementation.java
/** * Add list of documents to the index. This method will be used for add whole table to the index. * It performs asynchronous request.//from w ww . j ava 2 s . co m * * @param documentsToIndex list of json documents to the index */ public String addType(HashMap<Integer, HttpEntity> documentsToIndex) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(documentsToIndex.size()); final StringBuilder output = new StringBuilder(); for (HashMap.Entry<Integer, HttpEntity> entry : documentsToIndex.entrySet()) { restClient.performRequestAsync("PUT", "/" + this.getIndex() + "/" + this.getType() + "/" + entry.getKey(), Collections.<String, String>emptyMap(), entry.getValue(), new ResponseListener() { @Override //problem with return type - it should be String //dirty hack private variable ArrayResult public void onSuccess(Response response) { output.append(response.toString()); latch.countDown(); } @Override public void onFailure(Exception exception) { latch.countDown(); } }); } latch.await(); return output.toString(); }
From source file:com.example.android.vault.EncryptedDocumentTest.java
private void testMetadataAndContents(byte[] content) throws Exception { final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey); final byte[] beforeContent = content; final ParcelFileDescriptor[] beforePipe = ParcelFileDescriptor.createReliablePipe(); new Thread() { @Override//from ww w .j a v a 2 s . c om public void run() { final FileOutputStream os = new FileOutputStream(beforePipe[1].getFileDescriptor()); try { os.write(beforeContent); beforePipe[1].close(); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); // fully write metadata and content final JSONObject before = new JSONObject(); before.put("meow", "cake"); doc.writeMetadataAndContent(before, beforePipe[0]); // now go back and verify we can read final JSONObject after = doc.readMetadata(); assertEquals("cake", after.getString("meow")); final CountDownLatch latch = new CountDownLatch(1); final ParcelFileDescriptor[] afterPipe = ParcelFileDescriptor.createReliablePipe(); final byte[] afterContent = new byte[beforeContent.length]; new Thread() { @Override public void run() { final FileInputStream is = new FileInputStream(afterPipe[0].getFileDescriptor()); try { int i = 0; while (i < afterContent.length) { int n = is.read(afterContent, i, afterContent.length - i); i += n; } afterPipe[0].close(); latch.countDown(); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); doc.readContent(afterPipe[1]); latch.await(5, TimeUnit.SECONDS); MoreAsserts.assertEquals(beforeContent, afterContent); }