00:00

Problem Statement

Input/Output Examples

Visual Explanation

The workers never wait on each other. Only the threads that call await() wait, which is the difference between a latch and a barrier.

Approaches

Both approaches block the main thread until the three workers are done. The first uses the classic latch; the second uses futures.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw milliseconds; both tabs print the same output.

Complexity Analysis

The main thread waits as long as the slowest worker. The latch itself stores one counter; the futures version keeps one future per worker.

Interview Tips and Recommended Approach

  • Call countDown() in a finally block in real code, or a failing worker leaves main waiting forever.
  • Use await(timeout, unit) when waiting forever is not acceptable.
  • Compare with join(). A latch also works with thread pools, where you do not own the threads.
  • Contrast with CyclicBarrier: a latch is one-shot and others wait; a barrier is reusable and the workers wait for each other.

Recommended Approach: CountDownLatch

Why: it is purpose-built for this job, works with any kind of thread and makes the "wait for N events" intent obvious.