Java SE API

CountDownLatch.countDown()

Decrease the count if positive and release waiters when it reaches zero.

Formal Syntax & Structure

java syntaxjava
void countDown()

Working Example

Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main {    // Only finite tasks and timed coordination are used in these examples.    static void finish(Thread thread) throws InterruptedException {        try {            if (!thread.join(Duration.ofSeconds(3))) {                thread.interrupt();                if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop");                throw new AssertionError("worker timed out");            }        } catch (InterruptedException e) {            thread.interrupt();            throw e;        }    }    static void await(CountDownLatch latch) {        try {            if (!latch.await(3, TimeUnit.SECONDS)) throw new AssertionError("latch timed out");        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new AssertionError("unexpected cancellation", e);        }    }    static class Box { int value; }    public static void main(String[] args) throws Exception {        Box box = new Box();        CountDownLatch available = new CountDownLatch(1);        Thread writer = new Thread(() -> { box.value = 17; available.countDown(); });        writer.start();        try { await(available); System.out.println(box.value); }        finally { finish(writer); }    }}
Java Reference