CountDownLatch Class

Definition

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

[Android.Runtime.Register("java/util/concurrent/CountDownLatch", DoNotGenerateAcw=true)]
public class CountDownLatch : Java.Lang.Object
[<Android.Runtime.Register("java/util/concurrent/CountDownLatch", DoNotGenerateAcw=true)>]
type CountDownLatch = class
    inherit Object
Inheritance
CountDownLatch
Attributes

Remarks

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 <em>count</em>. The #await 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 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 #await await wait at the gate until it is opened by a thread invoking #countDown. A CountDownLatch initialized to <em>N</em> can be used to make one thread wait until <em>N</em> 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 await until all threads could pass.

<b>Sample usage:</b> Here is a pair of classes in which a group of worker threads use two countdown latches: <ul> <li>The first is a start signal that prevents any worker from proceeding until the driver is ready for them to proceed; <li>The second is a completion signal that allows the driver to wait until all workers have completed. </ul>

{@code
            class Driver { // ...
              void main() throws InterruptedException {
                CountDownLatch startSignal = new CountDownLatch(1);
                CountDownLatch doneSignal = new CountDownLatch(N);

                for (int i = 0; i < N; ++i) // create and start threads
                  new Thread(new Worker(startSignal, doneSignal)).start();

                doSomethingElse();            // don't let run yet
                startSignal.countDown();      // let all threads proceed
                doSomethingElse();
                doneSignal.await();           // wait for all to finish
              }
            }

            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.)

{@code
            class Driver2 { // ...
              void main() throws InterruptedException {
                CountDownLatch doneSignal = new CountDownLatch(N);
                Executor e = ...;

                for (int i = 0; i < N; ++i) // create and start threads
                  e.execute(new WorkerRunnable(doneSignal, i));

                doneSignal.await();           // wait for all to finish
              }
            }

            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() {
                doWork();
                doneSignal.countDown();
              }

              void doWork() { ... }
            }}

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

Added in 1.5.

Java documentation for java.util.concurrent.CountDownLatch.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

CountDownLatch(Int32)

Constructs a CountDownLatch initialized with the given count.

CountDownLatch(IntPtr, JniHandleOwnership)

A constructor used when creating managed representations of JNI objects; called by the runtime.

Properties

Class

Returns the runtime class of this Object.

(Inherited from Object)
Count

Returns the current count.

Handle

The handle to the underlying Android instance.

(Inherited from Object)
JniIdentityHashCode (Inherited from Object)
JniPeerMembers
PeerReference (Inherited from Object)
ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

ThresholdType

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Await()

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted.

Await(Int64, TimeUnit)

Causes the current thread to wait until the latch has counted down to zero, unless the thread is Thread#interrupt interrupted, or the specified waiting time elapses.

AwaitAsync()
AwaitAsync(Int64, TimeUnit)
Clone()

Creates and returns a copy of this object.

(Inherited from Object)
CountDown()

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Dispose() (Inherited from Object)
Dispose(Boolean) (Inherited from Object)
Equals(Object)

Indicates whether some other object is "equal to" this one.

(Inherited from Object)
GetHashCode()

Returns a hash code value for the object.

(Inherited from Object)
JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object)
Notify()

Wakes up a single thread that is waiting on this object's monitor.

(Inherited from Object)
NotifyAll()

Wakes up all threads that are waiting on this object's monitor.

(Inherited from Object)
SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object)
ToArray<T>() (Inherited from Object)
ToString()

Returns a string representation of the object.

(Inherited from Object)
UnregisterFromRuntime() (Inherited from Object)
Wait()

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>.

(Inherited from Object)
Wait(Int64)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)
Wait(Int64, Int32)

Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

JavaCast<TResult>(IJavaObject)

Performs an Android runtime-checked type conversion.

JavaCast<TResult>(IJavaObject)
GetJniTypeName(IJavaPeerable)

Applies to