What is a CountDownLatch and why is it one-shot? — Cracked Java
// Concurrency & Multithreading · Synchronizers: Latch, Barrier, Semaphore, Phaser
MidTheoryCodingEPAM

What is a CountDownLatch and why is it one-shot?

A CountDownLatch is a one-shot gate initialized with a count: threads call await() to block until the count reaches zero, which other threads drive with countDown(). It is one-shot because the count only ever decreases and there is no API to reset it — once it hits zero it stays open forever.

How it works

You construct it with a fixed count. await() blocks (interruptibly, optionally with a timeout) while the count is greater than zero. Each countDown() decrements the count by one; when it reaches zero, all waiting threads are released at once and any later await() returns immediately. getCount() lets you peek at the remaining count.

Internally it is an AQS whose shared state is the count. countDown() does a CAS-decrement; reaching zero releases the AQS shared lock, waking every queued waiter. There is deliberately no operation to increment the state back up — that is the structural reason it cannot be reused.

Two canonical uses

Start gate — hold N worker threads at the line, then drop the flag so they all begin together. Completion gate — the main thread waits for N workers to finish.

int workers = 3;
CountDownLatch ready = new CountDownLatch(workers); // completion gate
ExecutorService pool = Executors.newFixedThreadPool(workers);

for (int i = 0; i < workers; i++) {
    pool.submit(() -> {
        try {
            doWork();
        } finally {
            ready.countDown(); // ALWAYS in finally
        }
    });
}

ready.await();            // blocks until all 3 finish
System.out.println("all workers done");
pool.shutdown();

Why one-shot matters

Because it cannot reset, a latch is the wrong tool for a loop where the same threads rendezvous each iteration — that is what CyclicBarrier or Phaser are for. Treat a latch as a single event: "the service is initialized," "all tasks completed."

Mark your status