Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

CountDownLatch

A counter that lets a thread wait until others have performed N actions.

Available since: Java 1.5

Syntax

public class CountDownLatch
public CountDownLatch(int count)

Parameters

ParameterTypeDescription
countintHow many `countDown()` calls open the latch.

Examples

Waiting for all services to start:

void main() throws InterruptedException {
    List<String> services = List.of("db", "cache", "mail");
    var ready = new CountDownLatch(services.size());
    for (String s : services) {
        Thread.startVirtualThread(() -> {
            try { Thread.sleep(100); } catch (InterruptedException e) { return; }
            ready.countDown();
        });
    }
    ready.await();
    IO.println("All " + services.size() + " services are up, count = " + ready.getCount());
}

Output:

All 3 services are up, count = 0

Notes

countDown() decreases the count and await() blocks until it reaches zero. A latch is single-use and cannot be reset; for repeating barriers there are CyclicBarrier and Phaser. await(timeout, unit) waits for a limited time.

See also

In the tutorial

  • Synchronization — Race conditions in Java and how to avoid them — synchronized methods and blocks, atomic classes like AtomicInteger, ReentrantLock and a shared lock object.

Thanks for reading!

Donate to the site — we work hard for you.