Syntax
new CountDownLatch(count); latch.countDown(); latch.await()Examples
CountDownLatch Coordination
Save as Main.java and run with a Java 17+ JDK: java Main.java.
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws Exception {
CountDownLatch done = new CountDownLatch(1);
int[] result = new int[1];
Thread worker = new Thread(() -> {
try { result[0] = 42; }
finally { done.countDown(); }
});
worker.start();
done.await();
System.out.println(result[0]);
worker.join();
}
}- Expected output: 42
- Actions before countDown become visible after the matching successful await. The finally block releases the waiter if the worker body fails.
Best practices
- Prefer timed waits where an indefinite wait would be unacceptable.
- Use a separate mechanism to report worker failures; countDown alone does not convey success.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification