CountDownLatch is a synchronization aid in Java that allows one or more threads to wait until a set of operations performed by other threads completes. It is part of the java.util.concurrent package and is commonly used in multithreaded programming.
Characteristics of CountDownLatch:
- Used for one-time synchronization
- Count cannot be reset
- Multiple threads can wait on the same latch
- Once count reaches zero, all waiting threads are released
Need for CountDownLatch
In many real-world applications, a thread must wait for other threads to finish their tasks before proceeding.
Example use cases:
- Starting a server only after all services are ready
- Running tests after all components are initialized
- Coordinating multiple background tasks
Working of CountDownLatch
- A CountDownLatch is created with a count value.
- Each worker thread performs its task and calls countDown().
- The waiting thread calls await() and blocks.
- When the count reaches zero, the waiting thread resumes execution.
Constructor of CountDownLatch
CountDownLatch(int count)
- count: Number of threads or events to wait for
Important Methods
Method | Description |
|---|---|
await() | Blocks the calling thread until count becomes zero |
countDown() | Decrements the count by 1 |
getCount() | Returns the current count |
Example: Using CountDownLatch in Java
This program demonstrates the use of CountDownLatch in Java to make the main thread wait until multiple worker threads complete their execution.
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
Worker w1 = new Worker(1000, latch, "WORKER-1");
Worker w2 = new Worker(2000, latch, "WORKER-2");
Worker w3 = new Worker(3000, latch, "WORKER-3");
Worker w4 = new Worker(4000, latch, "WORKER-4");
w1.start();
w2.start();
w3.start();
w4.start();
latch.await();
System.out.println(Thread.currentThread().getName() + " has finished");
}
}
class Worker extends Thread {
private int delay;
private CountDownLatch latch;
public Worker(int delay, CountDownLatch latch, String name) {
super(name);
this.delay = delay;
this.latch = latch;
}
public void run() {
try {
Thread.sleep(delay);
latch.countDown();
System.out.println(Thread.currentThread().getName() + " finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
WORKER-4 finished
main has finished
Explanation
- A CountDownLatch with count 4 is created.
- Four worker threads execute independently.
- Each worker calls countDown() after completing its task.
- The main thread waits using await().
- Once all workers finish, the main thread resumes.
CountDownLatch vs CyclicBarrier
CountDownLatch | CyclicBarrier |
|---|---|
One-time use | Reusable |
Main thread waits | All threads wait |
Count cannot be reset | Can be reset |