CountDownLatch
Code IndexAdd Codota to your IDE (free)

Best code snippets using java.util.concurrent.CountDownLatch(Showing top 20 results out of 12,249)

Refine search

  • AtomicInteger
  • AtomicBoolean
  • AtomicReference
  • ExecutorService
  • Executors
  • Ignite
  • Session
  • BrokerService
  • Common ways to obtain CountDownLatch
private void myMethod () {
CountDownLatch c =
  • new CountDownLatch(count)
  • List list;new CountDownLatch(list.size())
  • AtomicReference atomicReference;atomicReference.get()
  • Smart code suggestions by Codota
}
origin: square/retrofit

 @Override public void onFailure(Call<T> call, Throwable t) {
  failureRef.set(t);
  latch.countDown();
 }
});
origin: square/okhttp

 /** Visible for testing. */
 void setListBytes(byte[] publicSuffixListBytes, byte[] publicSuffixExceptionListBytes) {
  this.publicSuffixListBytes = publicSuffixListBytes;
  this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes;
  listRead.set(true);
  readCompleteLatch.countDown();
 }
}
origin: google/guava

 @Override
 public void run() {
  try {
   cacheRef.get().getUnchecked(3);
  } finally {
   doneSignal.countDown();
  }
 }
};
origin: google/guava

 @Override
 public T load(T key) throws InterruptedException {
  if (shouldWait.get()) {
   delayLatch.await();
  }
  return key;
 }
}
origin: google/guava

 @Override
 public void run() {
  try {
   okayToRun.await();
  } catch (InterruptedException e) {
   Thread.currentThread().interrupt();
   throw new RuntimeException(e);
  }
  runCalled.getAndIncrement();
 }
},
origin: commons-io/commons-io

  @Override
  public void run() {
    started.countDown();
    FileUtils.waitFor(new File(""), 2);
    wasInterrupted.set( Thread.currentThread().isInterrupted());
  }
};
origin: druid-io/druid

 @Override
 public void run()
 {
  try {
   start.await();
  }
  catch (InterruptedException e) {
   throw Throwables.propagate(e);
  }
  final Random rndGen = new Random();
  while (!done.get()) {
   Integer idx = rndGen.nextInt(queryableIndex.get() + 1);
   Assert.assertEquals(idx, concurrentIndexible.get(idx));
  }
 }
}
origin: google/guava

@GwtIncompatible // threads
public void testSubmitAsync_asyncCallable_cancelledBeforeApplyingFunction()
  throws InterruptedException {
 final AtomicBoolean callableCalled = new AtomicBoolean();
 AsyncCallable<Integer> callable =
   new AsyncCallable<Integer>() {
    @Override
    public ListenableFuture<Integer> call() {
     callableCalled.set(true);
     return immediateFuture(1);
    }
   };
 ExecutorService executor = newSingleThreadExecutor();
 // Pause the executor.
 final CountDownLatch beforeFunction = new CountDownLatch(1);
 executor.execute(
   new Runnable() {
    @Override
    public void run() {
     awaitUninterruptibly(beforeFunction);
    }
   });
 ListenableFuture<Integer> future = submitAsync(callable, executor);
 future.cancel(false);
 // Unpause the executor.
 beforeFunction.countDown();
 executor.shutdown();
 assertTrue(executor.awaitTermination(5, SECONDS));
 assertFalse(callableCalled.get());
}
origin: eclipse/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: google/guava

 @Override
 public String load(String key) throws InterruptedException {
  callCount.incrementAndGet();
  startSignal.await();
  throw e;
 }
});
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: openzipkin/zipkin

 @Test(timeout = 1000L)
 public void get_memoizes() throws InterruptedException {
  int getCount = 1000;

  AtomicInteger value = new AtomicInteger();

  Lazy<Integer> lazyInt = new Lazy<Integer>() {
   final AtomicInteger val = new AtomicInteger();

   @Override protected Integer compute() {
    return val.incrementAndGet();
   }
  };

  CountDownLatch latch = new CountDownLatch(getCount);
  Executor exec = Executors.newFixedThreadPool(10);
  for (int i = 0; i < getCount; i++) {
   exec.execute(() -> {
    // if lazy computes multiple times, the result of lazyInt.get() > 1
    value.getAndAdd(lazyInt.get());
    latch.countDown();
   });
  }
  latch.await();

  assertThat(value.get()).isEqualTo(getCount);
 }
}
origin: neo4j/neo4j

@Test
public void tryToReproduceTheIssue() throws Exception
{
  // GIVEN
  GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
  CountDownLatch startSignal = new CountDownLatch( 1 );
  AtomicBoolean stopSignal = new AtomicBoolean();
  AtomicReference<Exception> failure = new AtomicReference<>();
  Node parentNode = createNode( db );
  Collection<Worker> workers = createWorkers( db, startSignal, stopSignal, failure, parentNode );
  // WHEN
  startSignal.countDown();
  sleep( 500 );
  stopSignal.set( true );
  awaitWorkersToEnd( workers );
  // THEN
  if ( failure.get() != null )
  {
    throw new Exception( "A worker failed", failure.get() );
  }
}
origin: google/guava

 @Override
 public void run() {
  cache.getUnchecked(s);
  computedCount.incrementAndGet();
  tasksFinished.countDown();
 }
});
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: eclipse/vert.x

@Test
public void testHttpClientConnectionCloseAfterRequestEnd() throws Exception {
 CountDownLatch started = new CountDownLatch(1);
 client = vertx.createHttpClient();
 AtomicReference<EndpointMetric> endpointMetrics = new AtomicReference<>();
 server = vertx.createHttpServer().requestHandler(req -> {
  endpointMetrics.set(((FakeHttpClientMetrics)FakeHttpClientMetrics.getMetrics(client)).endpoint("localhost:8080"));
  req.response().end();
 }).listen(8080, "localhost", ar -> {
  assertTrue(ar.succeeded());
  started.countDown();
 });
 awaitLatch(started);
 CountDownLatch closed = new CountDownLatch(1);
 HttpClientRequest req = client.get(8080, "localhost", "/somepath");
 req.handler(resp -> {
   HttpConnection conn = req.connection();
   conn.closeHandler(v2 -> {
    closed.countDown();
   });
   conn.close();
 req.end();
 awaitLatch(closed);
 EndpointMetric val = endpointMetrics.get();
 assertWaitUntil(() -> val.connectionCount.get() == 0);
 assertEquals(0, val.queueSize.get());
 assertEquals(0, val.requests.get());
origin: google/guava

 @Override
 public Integer call() throws Exception {
  enterLatch.countDown();
  try {
   new CountDownLatch(1).await(); // wait forever
   throw new AssertionError();
  } catch (InterruptedException e) {
   interruptedExceptionThrown.set(true);
   throw e;
  } finally {
  }
 }
});
origin: druid-io/druid

 startLatch.await();
 stopLatch.countDown();
 return;
   final float indexedVal = indexed2.get(j);
   if (Floats.compare(val, indexedVal) != 0) {
    failureHappened.set(true);
    reason.set(StringUtils.format("Thread2[%d]: %f != %f", j, val, indexedVal));
    stopLatch.countDown();
    return;
 reason.set(e.getMessage());
 failureHappened.set(true);
stopLatch.countDown();
origin: eclipse/vert.x

 countMap.put(msg.body().getString("deploymentID"), msg.body().getInteger("count"));
});
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> deploymentID1 = new AtomicReference<>();
AtomicReference<String> deploymentID2 = new AtomicReference<>();
  setIsolationGroup(group1).setIsolatedClasses(isolatedClasses), ar -> {
  assertTrue(ar.succeeded());
  deploymentID1.set(ar.result());
  assertEquals(0, TestVerticle.instanceCount.get());
  vertx.deployVerticle(verticleID,
   new DeploymentOptions().setIsolationGroup(group2).setIsolatedClasses(isolatedClasses), ar2 -> {
   assertTrue(ar2.succeeded());
   deploymentID2.set(ar2.result());
   assertEquals(0, TestVerticle.instanceCount.get());
   latch.countDown();
  });
 });
 assertEquals(count1, countMap.get(deploymentID1.get()).intValue());
 assertEquals(count2, countMap.get(deploymentID2.get()).intValue());
 assertTrue(expectedSuccess);
origin: eclipse/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();
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 classes and methods

  • addToBackStack (FragmentTransaction)
  • setRequestProperty (URLConnection)
    Sets the value of the specified request header field. The value will only be used by the current URL
  • notifyDataSetChanged (ArrayAdapter)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • KeyStore (java.security)
    KeyStore is responsible for maintaining cryptographic keys and their owners. The type of the syste
  • ResultSet (java.sql)
    A table of data representing a database result set, which is usually generated by executing a statem
  • HashMap (java.util)
    HashMap is an implementation of Map. All optional operations are supported.All elements are permitte
  • BlockingQueue (java.util.concurrent)
    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu

For IntelliJ IDEA,
Android Studio or Eclipse

  • Codota IntelliJ IDEA pluginCodota Android Studio pluginCode IndexSign in
  • EnterpriseFAQAboutContact Us
  • Terms of usePrivacy policyCodeboxFind Usages
Add Codota to your IDE (free)