0
0
JavaConceptBeginner · 3 min read

What is CountDownLatch in Java: Simple Explanation and Example

CountDownLatch in Java is a synchronization aid that allows one or more threads to wait until a set of operations in other threads completes. It uses a counter that threads count down, and when it reaches zero, waiting threads proceed.
⚙️

How It Works

Imagine you have a group of friends waiting to start a game, but they want to wait until everyone arrives. CountDownLatch works like a countdown timer that starts at a number equal to the number of friends. Each friend arriving reduces the count by one. When the count reaches zero, the game starts.

In Java, CountDownLatch holds a count initialized when created. Threads call countDown() to reduce the count. Other threads call await() to wait until the count hits zero. This helps coordinate tasks that must finish before others proceed.

💻

Example

This example shows three worker threads doing some work, then calling countDown(). The main thread waits until all workers finish before printing a final message.

java
import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        Runnable worker = () -> {
            try {
                Thread.sleep((long) (Math.random() * 1000));
                System.out.println(Thread.currentThread().getName() + " finished work");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                latch.countDown();
            }
        };

        new Thread(worker, "Worker 1").start();
        new Thread(worker, "Worker 2").start();
        new Thread(worker, "Worker 3").start();

        latch.await();
        System.out.println("All workers finished. Main thread proceeds.");
    }
}
Output
Worker 2 finished work Worker 1 finished work Worker 3 finished work All workers finished. Main thread proceeds.
🎯

When to Use

Use CountDownLatch when you want one or more threads to wait for other threads to complete certain tasks before continuing. For example:

  • Waiting for multiple services to start before launching an application.
  • Waiting for several parts of a job to finish before combining results.
  • Coordinating test setup steps that must complete before tests run.

It is useful in scenarios where you have a fixed number of events or tasks to wait for.

Key Points

  • CountDownLatch uses a counter initialized once and cannot be reset.
  • Threads call countDown() to reduce the count.
  • Threads calling await() wait until the count reaches zero.
  • It helps coordinate threads to wait for others to finish.
  • For reusable countdowns, consider CyclicBarrier instead.

Key Takeaways

CountDownLatch lets threads wait until a set number of events complete.
Use countDown() to reduce the count and await() to wait for zero.
It is ideal for coordinating fixed numbers of tasks or threads.
Once the count reaches zero, waiting threads continue immediately.
It cannot be reset after reaching zero; use CyclicBarrier for reusable waits.