Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CountDownLatch — one-shot waiting for signals

CountDownLatch coordinates threads: await() waits until countDown() calls reduce the count to zero. It supports waiting for a group of operations and guarantees visibility of earlier writes.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new CountDownLatch(count)
void await() throws InterruptedException
boolean await(long timeout, TimeUnit unit) throws InterruptedException
void countDown()

CountDownLatch in java.util.concurrent lets threads wait for a fixed number of signals. The count represents countDown() calls, not necessarily distinct threads. The latch is one-shot: it cannot be reset.

CountDownLatch.countDown decrements a positive count without waiting; at zero it does nothing. CountDownLatch.await waits for zero. The await(timeout, unit) overload returns false on timeout or true when zero is reached. Interruption throws InterruptedException and clears interrupt status; propagate the exception or handle it deliberately.

Writes preceding the signals that bring the count to zero happen-before actions after successful waiting in another thread. Therefore, the example reads results only after done.await().

Signaling in finally prevents exceptions from skipping the signal, but does not imply task success. Missing required signals can block an untimed wait indefinitely; a timeout does not cancel workers.

Examples

import java.util.concurrent.CountDownLatch;

public class LatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch done = new CountDownLatch(2);
        int[] results = new int[2];

        for (int i = 0; i < results.length; i++) {
            final int index = i;
            new Thread(() -> {
                try {
                    results[index] = (index + 1) * 10;
                } finally {
                    done.countDown();
                }
            }).start();
        }

        done.await();
        System.out.println(results[0] + results[1]);
    }
}

Result

30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources