List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:interactivespaces.activity.component.ActivityComponentContextTest.java
/** * Make a couple of threads start running and see if they properly stop * running when the context signals startup failure. *///from w ww.j av a 2 s .c om @Test public void testStartupWaitWithTwoThreadsFailure() throws Exception { final CountDownLatch startLatch = new CountDownLatch(2); final CountDownLatch stopLatch = new CountDownLatch(2); final AtomicInteger countAllowedHandlers = new AtomicInteger(0); Runnable runnable = new Runnable() { @Override public void run() { startLatch.countDown(); if (context.canHandlerRun()) { countAllowedHandlers.incrementAndGet(); } stopLatch.countDown(); } }; executor.execute(runnable); executor.execute(runnable); // Make sure they have both entered before starting the wait. Assert.assertTrue(startLatch.await(500, TimeUnit.MILLISECONDS)); context.endStartupPhase(false); // Make sure they have both entered before starting the wait. Assert.assertTrue(stopLatch.await(500, TimeUnit.MILLISECONDS)); // No handlers should have been allowed. Assert.assertEquals(0, countAllowedHandlers.get()); }
From source file:com.metamx.emitter.core.HttpPostEmitter.java
@Override public void flush() throws IOException { final CountDownLatch latch = new CountDownLatch(1); if (started.get()) { final EmittingRunnable emittingRunnable = new EmittingRunnable(version.get()); exec.execute(new Runnable() { @Override/* w ww . java2s .c o m*/ public void run() { try { emittingRunnable.run(); } finally { log.debug("Counting down"); latch.countDown(); } } }); try { latch.await(); log.debug("Awaited Latch"); } catch (InterruptedException e) { log.debug("Thread Interrupted"); Thread.currentThread().interrupt(); } } }
From source file:metlos.executors.batch.BatchExecutorTest.java
public void testChangesInTaskCollectionPickedUpInRepetitions() throws Exception { final ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<Runnable>(); final AtomicInteger reportedNofTasks = new AtomicInteger(); final CountDownLatch waitForTask2 = new CountDownLatch(2); final CountDownLatch waitForTask3 = new CountDownLatch(2); Runnable task1 = new Runnable() { @Override//from w ww . ja va 2 s . c o m public void run() { } }; Runnable task2 = new Runnable() { @Override public void run() { if (tasks.size() == 2) { reportedNofTasks.set(2); waitForTask2.countDown(); } } }; Runnable task3 = new Runnable() { @Override public void run() { if (tasks.size() == 3) { reportedNofTasks.set(3); waitForTask3.countDown(); } } }; BatchExecutor ex = getExecutor(10); tasks.add(task1); tasks.add(task2); ex.submitWithPreferedDurationAndFixedDelay(tasks, 0, 0, 0, TimeUnit.MILLISECONDS); //k, now the tasks should be running and there should be just 2 of them... //so we should be getting the value of "2" reported by the reportedNofTasks waitForTask2.countDown(); waitForTask2.await(); int currentReportedTasks = reportedNofTasks.get(); assert currentReportedTasks == 2 : "We should be getting 2 tasks reported but are getting " + currentReportedTasks + " instead."; //k, now let's try updating the tasks collection... this should get picked up by the //repeated executions tasks.add(task3); //now the reported nof tasks should change to 3. let's wait on it first to make sure the executor has had time to //register the change. waitForTask3.countDown(); waitForTask3.await(); currentReportedTasks = reportedNofTasks.get(); assert currentReportedTasks == 3 : "We should be getting 3 tasks reported but are getting " + currentReportedTasks + " instead."; ex.shutdown(); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java
@Test public void testGetParticipantNodes() throws Exception { final int READERS = 20; final int WRITERS = 8; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try {/*from ww w.j a v a 2s . co m*/ client.start(); final CountDownLatch latch = new CountDownLatch(READERS + WRITERS); final CountDownLatch readLatch = new CountDownLatch(READERS); final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < READERS; ++i) { service.submit(new Callable<Void>() { @Override public Void call() throws Exception { lock.readLock().acquire(); latch.countDown(); readLatch.countDown(); return null; } }); } for (int i = 0; i < WRITERS; ++i) { service.submit(new Callable<Void>() { @Override public Void call() throws Exception { Assert.assertTrue(readLatch.await(10, TimeUnit.SECONDS)); latch.countDown(); // must be before as there can only be one writer lock.writeLock().acquire(); return null; } }); } Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Collection<String> readers = lock.readLock().getParticipantNodes(); Collection<String> writers = lock.writeLock().getParticipantNodes(); Assert.assertEquals(readers.size(), READERS); Assert.assertEquals(writers.size(), WRITERS); } finally { IOUtils.closeQuietly(client); } }
From source file:com.metamx.tranquility.kafka.KafkaConsumerTest.java
@Test(timeout = 60_000L) public void testStartConsumersNoCommit() throws Exception { final String topic = "testStartConsumersNoCommit"; final int numMessages = 5; final CountDownLatch latch = new CountDownLatch(numMessages); AdminUtils.createTopic(zkUtils, topic, 1, 1, new Properties()); consumerProperties.setProperty("topicPattern", topic); TranquilityEventWriter mockEventWriter = EasyMock.mock(TranquilityEventWriter.class); mockEventWriter.send(EasyMock.anyObject()); EasyMock.expectLastCall().andStubAnswer(new IAnswer<Void>() { @Override/* www.j a v a 2s .c om*/ public Void answer() throws Throwable { latch.countDown(); return null; } }); WriterController mockWriterController = EasyMock.mock(WriterController.class); EasyMock.expect(mockWriterController.getWriter(topic)).andReturn(mockEventWriter).times(numMessages); EasyMock.expect(mockWriterController.flushAll()).andReturn(Maps.<String, MessageCounters>newHashMap()); mockWriterController.stop(); EasyMock.expectLastCall(); EasyMock.replay(mockWriterController, mockEventWriter); TranquilityKafkaConfig config = new ConfigurationObjectFactory(consumerProperties) .build(TranquilityKafkaConfig.class); FireDepartment fd = new FireDepartment( new DataSchema(topic, null, new AggregatorFactory[] {}, null, new ObjectMapper()), new RealtimeIOConfig(new LocalFirehoseFactory(null, null, null), new PlumberSchool() { @Override public Plumber findPlumber(DataSchema schema, RealtimeTuningConfig config, FireDepartmentMetrics metrics) { return null; } }, null), null); Map<String, DataSourceConfig<TranquilityKafkaConfig>> datasourceConfigs = ImmutableMap.of(topic, new DataSourceConfig<>(config, topic, fireDepartmentToScalaMap(fd))); // commitMillis is set high enough that the commit thread should not run during the test KafkaConsumer kafkaConsumer = new KafkaConsumer(config, consumerProperties, datasourceConfigs, mockWriterController); kafkaConsumer.start(); Assert.assertEquals("Unexpected consumer offset", -1, getConsumerOffset(topic)); for (int i = numMessages; i > 0; i--) { producer.send(new ProducerRecord<>(topic, MESSAGE)).get(); } producer.flush(); latch.await(); // check that offset wasn't committed since commit thread didn't run Assert.assertEquals("Unexpected consumer offset", -1, getConsumerOffset(topic)); kafkaConsumer.stop(); // check that offset was committed on shutdown Assert.assertEquals("Unexpected consumer offset", numMessages, getConsumerOffset(topic)); EasyMock.verify(mockWriterController, mockEventWriter); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphoreCluster.java
@Test public void testCluster() throws Exception { final int QTY = 20; final int OPERATION_TIME_MS = 1000; final String PATH = "/foo/bar/lock"; ExecutorService executorService = Executors.newFixedThreadPool(QTY); ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService); final Timing timing = new Timing(); TestingCluster cluster = new TestingCluster(3); List<SemaphoreClient> semaphoreClients = Lists.newArrayList(); try {//from w w w .j av a 2 s . c o m cluster.start(); final AtomicInteger opCount = new AtomicInteger(0); for (int i = 0; i < QTY; ++i) { SemaphoreClient semaphoreClient = new SemaphoreClient(cluster.getConnectString(), PATH, new Callable<Void>() { @Override public Void call() throws Exception { opCount.incrementAndGet(); Thread.sleep(OPERATION_TIME_MS); return null; } }); completionService.submit(semaphoreClient); semaphoreClients.add(semaphoreClient); } timing.forWaiting().sleepABit(); Assert.assertNotNull(SemaphoreClient.getActiveClient()); final CountDownLatch latch = new CountDownLatch(1); CuratorFramework client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.LOST) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.start(); try { client.getZookeeperClient().blockUntilConnectedOrTimedOut(); cluster.stop(); latch.await(); } finally { IOUtils.closeQuietly(client); } long startTicks = System.currentTimeMillis(); for (;;) { int thisOpCount = opCount.get(); Thread.sleep(2 * OPERATION_TIME_MS); if (thisOpCount == opCount.get()) { break; // checking that the op count isn't increasing } Assert.assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); } int thisOpCount = opCount.get(); Iterator<InstanceSpec> iterator = cluster.getInstances().iterator(); cluster = new TestingCluster(iterator.next(), iterator.next()); cluster.start(); timing.forWaiting().sleepABit(); startTicks = System.currentTimeMillis(); for (;;) { Thread.sleep(2 * OPERATION_TIME_MS); if (opCount.get() > thisOpCount) { break; // checking that semaphore has started working again } Assert.assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); } } finally { for (SemaphoreClient semaphoreClient : semaphoreClients) { IOUtils.closeQuietly(semaphoreClient); } IOUtils.closeQuietly(cluster); executorService.shutdownNow(); } }
From source file:com.uber.hoodie.common.util.queue.BoundedInMemoryExecutor.java
/** * Start all Producers//w w w .ja v a 2s . c om */ public ExecutorCompletionService<Boolean> startProducers() { // Latch to control when and which producer thread will close the queue final CountDownLatch latch = new CountDownLatch(producers.size()); final ExecutorCompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>( executorService); producers.stream().map(producer -> { return completionService.submit(() -> { try { preExecute(); producer.produce(queue); } catch (Exception e) { logger.error("error consuming records", e); queue.markAsFailed(e); throw e; } finally { synchronized (latch) { latch.countDown(); if (latch.getCount() == 0) { // Mark production as done so that consumer will be able to exit queue.close(); } } } return true; }); }).collect(Collectors.toList()); return completionService; }
From source file:org.callimachusproject.script.ConcurrentResponseTest.java
public void testResponseConcurrent() throws Throwable { int n = Runtime.getRuntime().availableProcessors() * 4; final CountDownLatch up = new CountDownLatch(1); final CountDownLatch down = new CountDownLatch(n); final List<Throwable> errors = new ArrayList<Throwable>(n); for (int i = 0; i < n; i++) { new Thread(new Runnable() { public void run() { try { up.await();/*from w ww . j a v a 2 s .c om*/ for (int i = 0; i < 100; i++) { testJsonResponse(); } } catch (Throwable e) { e.printStackTrace(); synchronized (errors) { errors.add(e); } } finally { down.countDown(); } } }).start(); } up.countDown(); down.await(); synchronized (errors) { if (!errors.isEmpty()) { throw errors.get(0); } } }
From source file:com.metamx.tranquility.kafka.KafkaConsumerTest.java
@Test(timeout = 60_000L) public void testStartConsumersWithCommitThread() throws Exception { final String topic = "testStartConsumersWithCommitThread"; final int numMessages = 8; final CountDownLatch latch = new CountDownLatch(numMessages); AdminUtils.createTopic(zkUtils, topic, 1, 1, new Properties()); consumerProperties.setProperty("topicPattern", topic); TranquilityEventWriter mockEventWriter = EasyMock.mock(TranquilityEventWriter.class); mockEventWriter.send(EasyMock.anyObject()); EasyMock.expectLastCall().andStubAnswer(new IAnswer<Void>() { @Override//from w ww . ja v a 2s.c om public Void answer() throws Throwable { latch.countDown(); return null; } }); WriterController mockWriterController = EasyMock.mock(WriterController.class); EasyMock.expect(mockWriterController.getWriter(topic)).andReturn(mockEventWriter).times(numMessages); EasyMock.expect(mockWriterController.flushAll()).andReturn(Maps.<String, MessageCounters>newHashMap()) .times(2); mockWriterController.stop(); EasyMock.expectLastCall(); EasyMock.replay(mockWriterController, mockEventWriter); TranquilityKafkaConfig config = new ConfigurationObjectFactory(consumerProperties) .build(TranquilityKafkaConfig.class); FireDepartment fd = new FireDepartment( new DataSchema(topic, null, new AggregatorFactory[] {}, null, new ObjectMapper()), new RealtimeIOConfig(new LocalFirehoseFactory(null, null, null), new PlumberSchool() { @Override public Plumber findPlumber(DataSchema schema, RealtimeTuningConfig config, FireDepartmentMetrics metrics) { return null; } }, null), null); Map<String, DataSourceConfig<TranquilityKafkaConfig>> datasourceConfigs = ImmutableMap.of(topic, new DataSourceConfig<>(config, topic, fireDepartmentToScalaMap(fd))); // commitMillis is set high enough that the commit thread should not run during the test KafkaConsumer kafkaConsumer = new KafkaConsumer(config, consumerProperties, datasourceConfigs, mockWriterController); kafkaConsumer.start(); Assert.assertEquals("Unexpected consumer offset", -1, getConsumerOffset(topic)); for (int i = numMessages; i > 0; i--) { producer.send(new ProducerRecord<>(topic, MESSAGE)).get(); } producer.flush(); latch.await(); kafkaConsumer.commit(); // check that offset was committed since commit ran Assert.assertEquals("Unexpected consumer offset", numMessages, getConsumerOffset(topic)); kafkaConsumer.stop(); Assert.assertEquals("Unexpected consumer offset", numMessages, getConsumerOffset(topic)); EasyMock.verify(mockWriterController, mockEventWriter); }
From source file:io.fabric8.kubernetes.PodIT.java
@Test public void exec() throws InterruptedException { // Wait for resources to get ready ReadyEntity<Pod> podReady = new ReadyEntity<>(Pod.class, client, pod1.getMetadata().getName(), currentNamespace);/*from www.ja va 2s. co m*/ await().atMost(30, TimeUnit.SECONDS).until(podReady); final CountDownLatch execLatch = new CountDownLatch(1); ByteArrayOutputStream out = new ByteArrayOutputStream(); ExecWatch execWatch = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()) .writingOutput(out).withTTY().usingListener(new ExecListener() { @Override public void onOpen(Response response) { logger.info("Shell was opened"); } @Override public void onFailure(Throwable throwable, Response response) { logger.info("Shell barfed"); execLatch.countDown(); } @Override public void onClose(int i, String s) { logger.info("Shell closed"); execLatch.countDown(); } }).exec("date"); execLatch.await(5, TimeUnit.SECONDS); assertNotNull(execWatch); assertNotNull(out.toString()); }