Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

In code review guidance for your teams, how would you describe when to use each of CountDownLatch, CyclicBarrier, Semaphore, Phaser and Exchanger, and which ones should prompt extra scrutiny?

In review guidance, I would describe CountDownLatch as wait once for N events, Semaphore as limit how many things run at once, and CyclicBarrier as fixed groups of threads in repeated phases, mostly in batch or compute code. Phaser and Exchanger are rarely needed in service code and should come with a written reason. Most service code needs futures, executors or virtual threads rather than raw synchronizers, and every use must have timeouts on its waits and release() or countDown() in a finally block.

Why this question is asked

Raw synchronizers are small classes with large consequences. A CountDownLatch without a timeout can hang a service at startup; a Semaphore released in the wrong place can silently raise a limit; a CyclicBarrier can lose hours of batch work. Reviewers who do not use these classes often cannot spot those problems, so a short, shared description of when each one fits is worth more than a long concurrency guide. Interviewers ask this to see whether we can turn our own knowledge into guidance that works for a whole organisation. In this answer, we will go through each synchronizer as a reviewer should see it, explain why higher-level tools usually come first, and end with the two rules every use must follow and a review checklist.

1Start With the Question a Reviewer Should Ask

The most useful first question in a review is not is this synchronizer used correctly, but does this code need a synchronizer at all. In service code, most coordination is one of two shapes: run some calls in parallel and combine their results, or limit how many calls run at once. The first shape is solved by futures and executors: CompletableFuture, ExecutorService.invokeAll(), or with virtual threads, one thread per task joined with Future.get(). The second is solved by a Semaphore or a bulkhead library. Hand-built waiting with latches and barriers is rarely the clearest way to express either.

So the guidance opens with a short rule: prefer futures, executors and virtual threads; reach for a raw synchronizer when they do not express the problem, and say which one and why.

2CountDownLatch and Semaphore: The Two Common Ones

CountDownLatch means wait once for N events. Good uses are a test that waits for three asynchronous callbacks, or a component that waits for a fixed set of initialisations to finish. It is one-shot, so a reviewer should question any code that creates new latches in a loop to fake reuse. When the events are results of tasks we submitted ourselves, a list of futures is usually clearer, because futures also carry the failure.

Semaphore means limit concurrency: at most N calls to the fragile service, at most N files open at once. Its permits are not owned by threads, so any thread can release, and the semaphore never checks. That is what makes the two classic bugs possible: releasing a permit that was never acquired, which silently raises the limit, and missing a release on an exception path, which leaks permits until the limit is zero. A reviewer should look at exactly where acquire() and release() sit relative to the try block.

3CyclicBarrier: Fixed Groups in Repeated Phases

CyclicBarrier is for a fixed number of threads that work in steps and must all finish step n before any starts step n + 1, such as a simulation over a grid or a parallel batch transform. It belongs mostly in batch or compute code, not in request handling. In a review, the questions are about failure: what happens when one party throws, which breaks the barrier and releases every other party with BrokenBarrierException, whether the original cause is recorded, and whether work is checkpointed so a failure does not lose the whole run. A barrier in a web request path is a strong signal that the design should be revisited.

4Phaser and Exchanger: Ask for a Reason

Phaser supports a changing number of parties and many phases, and Exchanger lets exactly two threads swap objects. Both are correct, well-implemented tools, and both are rarely needed in service code. Phaser fits dynamic task trees and phased computations whose membership changes; Exchanger fits double buffering between two threads. Because few reviewers know their details, such as arriveAndAwaitAdvance() not being interruptible, or the arbitrary pairing when more than two threads use an Exchanger, I would ask that any use come with a short comment explaining why a simpler tool did not fit. That is not a ban; it is a way to make sure the choice was deliberate and that the next reader can follow it.

Synchronizers in review
ClassUse it forReview level
CountDownLatchwait once for N eventsnormal: check timeout and countDown in finally
Semaphorelimit concurrency to Nnormal: check acquire before try, release in finally
CyclicBarrierfixed group, repeated phases (batch, compute)extra: failure handling and checkpoints
Phaserchanging parties, many phasesextra: needs a written reason
Exchangertwo threads swapping buffersextra: needs a written reason
Futures, executors, virtual threadsparallel calls and combining resultspreferred default in service code

5The Two Rules Every Use Must Follow

Whatever class is used, two rules are non-negotiable in the guidance. First, every wait has a timeout: await(timeout, unit), tryAcquire(timeout, unit), awaitAdvanceInterruptibly(phase, timeout, unit), exchange(x, timeout, unit). An unbounded wait turns any bug or outage elsewhere into a hang, and hangs are the hardest failures to diagnose. Second, the signal that releases others is always in a finally block: countDown(), release(), arriveAndDeregister(). Otherwise an exception skips the signal and the waiters never wake up.

Java
// What the guidance asks for, in one place
if (!permits.tryAcquire(200, TimeUnit.MILLISECONDS)) throw new Busy(); // bounded wait
try {
callDownstream();
} finally {
permits.release(); // signal in finally
}
if (!ready.await(30, TimeUnit.SECONDS)) { // bounded wait, explicit decision
throw new IllegalStateException("dependencies not ready after 30s");
}

Notice that a timeout always comes with a decision: what the code does when it fires. A reviewer should check that the false or TimeoutException branch does something meaningful, such as failing with a clear message or using a fallback, and does not simply loop back into another wait.

6Turning the Guidance Into a Review Habit

Guidance only works if reviewers can apply it quickly. I would put a short checklist in the team's review template and back it with static analysis where possible: rules that flag await() and acquire() without timeouts, and countDown() or release() outside finally blocks, catch most problems automatically. The decision flow below is the whole checklist in one picture.

Step throughReviewing a use of a synchronizer
  1. Would futures, an executor or virtual threads express this?parallel calls, combining results
    YesAsk for that insteadNoContinue
  2. Is it a latch, semaphore or barrier for its intended use?
    YesContinueNoAsk for a written reason (Phaser, Exchanger)
  3. Does every wait have a timeout and a decision?
    YesContinueNoRequest a bounded wait
  4. Is every countDown, release or deregister in finally?
    YesApproveNoRequest the fix

4 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Why not ban Phaser and Exchanger outright?

Because they solve real problems better than anything else when the problem fits, such as a crawler whose task tree grows while it runs. A ban pushes people to rebuild them badly with latches and counters. Asking for a reason keeps them available while making sure they are chosen deliberately.

Are virtual threads a replacement for synchronizers?

Not for all of them. Virtual threads make it cheap to block, so code can use simple blocking calls and futures instead of complicated asynchronous coordination. But they remove the old implicit limit of a thread pool, so Semaphore becomes more important, not less.

How strict should the timeout rule be in tests?

Just as strict. A test that waits on a latch without a timeout hangs the build instead of failing, and the failure message is lost. await(5, TimeUnit.SECONDS) with an assertion on the result gives a clear failure.

8Conclusion

In this answer, we built review guidance around one question first: does this code need a raw synchronizer at all, since futures, executors and virtual threads cover most service code. Then CountDownLatch is for waiting once for N events, Semaphore for limiting concurrency, and CyclicBarrier for fixed groups in repeated phases, mostly in batch and compute code. Phaser and Exchanger are rarely needed in services and should come with a reason. Every use follows two rules: waits have timeouts with a clear decision, and countDown, release and deregister calls live in finally blocks.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd make the guidance short enough that every reviewer can apply it. The first question is whether the code needs a raw synchronizer at all, because most service code is either parallel calls whose results you combine, which is futures, executors or virtual threads, or limiting concurrency, which is a semaphore or a bulkhead.

Then, if they want more

Then one line per class. CountDownLatch is wait once for N events; it's one-shot, and if the events are your own tasks, futures are usually clearer because they carry the failure. Semaphore is limit concurrency to N; check that acquire is before the try and release is in finally, because permits aren't owned and the bugs are silent.

CyclicBarrier is a fixed group of threads in repeated phases, mostly batch or compute code, and the review is about failure handling and checkpoints. Phaser and Exchanger are rarely needed in services, so I'd ask for a short written reason. That's not a ban, just proof the choice was deliberate.

And two rules apply to all of them: every wait has a timeout with a real decision when it fires, and every countDown, release or arriveAndDeregister sits in a finally block. Where possible I'd back those two rules with static analysis so reviewers don't have to catch them by eye.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In code review guidance for your teams, how would you describe when to use each of...": https://scrivio-interview-library.netlify.app/java/synchronizers/3238f8ecae/