Java Concurrency Interview

Synchronizers: latches, barriers, semaphores question 49 of 180 senior

What is a Phaser and when does it beat a CyclicBarrier?

CyclicBarrier fixes the party count at construction. Phaser lets threads register() and arriveAndDeregister() as the computation proceeds, which fits work that spawns or retires participants between rounds: a simulation where entities appear and die, or a pipeline whose stages drain one by one.

It also numbers its phases, so arriveAndAwaitAdvance() returns the phase you just completed and awaitAdvance(phase) lets a thread wait for a specific round without being a party to it. Overriding onAdvance(phase, parties) gives you the barrier action plus the ability to terminate the phaser by returning true.

The honest caveat: most code that reaches for a Phaser does not need one, and the API is easy to get wrong. Say that. Fixed parties and a fixed number of rounds are a CyclicBarrier, and one-shot is a latch.

synchronizers phaser

Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction