Codectionary / Developer documentation / Java

CountDownLatch Coordination

CountDownLatch lets one thread wait until a fixed number of completion signals arrive. Once opened, a latch remains open and cannot be reset. Save as Main.java and run with a Java 17+ JDK: java Main.java.

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();
  }
}
  1. Expected output: 42
  2. 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

Specifications & further reading