Quiz: Java Synchronizers: CountDownLatch, CyclicBarrier, Semaphore

Total: 8 questions

1. 

What are synchronizers in Java, and which ones are there?

Synchronizers are classes from the java.util.concurrent package that coordinate threads. There are five of them:

  • CountDownLatch (Java 5) - wait for N events; single-use;
  • CyclicBarrier (Java 5) - gather N threads at one point; reusable;
  • Phaser (Java 7) - a barrier with phases and a changing number of parties;
  • Semaphore (Java 5) - let no more than N threads access a resource at once;
  • Exchanger (Java 5) - swap objects between two threads.

All of this can be built on wait()/notify(), but synchronizers spare you monitor mistakes and spurious wakeups, so new code uses them. To pass data from producers to consumers you need a BlockingQueue, not a synchronizer.

The waiting methods of synchronizers (await(), acquire(), exchange()) throw InterruptedException when interrupted. The exceptions are Semaphore.acquireUninterruptibly() and Phaser.arriveAndAwaitAdvance()/awaitAdvance(): they ignore interruption. With CyclicBarrier, interrupting one party breaks the barrier for everyone.

2. 

How does CountDownLatch work, and why is countDown() called in finally?

CountDownLatch is a latch with a counter. It is created with a number N, threads call countDown(), and threads in await() wait until the count reaches zero. The count tracks events, not threads: one thread may call countDown() several times.

  • await(timeout, unit) returns true if the count reached zero and false if the time ran out;
  • getCount() is the current value, for logs and tests only;
  • countDown() at zero does nothing, and new CountDownLatch(-1) throws IllegalArgumentException.

The latch is single-use: the count cannot be reset, and await() on an open latch returns immediately.

countDown() goes in finally: if a task fails before the call, the count never reaches zero, and await() without a timeout waits forever. Report failures separately - the latch does not care how a task ended.

Two common patterns: "wait for N tasks" (a service starts after its components are initialized) and the "starting gun" - a latch of 1 holds N threads until the controlling thread calls countDown(). Actions before countDown() are visible to a thread after await(). Unlike join(), a latch waits for a moment rather than for a thread to finish, and it works with a pool.

3. 

How does CyclicBarrier work: barrierAction, generations, BrokenBarrierException and reset()?

CyclicBarrier is a barrier for N parties. Each thread calls await() and waits until all N reach the meeting point. When the last one arrives, the barrier trips, everyone continues, and the barrier is ready for the next round - a new generation.

The barrierAction from the constructor runs in the last arriving thread, before the others leave await(). It is a good place to combine the results of a phase; heavy work does not belong there because every party waits for it.

await() returns the arrival index: getParties() - 1 for the first thread, 0 for the last.

The barrier is all-or-nothing. If a party is interrupted, its await(timeout) times out, reset() is called, or barrierAction throws, the barrier breaks. The thread that caused it gets its own exception (InterruptedException, TimeoutException), the rest get BrokenBarrierException. A broken barrier throws BrokenBarrierException on every new await() until reset() is called; the Javadoc suggests creating a new barrier after a break instead.

4. 

What is the difference between CountDownLatch and CyclicBarrier?

In short: a latch waits for events, a barrier waits for threads.

  • Who waits. With CountDownLatch, some threads wait in await() while others count down via countDown() without blocking. With CyclicBarrier, the parties themselves both count and wait: await() marks the arrival and waits for the rest.
  • Reuse. A latch is single-use; a barrier is ready for a new round automatically.
  • Action. A latch has none; a barrier has barrierAction, run by the last arriving thread.
  • If someone never arrives. Threads waiting on a latch hang until the await(timeout) expires, or forever. A barrier breaks, and the others get BrokenBarrierException.
  • Number of threads. A latch is not tied to N: one thread may wait for 1,000 events. A barrier has exactly N parties per round.

Typical uses: a latch for starting after initialization, the "starting gun", waiting for N responses; a barrier for iterative computations and simulations with a shared step. If the number of parties changes during the work, you need a Phaser.

5. 

How do you limit the number of concurrent accesses to a resource with a Semaphore?

A Semaphore holds a count of permits: acquire() takes a permit or waits, release() returns it. A semaphore with N permits lets no more than N threads at a time access a resource - this is how you cap database connections, calls to an external API, or parallel downloads.

permits.acquire();          // before try: not acquired - not returned
try {
    download(file);
} finally {
    permits.release();      // always return it
}

acquire() goes before try: if a thread is interrupted while waiting and release() sits in finally, you end up with more permits than you started with.

new Semaphore(n, true) is a fair semaphore: permits are handed out in queue order (FIFO). The Javadoc recommends fair semaphores for resource access. Only the no-argument tryAcquire() jumps the queue; tryAcquire(0, TimeUnit.SECONDS) honors it.

A semaphore limits the number of concurrent operations, not their rate. A newFixedThreadPool(n) limits threads and everything they do, while a semaphore limits access to one specific resource. With virtual threads, a semaphore is the standard way to limit concurrency: they are not pooled, and a virtual thread waiting in acquire() is parked and does not occupy a carrier thread (JEP 444).

6. 

What does "a Semaphore has no owner" mean, and how is a binary semaphore different from a mutex?

A semaphore does not remember which thread took a permit - it is just a counter. So a release() without a prior acquire() silently raises the number of permits above the initial value: new Semaphore(1) after an extra release() lets in two threads. There is no exception; with a ReentrantLock the same mistake would throw IllegalMonitorStateException.

A typical source of an extra release() is acquire() inside try with release() in finally: a thread interrupted while waiting never got a permit but returns one anyway.

A binary semaphore (new Semaphore(1)) gives mutual exclusion, but it is not a mutex:

  • no owner - any thread can return the permit;
  • not reentrant - a second acquire() by the same thread waits for itself forever;
  • no wait conditions (newCondition()).

For a critical section use ReentrantLock or synchronized; use a semaphore when you actually need a permit counter.

7. 

What is a Phaser, and when is it better than CyclicBarrier and CountDownLatch?

Phaser (Java 7) is a reusable barrier whose number of parties can change while it runs. Phases are numbered from zero; getPhase() returns the current one.

  • register() - add a party on the fly;
  • arriveAndAwaitAdvance() - arrive and wait for the rest; arrive() - arrive without waiting;
  • arriveAndDeregister() - arrive and leave;
  • awaitAdvance(phase) - wait for a phase to end without being a party.

Instead of a barrierAction, you override onAdvance(phase, registeredParties): the last arriving party calls it. If it returns true, the phaser terminates; by default that happens when no parties are left.

arriveAndAwaitAdvance() and awaitAdvance() ignore interrupt(); the interruptible wait is awaitAdvanceInterruptibly().

How to choose: the number of parties is known and there is one phase - CountDownLatch; the number is known and there are many phases - CyclicBarrier (simpler API); parties come and go - Phaser. A single phaser supports at most 65,535 parties; beyond that register() throws IllegalStateException, and for more parties phasers are combined into a tree.

8. 

What is an Exchanger, and what is it used for?

Exchanger<V> (Java 5) is a meeting point for two threads. Each calls exchange(x), waits for its partner, and receives the object the other one passed.

buffer = exchanger.exchange(buffer);   // hand over the full one, get an empty one

The classic scenario is double buffering: one thread fills a buffer, the other empties one, and they swap buffers without creating new ones. exchange() guarantees visibility, so the buffers themselves can be plain ArrayLists: while a list is with one thread, the other does not touch it.

If the partner may never come, use exchange(x, timeout, unit), which throws TimeoutException when the time runs out. Interrupting a waiting thread gives InterruptedException.

An Exchanger works strictly in pairs. When there is more than one producer or consumer, use a BlockingQueue.

Page 1 of 1