CountDownLatch
A counter that lets a thread wait until others have performed N actions.
Available since: Java 1.5
Syntax
public class CountDownLatch
public CountDownLatch(int count)Parameters
| Parameter | Type | Description |
|---|---|---|
| count | int | How many `countDown()` calls open the latch. |
Examples
Waiting for all services to start:
void main() throws InterruptedException {
List<String> services = List.of("db", "cache", "mail");
var ready = new CountDownLatch(services.size());
for (String s : services) {
Thread.startVirtualThread(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) { return; }
ready.countDown();
});
}
ready.await();
IO.println("All " + services.size() + " services are up, count = " + ready.getCount());
}Output:
All 3 services are up, count = 0Notes
countDown() decreases the count and await() blocks until it reaches zero. A latch is single-use and cannot be reset; for repeating barriers there are CyclicBarrier and Phaser. await(timeout, unit) waits for a limited time.
See also
- Thread.join() — Waits for a thread to finish.
- ExecutorService.close() — Closes the pool and waits for all tasks; called automatically by try-with-resources.
In the tutorial
- Synchronization — Race conditions in Java and how to avoid them — synchronized methods and blocks, atomic classes like AtomicInteger, ReentrantLock and a shared lock object.