Countdown Latch from Scratch

Medium
ConcurrencySemaphoreCountDownLatchBarrierThread CoordinationAQS

Problem Statement

Implement CountDownLatch from scratch — a synchronization primitive that allows one or more threads to wait until a set of operations being performed in other threads complete.

The latch is initialized with a count N. Threads that must wait call await(). Other threads call countDown() to decrement the count. When the count reaches zero, all waiting threads are released.

class MyCountDownLatch {
    public MyCountDownLatch(int count) {}
    // Blocks until count reaches zero (or thread is interrupted)
    public void await() throws InterruptedException {}
    // Blocks with timeout — returns false if timed out before count=0
    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {}
    // Decrements count; releases all waiters when count reaches 0
    public void countDown() {}
    public long getCount() {}
}

Key Entities

  • AtomicInteger count: Decremented by countDown(), checked by await().
  • ReentrantLock + Condition: Waiting threads sleep on the condition; last countDown() signals all.
  • Volatile flag released: Set when count hits 0; fast-path check in await().

Requirements

  1. await() blocks until count reaches exactly zero.
  2. countDown() on a latch already at zero has no effect.
  3. Multiple threads can await() simultaneously — all released when count hits 0.
  4. await(timeout, unit) returns true if released in time, false if timed out.
  5. Once released, subsequent calls to await() return immediately.

Asked at: Amazon, Google, Microsoft, Adobe, Oracle, Uber

!Constraints

- 1 ≤ initial count ≤ 10,000 - Any number of threads may call await() simultaneously. - countDown() may be called from different threads. - The latch is not reusable (unlike CyclicBarrier) — once released, it stays released. - Thread interruption during await() must propagate InterruptedException.
Output

Run or submit your code to see output here.