CountDownLatch
A CountDownLatch starts at a count. Threads call countDown when they finish a step. Other threads call await and park until the count reaches zero. The latch cannot be reset.
Detailed Explanation
You want to start a race only after all workers are ready, or wait until all workers finish. A latch is that gate. new CountDownLatch(n) has n permits to burn. Each countDown subtracts one. await returns when the count is 0. Extra countDown calls on a zero latch do nothing. There is no countUp.
Because it cannot be reused, the lifecycle is one-shot. If you need a reusable barrier ("everyone finished phase i, start phase i+1"), use CyclicBarrier or Phaser. If you need to collect results, use Future or CompletableFuture.allOf.
await is interruptible. await(timeout, unit) returns false on timeout; the count may still be positive. Always check the return value. A thread that forgets to countDown in finally leaves waiters parked forever.
Typical uses: a main thread launches n tasks and awaits completion; n workers await a start latch that main countDowns once; tests wait for an async callback. The happens-before guarantee is that actions before countDown are visible to threads that return from await.
You reach for a latch when the number of events is known and the waiters only need a signal, not a value. You reach for a Semaphore when you want a reusable permit pool. You reach for join when you have the Thread objects and no pool.
The cost of a wrong initial count is a latch that opens too early or never. The cost of using a latch as a lock is a missing API (no ownership). The cost of a huge timeout-less await on a test is a hung CI. Prefer timed await in tests.
Code Examples
import java.util.concurrent.CountDownLatch;
public class StartLine {
public static void main(String[] args) throws InterruptedException {
CountDownLatch ready = new CountDownLatch(1);
Thread worker = new Thread(() -> {
try {
ready.await();
System.out.println("go");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
worker.start();
ready.countDown();
worker.join();
// prints: go
}
}import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AllDone {
public static void main(String[] args) throws InterruptedException {
int n = 3;
CountDownLatch done = new CountDownLatch(n);
ExecutorService pool = Executors.newFixedThreadPool(n);
for (int i = 0; i < n; i++) {
pool.execute(done::countDown);
}
done.await();
System.out.println(done.getCount()); // prints: 0
pool.shutdown();
}
}Common Gotchas
Forgetting `countDown` in `finally` hangs `await`
treat it like a lock release.
A latch is one-shot
creating a new one is the reset.
Timed `await` returns false on timeout
ignoring the boolean looks like success.