CKTIS / Java
Java CountDownLatch: constructor, await, and countDown
Use a one-shot counter to open a start gate or wait for a fixed number of signals. Learn both await overloads, how interruption works, and when writes become visible across threads.
Version: Java SE 21
Syntax
Java SE 21 — java.util.concurrent.CountDownLatch
public CountDownLatch(int count)
public void await() throws InterruptedException
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
public void countDown()In Java SE 21, java.util.concurrent.CountDownLatch is a one-shot synchronizer. The CountDownLatch(int) constructor sets the number of signals, not the number of threads: one thread can report several events. A count of 0 starts open; a negative count throws IllegalArgumentException. CountDownLatch.countDown subtracts one from a positive count without waiting for other signals. The transition to zero releases every waiter without determining the order in which they resume. At zero, further countDown() calls do nothing. The latch cannot be reset; use a new instance for another round.
CountDownLatch.await has two overloads. await() returns void and waits without a time limit if the count is positive. await(long timeout, TimeUnit unit) returns true if the count is or becomes zero, or false if the timeout expires before that happens. A nonpositive timeout checks without waiting. Both overloads throw InterruptedException and clear the interrupt status if it is set on entry or the thread is interrupted while waiting. Otherwise, at zero they return immediately.
The CountDownLatch.await/countDown pairing gives a visibility guarantee. Actions before a countDown() that reduces the count happen-before actions in another thread after it returns successfully from await() or gets true from timed await on the same latch. A false timeout result gives no such guarantee. The latch does not provide mutual exclusion.
Use a separate latch for each condition. start = 1 opens a shared start gate; done = 3 collects three completion signals. For two groups, set immediateReady = 2 and deferredReady = 4; each participant signals its own group's readiness once, and the first group cannot proceed until the coordinator opens a separate releaseImmediate = 1 gate. When both readiness latches reach zero, you know without Thread.sleep that the first group has made at least two readiness reports and the second at least four, but not that the threads are already blocked. With one report per participant, the totals are guaranteed to be exactly two and four only if the group sizes are independently fixed at two and four, respectively. To coordinate holding a resource, use two latches of 1: one confirms acquisition, the other signals that the holder may release it.
A missing signal can leave a thread waiting indefinitely. If you count attempts that have ended, including failures, call countDown() in finally and report failures separately. Zero confirms that the required signals arrived, not that the work succeeded.
Examples
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class LatchDemo {
public static void main(String[] args) throws InterruptedException {
int[] results = new int[3];
int[] input = new int[1];
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(3);
for (int i = 0; i < results.length; i++) {
int slot = i;
new Thread(() -> {
try {
start.await();
results[slot] = input[0] + slot;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
}).start();
}
System.out.println("Start open: " + start.await(0, TimeUnit.SECONDS));
input[0] = 10;
start.countDown();
done.await();
System.out.println("Results: " + Arrays.toString(results));
done.countDown();
System.out.println("Done open: " + done.await(0, TimeUnit.SECONDS));
}
}Result
Start open: false Results: [10, 11, 12] Done open: true
Only `main` prints. It first checks the closed gate, then writes `10` and opens `start`. Each worker writes to its own array slot. After `done.await()`, those writes are visible to `main`; the extra `done.countDown()` does not close the gate.
Related lessons
- Java · Lesson 34 · Advanced · Version: 2
- Java · Lesson 36 · Advanced · Version: 2
- Java · Lesson 58 · Intermediate · Version: 2