CountDownLatch
suggest changeA synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
- A
CountDownLatchis 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.
Key Methods:
public void await() throws InterruptedException
Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.
public void countDown()
Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
Example:
import java.util.concurrent.*;
class DoSomethingInAThread implements Runnable {
CountDownLatch latch;
public DoSomethingInAThread(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
System.out.println("Do something");
latch.countDown();
} catch(Exception err) {
err.printStackTrace();
}
}
}
public class CountDownLatchDemo {
public static void main(String[] args) {
try {
int numberOfThreads = args.length == 0 ? 5 : Integer.parseInt(args[0]);
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int n = 0; n < numberOfThreads; n++) {
Thread t = new Thread(new DoSomethingInAThread(latch));
t.start();
}
latch.await();
System.out.println("In Main thread after completion of " + numberOfThreads + " threads");
} catch(Exception err) {
err.printStackTrace();
}
}
}
Do something
Do something
Do something
Do something
Do something
In Main thread after completion of 5 threads
Explanation:
CountDownLatchis initialized with a count of 5 in the main thread.- The main thread waits by calling
await(). - Five instances of
DoSomethingInAThreadare created. Each instance decrements the count withcountDown(). - Once the count reaches zero, the main thread resumes.
If run() throws before countDown(), await() does not return. The printed lines can appear in any order.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents