Barrier Synchronization

Medium
ConcurrencyCyclicBarrierCountDownLatchBarrierSemaphoreThread Coordination

Problem Statement

Implement a reusable cyclic barrier from scratch. A barrier allows N threads to synchronize at a meeting point. No thread proceeds past the barrier until all N threads have arrived. Once all N threads arrive, the barrier is released and optionally a barrier action is executed. The barrier is cyclic — it resets automatically for the next round.

class MyCyclicBarrier {
    public MyCyclicBarrier(int parties) {}
    public MyCyclicBarrier(int parties, Runnable barrierAction) {}
    // Blocks until all parties have invoked await()
    // Returns the arrival index (0 = last to arrive)
    public int await() throws InterruptedException, BrokenBarrierException {}
    public void reset() {}   // Force-reset (breaks waiting threads)
    public int getNumberWaiting() {}
    public boolean isBroken() {}
}

Key Entities

  • parties: Total number of threads that must arrive before releasing.
  • count: Atomic counter of threads that have reached the barrier.
  • ReentrantLock + Condition: Threads wait on the condition; last thread signals all.
  • generation: Each round has a generation object to detect broken barriers.

Requirements

  1. All N threads must arrive before any is released.
  2. The barrier resets automatically for the next round (cyclic).
  3. If a thread is interrupted while waiting, the barrier is broken — all waiting threads throw BrokenBarrierException.
  4. The optional barrierAction runs exactly once per barrier trip (executed by the last arriving thread).

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

!Constraints

- 1 ≤ parties ≤ 1000 - Barrier must be reusable across multiple rounds without manual reset. - Thread interruption must propagate BrokenBarrierException to all waiting threads. - barrierAction (if provided) must complete before other threads are released.
Output

Run or submit your code to see output here.