List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:ninja.eivind.hotsreplayuploader.files.tempwatcher.RecursiveTempWatcherTest.java
@After public void tearDown() throws Exception { CountDownLatch latch = new CountDownLatch(1); Platform.runLater(() -> {/*from w w w . j a v a 2s . c o m*/ if (tempWatcher.cancel()) { latch.countDown(); } }); if (!latch.await(1, TimeUnit.SECONDS)) { fail("Service failed to stop"); } // give watchers some time to wind down recursively Thread.sleep(1000L); cleanupRecursive(directories.getRoot()); }
From source file:com.linkedin.helix.TestHelper.java
public static <T> Map<String, T> startThreadsConcurrently(final int nrThreads, final Callable<T> method, final long timeout) { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch finishCounter = new CountDownLatch(nrThreads); final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>(); final List<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < nrThreads; i++) { Thread thread = new Thread() { @Override/*from ww w .j ava 2s . com*/ public void run() { try { boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS); if (isTimeout) { LOG.error("Timeout while waiting for start latch"); } } catch (InterruptedException ex) { LOG.error("Interrupted while waiting for start latch"); } try { T result = method.call(); if (result != null) { resultsMap.put("thread_" + this.getId(), result); } LOG.debug("result=" + result); } catch (Exception e) { LOG.error("Exeption in executing " + method.getClass().getName(), e); } finishCounter.countDown(); } }; threadList.add(thread); thread.start(); } startLatch.countDown(); // wait for all thread to complete try { boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS); if (isTimeout) { LOG.error("Timeout while waiting for finish latch. Interrupt all threads"); for (Thread thread : threadList) { thread.interrupt(); } } } catch (InterruptedException e) { LOG.error("Interrupted while waiting for finish latch", e); } return resultsMap; }
From source file:org.mule.module.http.functional.listener.HttpListenerNotificationsTestCase.java
@Test public void receiveNotification() throws Exception { String listenerUrl = String.format("http://localhost:%s/%s", listenPort.getNumber(), path.getValue()); CountDownLatch latch = new CountDownLatch(2); TestConnectorMessageNotificationListener listener = new TestConnectorMessageNotificationListener(latch, listenerUrl);// www .j av a 2 s . com muleContext.getNotificationManager().addListener(listener); Request.Post(listenerUrl).execute(); latch.await(1000, TimeUnit.MILLISECONDS); assertThat(listener.getNotificationActionNames(), contains(getActionName(MESSAGE_RECEIVED), getActionName(MESSAGE_RESPONSE))); }
From source file:ch.cyberduck.core.io.ThreadedStreamCloser.java
@Override public void close(final InputStream in) throws ConnectionTimeoutException { final CountDownLatch signal = new CountDownLatch(1); threadFactory.newThread(new Runnable() { @Override/*from ww w . j av a 2 s . c o m*/ public void run() { IOUtils.closeQuietly(in); signal.countDown(); } }).start(); try { if (!signal.await(preferences.getInteger("connection.timeout.seconds"), TimeUnit.SECONDS)) { throw new StreamCloseTimeoutException("Timeout closing input stream", null); } } catch (InterruptedException e) { throw new ConnectionTimeoutException(e.getMessage(), e); } }
From source file:ch.cyberduck.core.io.ThreadedStreamCloser.java
@Override public void close(final OutputStream out) throws ConnectionTimeoutException { final CountDownLatch signal = new CountDownLatch(1); threadFactory.newThread(new Runnable() { @Override/*from w ww . java 2s .c om*/ public void run() { IOUtils.closeQuietly(out); signal.countDown(); } }).start(); try { if (!signal.await(preferences.getInteger("connection.timeout.seconds"), TimeUnit.SECONDS)) { throw new StreamCloseTimeoutException("Timeout closing output stream", null); } } catch (InterruptedException e) { throw new ConnectionTimeoutException(e.getMessage(), e); } }
From source file:com.nebhale.cyclinglibrary.util.GoogleMapsPointAugmenterTest.java
@Test @SuppressWarnings("rawtypes") public void augmentPoints() throws InterruptedException, URISyntaxException { Double[][] points = new Double[0][0]; List<String> encodedPolylines = Arrays.asList("encoded-polyline-0"); when(this.polylineEncoder.encode(1900, points)).thenReturn(encodedPolylines); Task task = new Task(Long.valueOf(0), Status.IN_PROGRESS, "test-message"); when(this.taskRepository.create("Augmenting %d segments", 1)).thenReturn(task); Map<String, Object> response = new HashMap<>(); response.put("status", "OK"); List<Map<String, Object>> results = new ArrayList<>(); Map<String, Object> result = new HashMap<>(); Map<String, Object> location = new HashMap<>(); location.put("lat", 1.0); location.put("lng", 2.0); result.put("location", location); result.put("elevation", 3.0); results.add(result);//from w w w.jav a2s .com response.put("results", results); when(this.restTemplate.getForEntity(new URI( "https://maps.googleapis.com/maps/api/elevation/json?sensor=false&locations=encoded-polyline-0"), Map.class)).thenReturn(new ResponseEntity<Map>(response, HttpStatus.OK)); CountDownLatch countDownLatch = new CountDownLatch(1); StubPointAugmenterCallback callback = new StubPointAugmenterCallback(countDownLatch); this.pointAugmenter.augmentPoints(points, callback); countDownLatch.await(250, TimeUnit.MILLISECONDS); assertEquals(1, callback.points.size()); Point point = callback.points.get(0); assertEquals(Double.valueOf(1.0), point.getLatitude()); assertEquals(Double.valueOf(2.0), point.getLongitude()); assertEquals(Double.valueOf(3.0), point.getElevation()); verify(this.taskRepository).update(Long.valueOf(0), Status.IN_PROGRESS, "Augmenting %d%% complete", 100); verify(this.taskRepository).update(Long.valueOf(0), Status.SUCCESS, "Augmentation complete"); }
From source file:org.apache.cxf.systest.jaxrs.JAXRSCxfContinuationsTest.java
private void doTestContinuation(String pathSegment) throws Exception { ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(1); executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1", "CXF in Action1", startSignal, doneSignal)); startSignal.countDown();// w w w.j a v a 2s . co m doneSignal.await(60, TimeUnit.SECONDS); executor.shutdownNow(); assertEquals("Not all invocations have completed", 0, doneSignal.getCount()); }
From source file:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java
private Callable createQueryRunnable(DataSource dataSource, CountDownLatch countDownLatch) { return () -> { // open new connection try (Connection connection = dataSource.getConnection()) { // wait till all the other connections get opened countDownLatch.countDown();// www. ja v a 2 s. c o m countDownLatch.await(1, MINUTES); //check that connection is alive checkThatConnectionAlive(connection); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return null; }; }
From source file:com.linkedin.helix.TestHelper.java
public static <T> Map<String, T> startThreadsConcurrently(final List<Callable<T>> methods, final long timeout) { final int nrThreads = methods.size(); final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch finishCounter = new CountDownLatch(nrThreads); final Map<String, T> resultsMap = new ConcurrentHashMap<String, T>(); final List<Thread> threadList = new ArrayList<Thread>(); for (int i = 0; i < nrThreads; i++) { final Callable<T> method = methods.get(i); Thread thread = new Thread() { @Override/*from w w w . ja v a 2 s. c o m*/ public void run() { try { boolean isTimeout = !startLatch.await(timeout, TimeUnit.SECONDS); if (isTimeout) { LOG.error("Timeout while waiting for start latch"); } } catch (InterruptedException ex) { LOG.error("Interrupted while waiting for start latch"); } try { T result = method.call(); if (result != null) { resultsMap.put("thread_" + this.getId(), result); } LOG.debug("result=" + result); } catch (Exception e) { LOG.error("Exeption in executing " + method.getClass().getName(), e); } finishCounter.countDown(); } }; threadList.add(thread); thread.start(); } startLatch.countDown(); // wait for all thread to complete try { boolean isTimeout = !finishCounter.await(timeout, TimeUnit.SECONDS); if (isTimeout) { LOG.error("Timeout while waiting for finish latch. Interrupt all threads"); for (Thread thread : threadList) { thread.interrupt(); } } } catch (InterruptedException e) { LOG.error("Interrupted while waiting for finish latch", e); } return resultsMap; }
From source file:io.syndesis.runtime.EventsITCase.java
@Test public void wsEventsWithoutToken() throws Exception { OkHttpClient client = new OkHttpClient(); // Using a random uuid should not work to connect String uuid = UUID.randomUUID().toString(); String uriTemplate = EventBusToWebSocket.DEFAULT_PATH + "/" + uuid; String url = resolveURI(uriTemplate).toString().replaceFirst("^http", "ws"); Request request = new Request.Builder().url(url).build(); // lets setup an event handler that we can inspect events on.. WebSocketListener listener = recorder(mock(WebSocketListener.class), WebSocketListener.class); List<Recordings.Invocation> invocations = recordedInvocations(listener); CountDownLatch countDownLatch = resetRecorderLatch(listener, 1); WebSocket ws = client.newWebSocket(request, listener); // We auto get a message letting us know we connected. assertThat(countDownLatch.await(1000, TimeUnit.SECONDS)).isTrue(); assertThat(invocations.get(0).getMethod().getName()).isEqualTo("onFailure"); assertThat(invocations.get(0).getArgs()[1].toString()) .isEqualTo("java.net.ProtocolException: Expected HTTP 101 response but was '404 Not Found'"); ws.close(1000, "closing"); }