List of usage examples for java.util.concurrent CountDownLatch getCount
public long getCount()
From source file:org.jenkinsci.remoting.protocol.IOHubTest.java
@Test public void hubCanRunTasks() throws Exception { final CountDownLatch started = new CountDownLatch(1); final CountDownLatch finish = new CountDownLatch(1); final CountDownLatch finished = new CountDownLatch(1); hub.hub().execute(new Runnable() { @Override/*from w w w . j a v a 2s .co m*/ public void run() { started.countDown(); try { finish.await(); } catch (InterruptedException e) { // ignore } finally { finished.countDown(); } } }); assertThat(finished.getCount(), is(1L)); started.await(); assertThat(finished.getCount(), is(1L)); finish.countDown(); assertThat(finished.await(1, TimeUnit.SECONDS), is(true)); }
From source file:com.hazelcast.hibernate.app.Executor.java
public void execute() throws Exception { CountDownLatch latch = new CountDownLatch(1000); int count;// ww w.j a v a 2 s . c om Session session = sessionFactory.openSession(); try { Criteria criteria = session.createCriteria(DummyEntity.class); criteria.setProjection(Projections.rowCount()); count = ((Long) criteria.uniqueResult()).intValue(); } finally { session.close(); } if (count == 0) { count = 200000; insertDummyEntities(count, 100); } try { for (int i = 0; i < latch.getCount(); i++) { executorService.submit(new Task(i, sessionFactory, 1000, latch)); } latch.await(1, TimeUnit.DAYS); } finally { executorService.shutdown(); } }
From source file:WorkQueue.java
/** * Waits until all the tasks associated with the group identifier have * finished. Once a task group has been successfully waited upon, the group * identifier is removed from the queue and is valid to be reused for a new * task group.//from w w w . j a v a 2 s . c om * * @throws IllegalArgumentException if the {@code taskGroupId} is not * currently associated with any active taskGroup */ public void await(Object taskGroupId) { CountDownLatch latch = taskKeyToLatch.get(taskGroupId); if (latch == null) throw new IllegalArgumentException("Unknown task group: " + taskGroupId); try { while (!latch.await(5, TimeUnit.SECONDS)) System.out.println("cur count: " + latch.getCount()); // Once finished, remove the key so it can be associated with a new // task taskKeyToLatch.remove(taskGroupId); } catch (InterruptedException ie) { throw new IllegalStateException("Not all tasks finished", ie); } }
From source file:io.fabric8.msg.jnatsd.TestConnect.java
@Test public void testConnect() throws Exception { Connection subConnection = connectionFactory.createConnection(); final int count = 1000; CountDownLatch countDownLatch = new CountDownLatch(count); Subscription subscription = subConnection.subscribe("foo", new MessageHandler() { @Override//from w w w . j av a2 s. co m public void onMessage(Message message) { countDownLatch.countDown(); //System.out.println("GOT " + message); } }); Connection pubConnection = new ConnectionFactory().createConnection(); for (int i = 0; i < count; i++) { String test = "Test" + i; pubConnection.publish("foo", "bah", test.getBytes()); } countDownLatch.await(2, TimeUnit.SECONDS); Assert.assertEquals(0, countDownLatch.getCount()); pubConnection.close(); subConnection.close(); }
From source file:org.commonjava.cartographer.INTERNAL.graph.agg.DefaultGraphAggregator.java
/** * Convert the current set of {@link DiscoveryTodo}'s into a set of * {@link DiscoveryRunnable}'s after first ensuring their corresponding GAVs * aren't already present, listed as missing, or listed as participants in a * relationship cycle.//from w ww . ja v a 2 s . c o m * * Then, execute all of these runnables and wait for processing to complete * before passing them back for output processing. * * @param todos The current set of {@link DiscoveryTodo}'s to process * @param config Configuration for how discovery should proceed * @param missing The accumulated list of confirmed-missing GAVs (NOT things * that have yet to be discovered) * @param seen map of seen projects pointing at the set of dependency exclusions * used by the filter * @param pass For diagnostic/logging purposes, the number of discovery passes * since discovery was initiated by the caller (part of the graph may have been * pre-existing) * @return The executed set of {@link DiscoveryRunnable} instances that contain * output to be processed and incorporated in the graph. */ private Set<DiscoveryRunnable> executeTodoBatch(final Set<DiscoveryTodo> todos, final AggregationOptions config, final Set<ProjectVersionRef> missing, final Map<ProjectVersionRef, Set<ProjectRef>> seen, /*final Set<ProjectVersionRef> cycleParticipants,*/final int pass) { final Set<DiscoveryRunnable> runnables = new HashSet<DiscoveryRunnable>(todos.size()); final Set<ProjectVersionRef> roMissing = Collections.unmodifiableSet(missing); int idx = 0; for (final DiscoveryTodo todo : todos) { final ProjectVersionRef todoRef = todo.getRef(); if (missing.contains(todoRef)) { logger.info("{}.{}. Skipping missing reference: {}", pass, idx++, todoRef); continue; } // else if ( cycleParticipants.contains( todoRef ) ) // { // logger.info( "{}.{}. Skipping cycle-participant reference: {}", pass, idx++, todoRef ); // continue; // } // WAS: net.containsProject(todoRef) ...this is pretty expensive, since it requires traversal. Instead, we track as we go. else if (seen.containsKey(todoRef) && todo.getDepExcludes().containsAll(seen.get(todoRef))) { logger.info("{}.{}. Skipping already-discovered reference: {}", pass, idx++, todoRef); continue; } // logger.info( "DISCOVER += {}", todo ); final DiscoveryRunnable runnable = new DiscoveryRunnable(todo, config, roMissing, discoverer, pass, idx); runnables.add(runnable); idx++; } final CountDownLatch latch = new CountDownLatch(runnables.size()); for (final DiscoveryRunnable runnable : runnables) { runnable.setLatch(latch); executor.execute(runnable); } while (latch.getCount() > 0) { logger.info("Waiting for {} more discovery threads to complete", latch.getCount()); try { latch.await(2, TimeUnit.SECONDS); } catch (final InterruptedException e) { logger.error("Interrupted on subgraph discovery."); return null; } } return runnables; }
From source file:com.android.switchaccess.SwitchAccessEndToEndTest.java
@MediumTest public void testScrolling_scroll() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return;//from w w w . j a v a2s . co m } final ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scroll_id); final CountDownLatch scrollsMissed = new CountDownLatch(1); scrollView.setAccessibilityDelegate(new AccessibilityDelegate() { @Override public boolean performAccessibilityAction(@NonNull View host, int action, Bundle args) { if (action == AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD) { scrollsMissed.countDown(); } return super.performAccessibilityAction(host, action, args); } }); sendKeyEventSync(mMoveFocusEvent); sendKeyEventSync(mScrollForwardEvent); assertEquals(0, scrollsMissed.getCount()); }
From source file:com.mozilla.fhr.consumer.FHRConsumer.java
@Override public void poll() { final CountDownLatch latch = new CountDownLatch(streams.size()); workers = new ArrayList<Future<Void>>(streams.size()); for (final KafkaStream<Message> stream : streams) { workers.add(executor.submit(new FHRConsumerWorker(stream, latch))); }//from w ww . j a v a2 s . co m // Wait for all tasks to complete which in the normal case they will // run indefinitely unless killed try { while (true) { latch.await(10, TimeUnit.SECONDS); if (latch.getCount() != streams.size()) { // we have a dead thread and should exit break; } } } catch (InterruptedException e) { LOG.info("Interrupted during polling", e); } // Spit out errors if there were any for (Future<Void> worker : workers) { try { if (worker.isDone() && !worker.isCancelled()) { worker.get(1, TimeUnit.SECONDS); } } catch (InterruptedException e) { LOG.error("Thread was interrupted:", e); } catch (ExecutionException e) { LOG.error("Exception occured in thread:", e); } catch (TimeoutException e) { LOG.error("Timed out waiting for thread result:", e); } catch (CancellationException e) { LOG.error("Thread has been canceled: ", e); } } }
From source file:org.springframework.integration.channel.QueueChannelTests.java
@Test public void testReactorPersistentQueue() throws InterruptedException, IOException { final AtomicBoolean messageReceived = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); PersistentQueue<Message<?>> queue = new PersistentQueueSpec<Message<?>>() .codec(new JavaSerializationCodec<Message<?>>()) .basePath(this.tempFolder.getRoot().getAbsolutePath()).get(); final QueueChannel channel = new QueueChannel(queue); new Thread(new Runnable() { @Override/* ww w . ja va 2s. c om*/ public void run() { Message<?> message = channel.receive(); if (message != null) { messageReceived.set(true); latch.countDown(); } } }).start(); assertFalse(messageReceived.get()); channel.send(new GenericMessage<String>("testing")); latch.await(1000, TimeUnit.MILLISECONDS); assertTrue(messageReceived.get()); final CountDownLatch latch1 = new CountDownLatch(2); Thread thread = new Thread(new Runnable() { @Override public void run() { while (true) { Message<?> message = channel.receive(100); if (message != null) { latch1.countDown(); if (latch1.getCount() == 0) { break; } } } } }); thread.start(); Thread.sleep(200); channel.send(new GenericMessage<String>("testing")); channel.send(new GenericMessage<String>("testing")); assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS)); final AtomicBoolean receiveInterrupted = new AtomicBoolean(false); final CountDownLatch latch2 = new CountDownLatch(1); Thread t = new Thread(new Runnable() { @Override public void run() { Message<?> message = channel.receive(10000); receiveInterrupted.set(true); assertTrue(message == null); latch2.countDown(); } }); t.start(); assertFalse(receiveInterrupted.get()); t.interrupt(); latch2.await(); assertTrue(receiveInterrupted.get()); receiveInterrupted.set(false); final CountDownLatch latch3 = new CountDownLatch(1); t = new Thread(new Runnable() { @Override public void run() { Message<?> message = channel.receive(); receiveInterrupted.set(true); assertTrue(message == null); latch3.countDown(); } }); t.start(); assertFalse(receiveInterrupted.get()); t.interrupt(); latch3.await(); assertTrue(receiveInterrupted.get()); GenericMessage<String> message1 = new GenericMessage<String>("test1"); GenericMessage<String> message2 = new GenericMessage<String>("test2"); assertTrue(channel.send(message1)); assertTrue(channel.send(message2)); List<Message<?>> clearedMessages = channel.clear(); assertNotNull(clearedMessages); assertEquals(2, clearedMessages.size()); clearedMessages = channel.clear(); assertNotNull(clearedMessages); assertEquals(0, clearedMessages.size()); // Test on artificial infinite wait // channel.receive(); // Distributed scenario final CountDownLatch latch4 = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { Message<?> message = channel.receive(); if (message != null) { latch4.countDown(); } } }).start(); queue.add(new GenericMessage<String>("foo")); assertTrue(latch4.await(1000, TimeUnit.MILLISECONDS)); }
From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java
@Test public void testRetry() throws Exception { final ServerSocket[] serverSocket = new ServerSocket[1]; final ExecutorService[] executor = new ExecutorService[1]; try {// w w w . j ava 2s . co m serverSocket[0] = new ServerSocket(0); executor[0] = Executors.newCachedThreadPool(); int port = serverSocket[0].getLocalPort(); Callable<Void> serverTask = new Callable<Void>() { @Override public Void call() throws Exception { Socket socket = serverSocket[0].accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String value = reader.readLine(); assertEquals("0", value); socket.close(); return null; } }; Future<Void> serverFuture = executor[0].submit(serverTask); final SocketClientSink<String> sink = new SocketClientSink<>(host, serverSocket[0].getLocalPort(), simpleSchema, -1, true); // Create the connection sink.open(new Configuration()); // Initial payload => this will be received by the server an then the socket will be // closed. sink.invoke("0\n"); // Get future an make sure there was no problem. This will rethrow any Exceptions from // the server. serverFuture.get(); // Shutdown the server socket serverSocket[0].close(); assertTrue(serverSocket[0].isClosed()); // No retries expected at this point assertEquals(0, sink.getCurrentNumberOfRetries()); final CountDownLatch retryLatch = new CountDownLatch(1); final CountDownLatch again = new CountDownLatch(1); Callable<Void> sinkTask = new Callable<Void>() { @Override public Void call() throws Exception { // Send next payload => server is down, should try to reconnect. // We need to send more than just one packet to notice the closed connection. while (retryLatch.getCount() != 0) { sink.invoke("1\n"); } return null; } }; Future<Void> sinkFuture = executor[0].submit(sinkTask); while (sink.getCurrentNumberOfRetries() == 0) { // Wait for a retry Thread.sleep(100); } // OK the poor guy retried to write retryLatch.countDown(); // Restart the server serverSocket[0] = new ServerSocket(port); Socket socket = serverSocket[0].accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Wait for the reconnect String value = reader.readLine(); assertEquals("1", value); // OK the sink re-connected. :) } finally { if (serverSocket[0] != null) { serverSocket[0].close(); } if (executor[0] != null) { executor[0].shutdown(); } } }