List of usage examples for java.util.concurrent CountDownLatch await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
From source file:io.kamax.mxisd.backend.firebase.GoogleFirebaseAuthenticator.java
private void waitOnLatch(BackendAuthResult result, CountDownLatch l, String purpose) { try {/*from w w w . j a v a 2 s .c o m*/ l.await(30, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("Interrupted while waiting for " + purpose); result.fail(); } }
From source file:fr.keemto.scheduling.ScheduledTaskIT.java
@Test public void shouldExecuteFetcherAsychronouslyWithDelay() throws Exception { CountDownLatch latch = new CountDownLatch(10); Task countDownTask = new CountDownTask(latch); scheduler.scheduleTask(countDownTask); latch.await(2000, TimeUnit.MILLISECONDS); assertThat(latch.getCount(), equalTo((long) 0)); }
From source file:org.auraframework.test.AuraTestingUtil.java
/** * Clear cached defs from the system. When mocking a def, if the def has already been cached, as itself, or as part * of a preloaded set, the mock will not be effective, so it's safer to clear any cached defs after setting up mocks * but before executing a test. This relies on source change notifications to get the servlets to clear their * caches./*from www . j av a2 s. com*/ * * @param defs the Definitions to be cleared from any caches * @throws InterruptedException */ public static <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception { if (defs == null || defs.isEmpty()) { return; } // Get the Descriptors for the provided Definitions final DefinitionService definitionService = Aura.getDefinitionService(); final Set<DefDescriptor<?>> cached = Sets.newHashSet(); for (T def : defs) { if (def != null) { cached.add(def.getDescriptor()); } } // Wait for the change notifications to get processed. We expect listeners to get processed in the order in // which they subscribe. final CountDownLatch latch = new CountDownLatch(cached.size()); SourceListener listener = new SourceListener() { private Set<DefDescriptor<?>> descriptors = Sets.newHashSet(cached); @Override public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event, String filePath) { if (descriptors.remove(source)) { latch.countDown(); } if (descriptors.isEmpty()) { definitionService.unsubscribeToChangeNotification(this); } } }; definitionService.subscribeToChangeNotification(listener); for (DefDescriptor<?> desc : cached) { definitionService.onSourceChanged(desc, SourceMonitorEvent.CHANGED, null); } if (!latch.await(CACHE_CLEARING_TIMEOUT_SECS, TimeUnit.SECONDS)) { throw new AuraRuntimeException( String.format("Timed out after %s seconds waiting for cached Aura definitions to clear: %s", CACHE_CLEARING_TIMEOUT_SECS, defs)); } }
From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java
/** * Function used to wait for a service to be available. * * @param host/*from w ww . j av a 2s . co m*/ * @param timeout * @param serviceLinks * @throws Throwable */ public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks) throws Throwable { final CountDownLatch latch = new CountDownLatch(serviceLinks.length); final Throwable error = new Throwable("Error: registerForAvailability returned errors"); Operation.CompletionHandler handler = new Operation.CompletionHandler() { @Override public void handle(Operation operation, Throwable throwable) { if (null != throwable) { error.addSuppressed(throwable); } latch.countDown(); } }; host.registerForServiceAvailability(handler, serviceLinks); if (!latch.await(timeout, TimeUnit.MILLISECONDS)) { throw new TimeoutException(String.format("One or several of service(s) %s not available", Utils.toJson(false, false, serviceLinks))); } if (error.getSuppressed().length > 0) { throw error; } }
From source file:com.navercorp.pinpoint.profiler.sender.NioUdpDataSenderTest.java
private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException { final AtomicBoolean limitCounter = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); NioUDPDataSender sender = newNioUdpDataSender(); try {// w ww. j ava 2s .c om sender.send(tbase); latch.await(waitTimeMillis, TimeUnit.MILLISECONDS); } finally { sender.stop(); } return limitCounter.get(); }
From source file:siia.booking.integration.FlightNotificationsSpelTest.java
@Test public void notificationShouldArriveAtSmsAdapter() throws Exception { TripNotification notification = mock(TripNotification.class); Message tripNotificationMessage = MessageBuilder.withPayload(notification).build(); CountDownLatch notifierInvoked = new CountDownLatch(1); doAnswer(countsDownLatch(notifierInvoked)).when(smsNotifier).notify(notification); tripNotifications.send(tripNotificationMessage); notifierInvoked.await(100, MILLISECONDS); verify(smsNotifier).notify(notification); }
From source file:uk.co.sdev.undertow.rx.services.offers.OffersServiceTest.java
@Test public void shouldReturnObservableOfOffers() throws Exception { OffersService service = new OffersService(mapper, client, "http://localhost:9101/offers"); stubGet("/offers?count=2", Arrays.asList(new Offer("offer1", "description1", "offer1.jpg"), new Offer("offer2", "description2", "offer2.jpg"))); List<Offer> offers = new ArrayList<>(); List<Throwable> throwables = new ArrayList<>(); CountDownLatch finished = new CountDownLatch(1); Observable<Offer> offer = service.offers(2); new Thread(() -> offer.subscribe(o -> offers.add(o), t -> throwables.add(t), () -> finished.countDown())) .start();/* w ww.java 2s .com*/ finished.await(5, TimeUnit.SECONDS); assertThat(offers.size(), is(2)); assertThat(offers.get(0).getTitle(), is("offer1")); assertThat(offers.get(1).getTitle(), is("offer2")); }
From source file:com.nebhale.cyclinglibrary.util.GoogleMapsPointAugmenterTest.java
@Test @SuppressWarnings("rawtypes") public void augmentPointsFailure() 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, String> response = new HashMap<>(); response.put("status", "FAIL"); 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); this.pointAugmenter.augmentPoints(points, new StubPointAugmenterCallback(countDownLatch)); boolean result = countDownLatch.await(250, TimeUnit.MILLISECONDS); assertFalse(result);// ww w . j av a 2s . co m verify(this.taskRepository).update(Long.valueOf(0), Status.FAILURE, "java.lang.IllegalStateException: Point augmentation failed with a status of 'FAIL'"); }
From source file:com.palantir.docker.compose.logging.FileLogCollectorShould.java
@Test public void collect_logs_when_one_container_is_running_and_does_not_terminate_until_after_start_collecting_is_run() throws Exception { when(compose.ps()).thenReturn(TestContainerNames.of("db")); CountDownLatch latch = new CountDownLatch(1); when(compose.writeLogs(eq("db"), any(OutputStream.class))).thenAnswer((args) -> { if (!latch.await(1, TimeUnit.SECONDS)) { throw new RuntimeException("Latch was not triggered"); }// w ww .j ava 2s . c o m OutputStream outputStream = (OutputStream) args.getArguments()[1]; IOUtils.write("log", outputStream); return false; }); logCollector.startCollecting(compose); latch.countDown(); logCollector.stopCollecting(); assertThat(logDirectory.listFiles(), arrayContaining(fileWithName("db.log"))); assertThat(new File(logDirectory, "db.log"), is(fileContainingString("log"))); }
From source file:com.datatorrent.demos.adsdimension.KafkaApplicationTest.java
@Test public void testApplication() throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.set("dt.operator.Kafka.prop.configProperties(metadata.broker.list)", "localhost:9092"); conf.set("dt.operator.Kafka.prop.topic", kafkaTopic); conf.set("dt.operator.DimensionsComputation.attr.APPLICATION_WINDOW_COUNT", "1"); lma.prepareDAG(new KafkaApplication(), conf); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); lc.runAsync();/*from ww w . j a v a2s . co m*/ CountDownLatch latch = new CountDownLatch(100); // Setup a message listener to receive the message KafkaTestConsumer listener = new KafkaTestConsumer(kafkaTopic); listener.setLatch(latch); new Thread(listener).start(); latch.await(30, TimeUnit.SECONDS); lc.shutdown(); String lastMessage; Assert.assertTrue("Minimum messages received from Kafka " + listener.holdingBuffer, listener.holdingBuffer.size() >= 100); while (!listener.holdingBuffer.isEmpty()) { lastMessage = listener.getMessage(listener.holdingBuffer.poll()); Assert.assertNotNull("Did not receive message from Kafka", lastMessage); LOG.debug("received:\n{}", lastMessage); } }