Tabnine Logo
CountDownLatch
Code IndexAdd Tabnine to your IDE (free)

How to use
CountDownLatch
in
java.util.concurrent

Best Java code snippets using java.util.concurrent.CountDownLatch (Showing top 20 results out of 28,071)

Refine searchRefine arrow

  • AtomicInteger
  • AtomicBoolean
  • AtomicReference
  • ExecutorService
  • Executors
  • Ignite
  • Session
  • BrokerService
origin: ReactiveX/RxJava

  @Override
  public void accept(Throwable e) throws Exception {
    interrupted.set(Thread.currentThread().isInterrupted());
    cdl.countDown();
  }
});
origin: ReactiveX/RxJava

@Override
public void onNext(String t) {
  firstOnNext.countDown();
  // force it to take time when delivering so the second one is enqueued
  try {
    latch.await();
  } catch (InterruptedException e) {
  }
}
origin: google/guava

 @Override
 public Void call() throws Exception {
  enterLatch.countDown();
  new CountDownLatch(1).await(); // wait forever
  return null;
 }
});
origin: google/guava

 @Override
 public synchronized void run() {
  checkState(wasRun.getCount() > 0);
  wasRun.countDown();
 }
}
origin: ReactiveX/RxJava

@Test(timeout = 1000)
public void testUnSubscribeObservableOfObservables() throws InterruptedException {
  final AtomicBoolean unsubscribed = new AtomicBoolean();
  final CountDownLatch latch = new CountDownLatch(1);
  final AtomicInteger count = new AtomicInteger();
  Observable.merge(source).take(6).blockingForEach(new Consumer<Long>() {
  latch.await(1000, TimeUnit.MILLISECONDS);
  System.out.println("unsubscribed: " + unsubscribed.get());
  assertTrue(unsubscribed.get());
origin: google/guava

AtomicBoolean computationShouldWait = new AtomicBoolean();
CountDownLatch computationLatch = new CountDownLatch(1);
QueuingRemovalListener<String, String> listener = queuingRemovalListener();
final LoadingCache<String, String> cache =
 expectedKeys.add(s);
computationShouldWait.set(true);
final AtomicInteger computedCount = new AtomicInteger();
ExecutorService threadPool = Executors.newFixedThreadPool(nThreads);
final CountDownLatch tasksFinished = new CountDownLatch(nTasks);
for (int i = 0; i < nTasks; i++) {
 final String s = "a" + i;
 @SuppressWarnings("unused") // go/futurereturn-lsc
 Future<?> possiblyIgnoredError =
   threadPool.submit(
     new Runnable() {
      @Override
computationLatch.countDown();
while (computedCount.get() < nThreads) {
 Thread.yield();
tasksFinished.await();
origin: neo4j/neo4j

private void unlockExclusiveAndTakeWriteLockMustBeAtomic() throws Exception
  CountDownLatch start = new CountDownLatch( threads );
  AtomicBoolean stop = new AtomicBoolean();
  OffHeapPageLock.tryExclusiveLock( lockAddr );
  Runnable runnable = () ->
    while ( !stop.get() )
        throw new RuntimeException( "I should not have gotten that lock" );
      start.countDown();
  for ( int i = 0; i < threads; i++ )
    futures.add( executor.submit( runnable ) );
  start.await();
  OffHeapPageLock.unlockExclusiveAndTakeWriteLock( lockAddr );
  stop.set( true );
  for ( Future<?> future : futures )
origin: ReactiveX/RxJava

final int numRetries = Flowable.bufferSize() * 2;
int ncpu = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2));
try {
  for (int r = 0; r < NUM_LOOPS; r++) {
    final AtomicInteger timeouts = new AtomicInteger();
    final Map<Integer, List<String>> data = new ConcurrentHashMap<Integer, List<String>>();
    final CountDownLatch cdl = new CountDownLatch(m);
    for (int i = 0; i < m; i++) {
      final int j = i;
      exec.execute(new Runnable() {
        @Override
        public void run() {
    cdl.await();
    assertEquals(0, timeouts.get());
    if (data.size() > 0) {
      fail("Data content mismatch: " + allSequenceFrequency(data));
  exec.shutdown();
origin: google/guava

final AtomicBoolean functionCalled = new AtomicBoolean();
AsyncFunction<String, Integer> function =
  new AsyncFunction<String, Integer>() {
ExecutorService executor = newSingleThreadExecutor();
ListenableFuture<Integer> future = transformAsync(inputFuture, function, executor);
final CountDownLatch beforeFunction = new CountDownLatch(1);
executor.execute(
  new Runnable() {
   @Override
beforeFunction.countDown();
executor.shutdown();
assertTrue(executor.awaitTermination(5, SECONDS));
assertFalse(functionCalled.get());
origin: apache/incubator-druid

final CountDownLatch queueShouldBeFullSignal = new CountDownLatch(capacity + 1);
final CountDownLatch taskCompletedSignal = new CountDownLatch(nTasks);
final CountDownLatch taskStartSignal = new CountDownLatch(1);
final AtomicInteger producedCount = new AtomicInteger();
final AtomicInteger consumedCount = new AtomicInteger();
final ExecutorService producer = Executors.newSingleThreadExecutor(
  new ThreadFactoryBuilder().setNameFormat(
    "ExecsTest-Producer-%d"
  ).build()
);
producer.submit(
  new Runnable()
queueShouldBeFullSignal.await();
Assert.assertEquals(capacity + 1, producedCount.get());
taskStartSignal.countDown();
taskCompletedSignal.await();
Assert.assertEquals(nTasks, consumedCount.get());
blockingExecutor.shutdown();
producer.shutdown();
origin: apache/activemq-artemis

public void testMessageListenerWithConsumer() throws Exception {
 final AtomicInteger counter = new AtomicInteger(0);
 final CountDownLatch done = new CountDownLatch(1);
 // Receive a message with the JMS API
 connection.start();
 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 ActiveMQDestination destination = createDestination(session, destinationType);
 MessageConsumer consumer = session.createConsumer(destination);
 consumer.setMessageListener(new MessageListener() {
   @Override
   public void onMessage(Message m) {
    counter.incrementAndGet();
    if (counter.get() == 4) {
      done.countDown();
    }
   }
 });
 // Send the messages
 sendMessages(session, destination, 4);
 assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
 Thread.sleep(200);
 // Make sure only 4 messages were delivered.
 assertEquals(4, counter.get());
}
origin: spring-projects/spring-framework

int end = 1000;
AtomicInteger index = new AtomicInteger(start);
AtomicReference<Object> result = new AtomicReference<>();
CountDownLatch latch = new CountDownLatch(1);
  int expected = index.getAndIncrement();
  Integer actual = (Integer) message.getHeaders().getOrDefault("seq", -1);
  if (actual != expected) {
    result.set("Expected: " + expected + ", but was: " + actual);
    latch.countDown();
    return;
      result.set(ex.toString());
      latch.countDown();
    result.set("Done");
    latch.countDown();
latch.await(10, TimeUnit.SECONDS);
assertEquals("Done", result.get());
origin: ReactiveX/RxJava

final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger();
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
latch.await();
assertEquals(2, count.get());
assertNotNull(error.get());
if (!(error.get() instanceof NumberFormatException)) {
  fail("It should be a NumberFormatException");
origin: eclipse-vertx/vert.x

ExecutorService exec = Executors.newFixedThreadPool(1);
try {
 server.connectHandler(so -> {
  so.handler(buff -> {
   assertEquals(256, buff.length());
   CountDownLatch latch = new CountDownLatch(1);
   exec.execute(() -> {
    latch.countDown();
    so.write(expected);
   });
 });
 startServer();
 AtomicInteger done = new AtomicInteger();
 for (int i = 0;i < num;i++) {
  client.connect(testAddress, ar -> {
     assertEquals(expected, buff);
     so.close();
     int val = done.incrementAndGet();
     if (val == num) {
      testComplete();
 exec.shutdown();
origin: AsyncHttpClient/async-http-client

@Test
public void testListenableFuture() throws Exception {
 final AtomicInteger statusCode = new AtomicInteger(500);
 try (AsyncHttpClient ahc = asyncHttpClient()) {
  final CountDownLatch latch = new CountDownLatch(1);
  final ListenableFuture<Response> future = ahc.prepareGet(getTargetUrl()).execute();
  future.addListener(() -> {
   try {
    statusCode.set(future.get().getStatusCode());
    latch.countDown();
   } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
   }
  }, Executors.newFixedThreadPool(1));
  latch.await(10, TimeUnit.SECONDS);
  assertEquals(statusCode.get(), 200);
 }
}
origin: ReactiveX/RxJava

final SerialDisposable task = new SerialDisposable();
try {
  final CountDownLatch finished = new CountDownLatch(1);
  final int COUNT = 30;
  final CountDownLatch timeHasPassed = new CountDownLatch(COUNT);
  final AtomicBoolean running = new AtomicBoolean(true);
  final AtomicInteger count = new AtomicInteger(0);
  final Flowable<Integer> obs = Flowable.unsafeCreate(new Publisher<Integer>() {
  timeHasPassed.await(8000, TimeUnit.MILLISECONDS);
  running.set(false);
  finished.await();
origin: pentaho/pentaho-kettle

@Test
 public void concurrentSyslogMessageTest() throws Exception {
 SyslogMessageTask syslogMessage = null;
 ExecutorService service = Executors.newFixedThreadPool( numOfTasks );
 for ( int i = 0; i < numOfTasks; i++ ) {
  syslogMessage = createSyslogMessageTask();
  service.execute( syslogMessage );
 }
 service.shutdown();
 countDownLatch.countDown();
 service.awaitTermination( 10000, TimeUnit.NANOSECONDS );
 Assert.assertTrue( numOfErrors.get() == 0 );
}
origin: eclipse-vertx/vert.x

@Test
public void testServerConnectionHandler() throws Exception {
 AtomicInteger status = new AtomicInteger();
 AtomicReference<HttpConnection> connRef = new AtomicReference<>();
 server.connectionHandler(conn -> {
  assertEquals(0, status.getAndIncrement());
  assertNull(connRef.getAndSet(conn));
 });
 server.requestHandler(req -> {
  assertEquals(1, status.getAndIncrement());
  assertSame(connRef.get(), req.connection());
  req.response().end();
 });
 CountDownLatch listenLatch = new CountDownLatch(1);
 server.listen(onSuccess(s -> listenLatch.countDown()));
 awaitLatch(listenLatch);
 client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
  testComplete();
 });
 await();
}
origin: jankotek/mapdb

public void testStreamForEachConcurrentStressTest() throws Throwable {
  if (!impl.isConcurrent()) return;
  final Collection c = impl.emptyCollection();
  final long testDurationMillis = timeoutMillis();
  final AtomicBoolean done = new AtomicBoolean(false);
  final Object elt = impl.makeElement(1);
  final Future<?> f1, f2;
  final ExecutorService pool = Executors.newCachedThreadPool();
  try (PoolCleaner cleaner = cleaner(pool, done)) {
    final CountDownLatch threadsStarted = new CountDownLatch(2);
    Runnable checkElt = () -> {
      threadsStarted.countDown();
      while (!done.get())
        c.stream().forEach(x -> assertSame(x, elt)); };
    Runnable addRemove = () -> {
      threadsStarted.countDown();
      while (!done.get()) {
        assertTrue(c.add(elt));
        assertTrue(c.remove(elt));
      }};
    f1 = pool.submit(checkElt);
    f2 = pool.submit(addRemove);
    Thread.sleep(testDurationMillis);
  }
  assertNull(f1.get(0L, MILLISECONDS));
  assertNull(f2.get(0L, MILLISECONDS));
}
origin: apache/activemq

String threadName = Thread.currentThread().getName();
try {
  producer = session.createProducer(destination);
  producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
  producer.setTimeToLive(msgTTL);
    while (running) {
      synchronized (this) {
        paused.await();
      sentCount.incrementAndGet();
    for (sentCount.set(0); sentCount.get() < messageCount && running; sentCount.incrementAndGet()) {
      synchronized (this) {
        paused.await();
} finally {
  if (finished != null) {
    finished.countDown();
java.util.concurrentCountDownLatch

Javadoc

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The #await methods block until the current count reaches zero due to invocations of the #countDown method, after which all waiting threads are released and any subsequent invocations of #await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

A CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking #awaitwait at the gate until it is opened by a thread invoking #countDown. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an #await until all threads could pass.

Sample usage: Here is a pair of classes in which a group of worker threads use two countdown latches:

  • The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed;
  • The second is a completion signal that allows the driver to wait until all workers have completed.
  
class Driver { // ...} 
class Worker implements Runnable  
private final CountDownLatch startSignal; 
private final CountDownLatch doneSignal; 
Worker(CountDownLatch startSignal, CountDownLatch doneSignal)  
this.startSignal = startSignal; 
this.doneSignal = doneSignal; 
} 
public void run()  
try  
startSignal.await(); 
doWork(); 
doneSignal.countDown(); 
} catch (InterruptedException ex) {} // return; 
} 
void doWork() { ... } 
}}

Another typical usage would be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. When all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a CyclicBarrier.)

  
class Driver2 { // ...} 
class WorkerRunnable implements Runnable  
private final CountDownLatch doneSignal; 
private final int i; 
WorkerRunnable(CountDownLatch doneSignal, int i)  
this.doneSignal = doneSignal; 
this.i = i; 
} 
public void run()  
try  
doWork(i); 
doneSignal.countDown(); 
} catch (InterruptedException ex) {} // return; 
} 
void doWork() { ... } 
}}

Memory consistency effects: Until the count reaches zero, actions in a thread prior to calling countDown()happen-before actions following a successful return from a corresponding await() in another thread.

Most used methods

  • countDown
    Decrements the count of the latch, releasing all waiting threads if the count reaches zero.If the cu
  • await
    Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thr
  • <init>
    Constructs a CountDownLatch initialized with the given count.
  • getCount
    Returns the current count.This method is typically used for debugging and testing purposes.
  • toString
    Returns a string identifying this latch, as well as its state. The state, in brackets, includes the

Popular in Java

  • Making http requests using okhttp
  • putExtra (Intent)
  • setContentView (Activity)
  • onCreateOptionsMenu (Activity)
  • URLConnection (java.net)
    A connection to a URL for reading or writing. For HTTP connections, see HttpURLConnection for docume
  • URLEncoder (java.net)
    This class is used to encode a string using the format required by application/x-www-form-urlencoded
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • ZipFile (java.util.zip)
    This class provides random read access to a zip file. You pay more to read the zip file's central di
  • Servlet (javax.servlet)
    Defines methods that all servlets must implement. A servlet is a small Java program that runs within
  • JLabel (javax.swing)
  • Best plugins for Eclipse
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now