Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 201 ยท Concurrency

CountDownLatch, CyclicBarrier, Semaphore and Phaser

Learn Java synchronizers - CountDownLatch to wait for events, CyclicBarrier for rounds, Semaphore to limit access, and Phaser for flexible multi-phase work.

Locks protect data. Synchronizers coordinate time: they make threads wait until something has happened. "Don't start until the config is loaded." "Wait until all five downloads are done." "Let at most three threads call the payment API at once." "Everyone finish round one before anyone starts round two." You could build each of these from wait/notify (Inter-Thread Communication) or a Condition (Locks and Conditions), but java.util.concurrent already has tested, readable versions.

This lesson covers the four you'll meet most: CountDownLatch, CyclicBarrier, Semaphore and Phaser, plus the rarer Exchanger. Each section shows what the tool coordinates, a small runnable demo, and the mistakes to avoid. Thread output order varies between runs, so read the explanations rather than expecting the exact same lines every time.

CountDownLatch: wait for N events

A CountDownLatch starts with a count. Any thread can call countDown() to decrease it; threads that call await() block until it reaches zero. Once at zero it stays open forever: a latch is single use.

Two classic uses:

  1. Wait for workers to finish: new CountDownLatch(n), each worker counts down when done, the coordinator awaits.
  2. Starting gate: new CountDownLatch(1), all workers await, the coordinator counts down once to release them at the same moment.
Java A starting gate and a finish line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The services report in order of boot time (cache, search, database), and the main thread wakes up after the slowest one, roughly 250 ms. Two habits in that code matter in real systems:

  • Call countDown() in a finally block. If a worker throws before counting down, the coordinator waits forever.
  • Prefer await(timeout, unit), which returns false if time runs out, over a bare await().

A latch can't be reset. If you need the same coordination again and again, use a barrier.

CyclicBarrier: meet up, then continue together

A CyclicBarrier is for a fixed group of threads that work in rounds. Each thread calls await() when it finishes its part of the round; nobody continues until all parties have arrived. Then the barrier resets automatically (that's the "cyclic" part) for the next round. An optional barrier action runs once per round, on the last thread to arrive, before anyone is released. It's the perfect place to merge the round's results.

Java Three workers, three rounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Within a round, the "finished" lines appear in random order, but a round's summary line always comes after all three of its workers and before any line from the next round. The totals are 60, 120 and 180 every time, because the barrier guarantees that the action sees every worker's write for that round. (Writes before await() happen-before the barrier action and everything after the barrier, so the plain int[] is safe here.)

If one waiting thread is interrupted or times out, the barrier is broken: every other thread waiting at it gets a BrokenBarrierException, so a group never hangs because one member died. Call reset() to repair it. Use await(timeout, unit) for the same reason you'd use it on a latch.

CountDownLatch CyclicBarrier
Who waits one or more waiters for events the participants wait for each other
Count decreased by anyone, any number of times each party's await()
Reusable no yes, automatically each round
Action on release no optional barrier action

Semaphore: limit how many at once

A Semaphore holds a number of permits. acquire() takes one, blocking if none are left; release() gives one back. With n permits, at most n threads can be inside the guarded section at once. It's the standard way to throttle access to something limited: a database that allows 10 connections, an API with a concurrency limit, or a CPU-heavy step you don't want running 50 times in parallel.

Java At most three downloads at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Ten pool threads are available, but the semaphore keeps the number of active downloads at three or fewer, so nine 100 ms downloads take about 300 ms. tryAcquire() (optionally with a timeout) grabs a permit only if one is available, which is how you implement "fail fast when overloaded" instead of queueing.

Semaphore facts worth knowing:

  • Permits aren't owned. Any thread can call release(), even one that never acquired. That makes semaphores flexible, but a stray extra release() silently raises the limit. Always pair acquire with release in try/finally.
  • new Semaphore(n, true) is fair: waiting threads get permits in arrival order. The default is faster but lets newcomers jump the queue.
  • acquire(k) and release(k) take several permits at once, useful for weighting expensive requests.
  • A semaphore with one permit works like a lock that any thread may unlock. Prefer a real lock for mutual exclusion.
  • With virtual threads, a semaphore is the right way to limit concurrency against a resource, instead of a small thread pool.

Phaser: flexible phases

A Phaser generalizes both the latch and the barrier. Threads register as parties, then work in numbered phases (0, 1, 2, ...). Its key differences from CyclicBarrier:

  • The number of parties can change: register() adds one, arriveAndDeregister() removes one.
  • A party can arrive() without waiting, or arriveAndAwaitAdvance() to wait for the others.
  • Override onAdvance(phase, registeredParties) to run code between phases; returning true terminates the phaser.
Java A Phaser where workers leave early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The "short" worker leaves after phase 0, "medium" after phase 1, and "long" after phase 2, at which point no parties remain and onAdvance returns true. The "works in" lines for one phase can come in any order, but each phase's summary line follows them. The main thread registers itself first so the phaser can't advance while workers are still being added, a common Phaser idiom.

You won't need Phaser often. Reach for it when the set of participants grows or shrinks during the computation, or when you need both "wait" and "don't wait" arrivals.

Exchanger: swap with a partner

An Exchanger<V> lets exactly two threads swap objects at a meeting point: each calls exchange(myObject) and receives the other's. The textbook use is double buffering, where a producer fills one buffer while a consumer drains the other, then they swap:

Java
Exchanger<List<String>> exchanger = new Exchanger<>();
// producer:  fullBuffer  = exchanger.exchange(fullBuffer);   // gets the empty one back
// consumer:  emptyBuffer = exchanger.exchange(emptyBuffer);  // gets the full one

In practice, a BlockingQueue (Concurrent Collections) is simpler for most producer-consumer designs.

Choosing a synchronizer

You want to... Use
wait until N tasks or events have happened, once CountDownLatch
release many threads at the same moment CountDownLatch(1) as a gate
run a fixed group in lock-step rounds CyclicBarrier
cap how many threads use a resource at once Semaphore
run phases with a changing set of participants Phaser
swap data between exactly two threads Exchanger
wait for results, not just events Future / CompletableFuture.allOf (CompletableFuture)

All of these classes are thread-safe, and actions before a release (countDown, barrier await, release, arrive) happen-before the actions of threads that pass the matching wait. You don't need extra volatile or locks to see data written before the coordination point.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A CountDownLatch is created with count 3. Four threads each call countDown() once. What happens?

    countDown never goes below zero. Once the latch reaches zero it stays open; latches cannot be reset.
  2. 2. Why should a worker call latch.countDown() inside a finally block?

    If the worker fails before counting down, the count never reaches zero and await() (without a timeout) blocks forever.
  3. 3. Five threads wait at a CyclicBarrier with 5 parties, and one of them is interrupted while waiting. What happens to the other four?

    An interrupt or timeout breaks the barrier, and every thread waiting at it gets BrokenBarrierException, so the group doesn't hang.
  4. 4. new Semaphore(2) guards a method. Ten threads call it at the same time and each holds the permit for 100 ms. About how long until all ten are done?

    Only two threads run at once, so the ten calls run in five batches of 100 ms, about 500 ms in total.
  5. 5. Which tool fits a computation where workers join and leave between phases?

    Phaser supports register() and arriveAndDeregister(), so the number of parties can change. CyclicBarrier has a fixed number of parties and a latch is single use.

Summary

  • CountDownLatch: threads await() until the count, decreased by countDown(), reaches zero; single use; count down in finally.
  • CyclicBarrier: a fixed group waits for each other each round, an optional barrier action runs between rounds, and one failed party breaks the barrier for all.
  • Semaphore: acquire/release permits to cap concurrent access; release in finally; tryAcquire fails fast; fairness is optional.
  • Phaser: phases with a dynamic set of parties, non-blocking arrive(), and onAdvance hooks.
  • Exchanger: two threads swap objects at a meeting point.
  • Always prefer timed waits in production code, and remember that output order between threads varies.

Next: Concurrent Collections, the thread-safe maps, lists and queues that make most of this coordination unnecessary.