Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-27

Java Synchronizers: CountDownLatch, CyclicBarrier, Semaphore

Java synchronizers are classes from the java.util.concurrent package that coordinate threads: wait until N events have happened (CountDownLatch), gather N threads at one point before moving on (CyclicBarrier, Phaser), let no more than N threads at a time access a resource (Semaphore), or swap data between two threads (Exchanger). You could build all of this by hand on wait()/notify(), but synchronizers already solve these tasks without monitor mistakes and spurious wakeups, so new code uses them (see modern alternatives to wait/notify).

CountDownLatch ready = new CountDownLatch(3);   // wait for three events
Semaphore permits = new Semaphore(3);           // at most three threads at once
CyclicBarrier barrier = new CyclicBarrier(3);   // three threads meet at one point

Mistakes with synchronizers rarely end in an exception. Create new Semaphore(1), call acquire() inside try and release() in finally, then interrupt the thread while it waits for a permit. After that, availablePermits() returns 2: a semaphore meant for one thread now lets in two, and not a single log line tells you so. The reason is explained in A Semaphore Has No Owner.

Which Synchronizers Java Has

There are five synchronizers in java.util.concurrent: CountDownLatch, CyclicBarrier, Semaphore and Exchanger arrived in Java 5, Phaser in Java 7. They differ in what a thread waits for: events from other threads, other parties at a meeting point, a free permit, or a partner to swap with.

Class Task Reusable? Who waits / who counts Analogy
CountDownLatch Wait for N events No: once the count reaches zero, the latch stays open for good Threads wait in await(); other threads count via countDown() A safe that opens after three turns of the key
CyclicBarrier Gather N threads at one point Yes: after it trips, the barrier is ready for the next round The same threads: await() both marks arrival and waits Hikers wait for stragglers at a rest stop, then walk on together
Phaser Like a barrier, but with phases and a changing number of parties Yes, phases are numbered Parties register (register()), arrive (arrive…()) and leave on the fly A guided tour that people join and leave along the way
Semaphore At most N threads at once Yes Threads wait in acquire(); release() from any thread returns a permit A car park with N spaces and a gate
Exchanger Swap objects in a pair Yes Both threads wait for each other in exchange() Two people meet and swap parcels

If the job is passing data from producers to consumers, you need a BlockingQueue, not a synchronizer (see BlockingQueue). If you need mutual exclusion with an owner, use ReentrantLock or synchronized.

CountDownLatch: Waiting for N Events

CountDownLatch in Java is a latch with a counter: you create it with a number N, threads call countDown() to decrease the count by one, and threads in await() wait until it reaches zero. At that point all waiting threads continue, and any new await() returns immediately. The latch is single-use: there is no method that resets the count back to N.

Method What it does Edge cases
new CountDownLatch(int count) Creates a latch with the given count count < 0 → IllegalArgumentException; with 0 the latch is open right away
void countDown() Decreases the count; when it hits zero, wakes all waiting threads At a count of 0 it does nothing — no exception, no negative values. Never blocks
void await() Waits until the count is 0 InterruptedException if interrupted; returns immediately if the count is already 0
boolean await(long timeout, TimeUnit unit) Waits no longer than the timeout true — the count reached zero, false — time ran out and the count isn’t 0 yet
long getCount() The current count For logs and tests; don’t base decisions on it — the value may change right after the call

The count tracks events, not threads. One thread can call countDown() three times, or three different threads can call it once each — for the latch it’s the same thing. Example: a service starts only when three components are ready — configuration, database and cache. The cache fails during initialization.

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ServiceStartup {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch ready = new CountDownLatch(3);
        Queue<String> failed = new ConcurrentLinkedQueue<>();

        startComponent("config", 100, false, ready, failed);
        startComponent("database", 300, false, ready, failed);
        startComponent("cache", 200, true, ready, failed);

        System.out.println("main waits, getCount() = " + ready.getCount());
        boolean allArrived = ready.await(2, TimeUnit.SECONDS);   // at most 2 s
        System.out.println("all arrived: " + allArrived + ", getCount() = " + ready.getCount());
        if (failed.isEmpty()) {
            System.out.println("Service started");
        } else {
            System.out.println("Service not started, errors: " + failed);
        }
    }

    static void startComponent(String name, long millis, boolean fail,
                               CountDownLatch ready, Queue<String> failed) {
        new Thread(() -> {
            try {
                Thread.sleep(millis);                            // "initialization"
                if (fail) {
                    throw new IllegalStateException("no connection");
                }
                System.out.println(name + " ready");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                failed.add(name);
            } catch (RuntimeException e) {
                System.out.println(name + ": " + e.getMessage());
                failed.add(name);
            } finally {
                ready.countDown();                               // no matter what
            }
        }, name).start();
    }
}
main waits, getCount() = 3
config ready
cache: no connection
database ready
all arrived: true, getCount() = 0
Service not started, errors: [cache]

The order of lines is set by the component delays (100, 200 and 300 ms), so the output is the same on every run. The key line in this code is countDown() in finally. Move it to the end of the try block, and the failed cache never calls its countDown(): await(2, SECONDS) returns false with getCount() = 1, and a plain await() without a timeout hangs main forever. The latch doesn’t care whether a task succeeded, so failures have to be reported separately — here through the failed queue.

The latch itself provides the visibility guarantee: everything a thread did before countDown() is visible to a thread that returned from await(). That’s why main reads failed without extra synchronization (the happens-before rule is covered in volatile in Java). The queue is still thread-safe, because the components write to it concurrently.

The second common pattern is the “starting gun”: a latch with a count of 1 holds N threads at the start line until the controlling thread says “go”. Tests use it to launch threads as close to simultaneously as possible and reproduce a race. It’s usually paired with a latch of N for the finish line — the example in the CountDownLatch Javadoc is built the same way:

CountDownLatch startSignal = new CountDownLatch(1);   // one shot
CountDownLatch doneSignal = new CountDownLatch(n);    // n tasks finished

for (int i = 0; i < n; i++) {
    new Thread(() -> {
        try {
            startSignal.await();          // everyone waits at the start line
            doWork();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            doneSignal.countDown();
        }
    }).start();
}
prepare();                 // setup while the threads wait
startSignal.countDown();   // the shot: all n threads start at once
doneSignal.await();        // wait until all of them finish

The deadlock lesson uses a similar trick: a latch makes both threads take their first monitor before reaching for the second, so the deadlock reproduces on every run (Java deadlock example).

CountDownLatch, join() and invokeAll()

There are three ways to wait for other threads to finish their work, and the choice depends on what exactly you’re waiting for: a specific thread to terminate, N events, or a set of tasks in a pool.

Approach What it waits for Works with a thread pool Task results and exceptions
thread.join() A specific thread to terminate No: a pool thread doesn’t terminate after a task No, pass them yourself
CountDownLatch.await() N calls to countDown() from any threads Yes, with both pools and plain threads No, pass them yourself; the event may also happen in the middle of a task
ExecutorService.invokeAll() All tasks in the list to complete Pool only Yes: List<Future>, exceptions via get()

For one or two of your own threads, join() is simpler (join() instead of polling isAlive()); for a set of tasks with results, use invokeAll() (invokeAll() and invokeAny()). CountDownLatch is for when you wait not for termination but for a moment: “component initialized”, “connection established”, “first batch of data loaded” — after which the thread keeps working.

CyclicBarrier: A Meeting Point for Threads

CyclicBarrier in Java is a barrier for N parties: each thread that reaches the meeting point calls await() and waits until all N have arrived. When the last one arrives, the barrier trips, all threads continue, and the barrier is ready for the next round — hence “cyclic”. An optional barrierAction passed to the constructor runs once per trip.

The action isn’t run by a separate thread but by the last thread to arrive, and it runs before the others leave await(). That makes barrierAction a good place to combine the results of a phase: every party has already written its part, and no one has started the next phase yet. Each trip starts a new generation of the barrier.

Method What it does Edge cases
new CyclicBarrier(int parties, Runnable barrierAction) A barrier for parties threads; the action may be null parties < 1 → IllegalArgumentException
int await() Mark arrival and wait for the rest InterruptedException, BrokenBarrierException; returns the arrival index
int await(long timeout, TimeUnit unit) The same with a timeout Time runs out → TimeoutException, and the barrier breaks for everyone
void reset() Returns the barrier to its initial state Threads waiting at that moment get BrokenBarrierException
isBroken(), getNumberWaiting(), getParties() Whether the barrier is broken, how many wait, how many parties For diagnostics and tests

Example: a three-phase calculation in three threads. Each thread computes its part of a phase, and barrierAction adds the parts together and prints which thread it ran in. The phase durations are chosen so that a different thread arrives last each time.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class PhasedCalculation {
    static final int WORKERS = 3;
    static final int PHASES = 3;
    static final int[] partial = new int[WORKERS];   // each thread's part of the result
    static int phase = 0;                            // changed only by barrierAction

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(WORKERS, () -> {
            int sum = 0;
            for (int value : partial) {
                sum += value;
            }
            System.out.println("phase " + phase + ": sum = " + sum
                    + ", barrierAction runs in " + Thread.currentThread().getName());
            phase++;
        });

        Thread[] threads = new Thread[WORKERS];
        for (int i = 0; i < WORKERS; i++) {
            int id = i + 1;
            threads[i] = new Thread(() -> {
                try {
                    for (int p = 0; p < PHASES; p++) {
                        Thread.sleep(((id + p) % 3 + 1) * 60L);   // 60, 120 or 180 ms
                        partial[id - 1] = id * (p + 1);           // this thread's part
                        barrier.await();                          // wait for the others
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } catch (BrokenBarrierException e) {
                    System.out.println(Thread.currentThread().getName() + ": barrier broken");
                }
            }, "worker-" + id);
            threads[i].start();
        }
        for (Thread t : threads) {
            t.join();
        }
        System.out.println("isBroken = " + barrier.isBroken()
                + ", getNumberWaiting = " + barrier.getNumberWaiting());
    }
}
phase 0: sum = 6, barrierAction runs in worker-2
phase 1: sum = 12, barrierAction runs in worker-1
phase 2: sum = 18, barrierAction runs in worker-3
isBroken = false, getNumberWaiting = 0

In phase 0 the slowest thread (180 ms) is worker-2, in phase 1 it’s worker-1, in phase 2 worker-3 — and each time that is exactly the thread that runs the action. The durations differ by 60 ms, enough to keep the output stable from run to run. The same barrier object worked three times in a row without being recreated.

The partial array and the phase field aren’t volatile, and that’s correct. The CyclicBarrier Javadoc guarantees a happens-before chain: a thread’s actions before await() → barrierAction → the threads’ actions after they return from await(). The practical consequence: a slow barrierAction holds every party until it finishes, so don’t put heavy work in it.

BrokenBarrierException and reset()

BrokenBarrierException is thrown to the parties when the barrier is broken: one of the waiting threads was interrupted or timed out, the barrier was reset with reset(), or barrierAction threw an exception. The barrier works on an all-or-nothing basis: if one party never arrives, the others don’t get stuck forever — they leave with an exception.

The thread that caused the break gets its own exception: an interrupted thread gets InterruptedException, a thread whose timeout expired gets TimeoutException, and if barrierAction failed, its exception is thrown from await() in the last arriving thread. Everyone else gets BrokenBarrierException. Example: a barrier for three, only two show up, and one of them waits with a timeout.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BrokenBarrierDemo {
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(3);   // the third party never comes

        Thread patient = new Thread(() -> {
            try {
                barrier.await();
                System.out.println("patient: passed the barrier");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (BrokenBarrierException e) {
                System.out.println("patient: BrokenBarrierException");
            }
        }, "patient");

        Thread impatient = new Thread(() -> {
            try {
                barrier.await(300, TimeUnit.MILLISECONDS);
            } catch (TimeoutException e) {
                System.out.println("impatient: TimeoutException");
            } catch (InterruptedException | BrokenBarrierException e) {
                System.out.println("impatient: " + e.getClass().getSimpleName());
            }
        }, "impatient");

        patient.start();
        impatient.start();
        patient.join();
        impatient.join();

        System.out.println("isBroken = " + barrier.isBroken());
        barrier.reset();
        System.out.println("after reset(): isBroken = " + barrier.isBroken());
    }
}
impatient: TimeoutException
patient: BrokenBarrierException
isBroken = true
after reset(): isBroken = false

After 300 ms impatient stops waiting and breaks the barrier, and patient, who was ready to wait indefinitely, immediately gets BrokenBarrierException. The first two lines may swap places — both threads wake up almost at the same time; the remaining lines are stable.

A broken barrier doesn’t recover on its own: every subsequent await() throws BrokenBarrierException right away until someone calls reset(). The Javadoc advises creating a new barrier if you need to carry on after a break, rather than resetting in the middle of work: reset() while threads are waiting breaks the barrier for them, and with several threads it’s easy to lose track of which generation each one is waiting on.

CountDownLatch vs CyclicBarrier

The main difference between CountDownLatch and CyclicBarrier is who waits. With CountDownLatch, some threads wait while others count, and the count never resets. With CyclicBarrier, the same threads both count and wait, waiting for each other, and after it trips the barrier is ready for a new round.

Criterion CountDownLatch CyclicBarrier
Who waits Any threads in await(), usually not the ones counting The parties themselves: each waits for all the others
Who decreases the count Any threads via countDown(), without blocking; one thread may call it several times Each party once per round, by calling await()
Reuse No Yes, automatically after each trip
Action on trip None barrierAction, run by the last thread to arrive
If a party never arrives Waiting threads hang until the await(timeout) expires If one party is interrupted or times out, the barrier breaks and the others get BrokenBarrierException
Number of threads Unrelated to N: one thread may wait for 1,000 events Exactly N party threads per round
Typical use Start after initialization, the “starting gun”, waiting for N responses Iterative computations, simulations, parallel phases with a shared step

A short rule for interviews: “a latch waits for events, a barrier waits for threads”. If the number of parties changes as the work goes on, neither fits — that’s what Phaser is for.

Semaphore: At Most N Threads at Once

A Semaphore in Java holds a count of permits: acquire() takes a permit or waits if none are free, and release() gives one back. A semaphore with N permits lets no more than N threads access a resource at the same time. That’s how you cap the number of database connections, concurrent calls to an external API, or parallel downloads.

Method If no permits are free Details
acquire() / acquire(int n) Waits InterruptedException if interrupted; acquire(n) takes n permits at once, not one by one
acquireUninterruptibly() Waits, ignores interruption The interrupt flag stays set after it returns
boolean tryAcquire() Returns false immediately Grabs a free permit ahead of the queue, even on a fair semaphore
boolean tryAcquire(long timeout, TimeUnit unit) Waits up to the timeout, then false InterruptedException; respects fairness
release() / release(int n) — Simply increases the count; there’s no check that this thread ever took a permit
availablePermits(), drainPermits() — How many are free; take all free permits at once (returns how many)

Example: ten files, but no more than three may download at once. Each download runs in its own virtual thread, and the semaphore enforces the limit. The active counter shows how many downloads are running right now, and maxActive records the peak.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class DownloadLimiter {
    private static final Semaphore permits = new Semaphore(3);
    private static final AtomicInteger active = new AtomicInteger();
    private static final AtomicInteger maxActive = new AtomicInteger();

    public static void main(String[] args) {
        long start = System.nanoTime();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 1; i <= 10; i++) {
                int fileId = i;
                executor.submit(() -> download(fileId));
            }
        }                                                   // close() waits for all 10 tasks
        long millis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("max at once: " + maxActive.get());
        System.out.println("free permits: " + permits.availablePermits());
        System.out.println("time: " + millis + " ms");
    }

    static void download(int fileId) {
        try {
            permits.acquire();                              // before try: not acquired - nothing to return
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        try {
            int now = active.incrementAndGet();
            maxActive.accumulateAndGet(now, Math::max);
            Thread.sleep(200);                              // "downloading" the file
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            active.decrementAndGet();
            permits.release();                              // always give it back
        }
    }
}
max at once: 3
free permits: 3
time: 817 ms

The first two lines are identical on every run. The time varies, but it’s never below 800 ms: ten 200 ms downloads with three at a time make four “waves”. Remove the semaphore, and the maximum becomes 10 and the time about 200 ms, because all downloads start at once. That’s exactly what makes a semaphore valuable: it caps the load on an external resource without touching the number of threads.

The order of acquire() and try is deliberate: a permit is returned only after it has been obtained. What happens with the other order is shown in the next section.

The second constructor parameter is fairness: new Semaphore(3, true) hands out permits in queue order (FIFO). By default a semaphore is unfair: a released permit can be grabbed by a thread that has just arrived. That’s faster, but a waiting thread can in theory starve. The Javadoc recommends making semaphores that control access to a resource fair. Only the no-argument tryAcquire() breaks fairness, while tryAcquire(0, TimeUnit.SECONDS) respects it — the same rule as for ReentrantLock (see fair locks).

A Semaphore Has No Owner: release() Without acquire()

A Semaphore doesn’t know which thread took a permit: it’s just a counter. Any thread can return a permit, and release() without a preceding acquire() silently raises the number of permits above the initial value. The Javadoc says so directly: a thread that releases a permit is not required to have acquired it by calling acquire().

What does this program print? The semaphore is created with one permit, main takes it, and worker waits in acquire() inside try and gets interrupted.

import java.util.concurrent.Semaphore;

public class ReleaseWithoutAcquire {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        semaphore.acquire();                         // the only permit is taken

        Thread worker = new Thread(() -> {
            try {
                semaphore.acquire();                 // waits for a permit...
                System.out.println("worker: working");
            } catch (InterruptedException e) {
                System.out.println("worker: interrupted, no permit acquired");
            } finally {
                semaphore.release();                 // ...but releases one anyway
            }
        }, "worker");
        worker.start();
        Thread.sleep(100);
        worker.interrupt();
        worker.join();

        semaphore.release();                         // main returns its own
        System.out.println("availablePermits = " + semaphore.availablePermits());
    }
}
worker: interrupted, no permit acquired
availablePermits = 2

There was one permit, and now there are two. worker never got a permit, but finally called release() anyway, and the semaphore accepted the “extra” permit without complaint. In production code every such interruption (for example, on a pool’s shutdownNow()) raises the limit by one more. The fix is the same order as in DownloadLimiter: acquire() before try, and only the work and release() in try/finally. With a ReentrantLock the same mistake would fail immediately with IllegalMonitorStateException.

Having no owner is not only a source of bugs but also an opportunity. A permit can be taken in one thread and returned in another: for example, taken when an asynchronous request is sent and returned in a callback that runs on the HTTP client’s thread. The Javadoc mentions one more use of a binary semaphore — deadlock recovery: the “lock” can be released by a thread other than the one that took it.

A semaphore with one permit is called a binary semaphore. It provides mutual exclusion like a mutex, but it isn’t a one-to-one replacement for a lock:

Criterion new Semaphore(1) ReentrantLock
Owner None Yes — the thread that called lock()
Release from another thread Allowed Not allowed: IllegalMonitorStateException
Release without acquiring The number of permits grows IllegalMonitorStateException
Re-acquiring by the same thread The thread waits for itself forever Allowed, the hold count grows
Wait conditions None newCondition()
More than one thread at a time Yes, with N > 1 permits No (except the read lock of a ReadWriteLock)

The fourth row is a frequent cause of hangs when a synchronized method is converted to a semaphore: a method under the semaphore calls another method under the same semaphore, and the thread blocks itself for good. If you need a critical section, take a lock; use a semaphore when you specifically need a counter or a release from another thread (there’s a question about this in the ReentrantLock lesson FAQ).

Phaser: Phases and a Changing Number of Parties

A Phaser (Java 7) is a reusable barrier whose number of parties can change while it runs. A party registers with register(), marks each phase with arriveAndAwaitAdvance() (arrive and wait for the others) or arrive() (arrive without waiting), and leaves with arriveAndDeregister(). Phases are numbered from zero; getPhase() returns the current one.

Instead of a barrierAction, a phaser lets you override onAdvance(phase, registeredParties): the last arriving party calls it when moving to the next phase. If it returns true, the phaser terminates. By default it returns true when no parties are left.

Example: main coordinates three worker threads that work for a different number of phases: worker-1 for one, worker-2 for two, worker-3 for three. Parties register on the fly and leave when they’re done.

import java.util.concurrent.Phaser;

public class PhaserExample {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(1) {                      // 1 - main itself
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("phase " + phase + " complete, registered parties: " + registeredParties);
                return registeredParties == 0;               // same as the default
            }
        };

        for (int i = 1; i <= 3; i++) {
            int phasesToWork = i;
            phaser.register();                               // a new party on the fly
            new Thread(() -> {
                for (int p = 1; p < phasesToWork; p++) {
                    phaser.arriveAndAwaitAdvance();          // finished a phase, waits for the rest
                }
                phaser.arriveAndDeregister();                // last phase - and leaves
            }, "worker-" + i).start();
        }

        phaser.arriveAndAwaitAdvance();                      // main in phase 0
        phaser.arriveAndAwaitAdvance();                      // main in phase 1
        int last = phaser.arriveAndDeregister();             // main leaves in phase 2
        phaser.awaitAdvance(last);                           // but waits for it to end
        System.out.println("isTerminated = " + phaser.isTerminated());
    }
}
phase 0 complete, registered parties: 3
phase 1 complete, registered parties: 2
phase 2 complete, registered parties: 0
isTerminated = true

The output is deterministic: only onAdvance() prints, and phases go strictly one after another. Phase 0 had four parties (main and three threads); worker-1 left, leaving three. In phase 1 worker-2 left, in phase 2 worker-3 and main. With zero parties left, onAdvance returned true and the phaser terminated. The last two lines of main show a useful technique: awaitAdvance(phase) lets you wait for a phase to end without being a party — after leaving via arriveAndDeregister(), main no longer holds phase 2 but still waits until worker-3 completes it.

Which one to choose. The number of parties is known up front and there’s a single phase — CountDownLatch. The number is known and there are many phases — CyclicBarrier, whose API is simpler. Parties come and go as the work progresses (recursive tasks, tree traversal, stages with a different number of workers) — Phaser. A single phaser supports at most 65,535 parties; beyond that register() throws IllegalStateException. For more, phasers are combined into a tree via the Phaser(Phaser parent) constructor.

Exchanger: Swapping Data Between Two Threads

An Exchanger (Java 5) is a meeting point for two threads: each calls exchange(x), waits for its partner and receives the object the other thread passed in. The classic scenario from the Javadoc is double buffering: one thread fills a buffer, the other drains one, and they swap buffers without allocating new ones.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangerExample {
    public static void main(String[] args) throws InterruptedException {
        Exchanger<List<Integer>> exchanger = new Exchanger<>();

        Thread filler = new Thread(() -> {
            List<Integer> buffer = new ArrayList<>();
            try {
                for (int round = 1; round <= 2; round++) {
                    for (int i = 0; i < 3; i++) {
                        buffer.add(round * 10 + i);
                    }
                    buffer = exchanger.exchange(buffer);   // hand over the full one, get an empty one
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "filler");

        Thread emptier = new Thread(() -> {
            List<Integer> buffer = new ArrayList<>();
            try {
                for (int round = 1; round <= 2; round++) {
                    buffer = exchanger.exchange(buffer);   // hand over the empty one, get a full one
                    System.out.println("received buffer: " + buffer);
                    buffer.clear();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "emptier");

        filler.start();
        emptier.start();
        filler.join();
        emptier.join();
    }
}
received buffer: [10, 11, 12]
received buffer: [20, 21, 22]

The two lists keep circulating between the threads, and neither thread touches a list while the other one has it. exchange() gives the same visibility guarantee as the other synchronizers, so plain ArrayLists are fine. There’s an exchange(x, timeout, unit) overload that throws TimeoutException if the partner doesn’t show up. An Exchanger works strictly in pairs; with more than one producer or consumer, use a BlockingQueue.

How Synchronizers React to Interruption

Almost all waiting methods of the synchronizers are interruptible: await(), acquire(), exchange() and their timed variants throw InterruptedException and clear the interrupt flag. The exceptions are Semaphore.acquireUninterruptibly() and waiting for a phase in Phaser: arriveAndAwaitAdvance() and awaitAdvance() don’t respond to interrupt().

Where the thread waits What interrupt() does What happens to the other parties
CountDownLatch.await(), await(timeout) InterruptedException Nothing: the count doesn’t change, others keep waiting
CyclicBarrier.await(), await(timeout) InterruptedException The barrier breaks, all waiting threads get BrokenBarrierException
Semaphore.acquire(), tryAcquire(timeout) InterruptedException, no permit granted Nothing
Semaphore.acquireUninterruptibly() Nothing: keeps waiting, the flag is still true after it gets a permit Nothing
Phaser.arriveAndAwaitAdvance(), awaitAdvance() Nothing: waits for the phase to end Nothing
Phaser.awaitAdvanceInterruptibly() InterruptedException The phase isn’t broken: the thread already marked its arrival via arrive()
Exchanger.exchange() InterruptedException A partner arriving later waits for another partner

The Phaser row is easy to miss: a thread stuck in arriveAndAwaitAdvance() can’t be pulled out by interrupt() or by the pool’s shutdownNow(). If the wait must be cancellable, call phaser.awaitAdvanceInterruptibly(phaser.arrive()) or its timed variant. CyclicBarrier is the opposite: interrupting one party affects everyone, and that’s handy — stopping any thread won’t leave the rest hanging. How to handle InterruptedException and which other JDK methods respond to interruption is covered in Thread Interruption in Java.

Common Mistakes with Synchronizers

Most synchronizer bugs end not in an exception but in a wait that never finishes or a limit that quietly stops working. Three things are behind most of them: countDown() or release() outside finally, a miscounted number of parties, and trying to reuse a single-use latch.

Mistake What happens How to fix it
countDown() not in finally A task fails, the count never reaches zero, await() waits forever countDown() in finally; wait with await(timeout)
Reusing a CountDownLatch The second await() returns immediately: the count is already 0 A new latch for each round, or CyclicBarrier/Phaser
Latch count larger than the number of events Waits forever, e.g. new CountDownLatch(tasks.size()) while one task gets filtered out Compute N where the tasks are launched; await(timeout)
A CyclicBarrier for 3 parties in newFixedThreadPool(2) Two pool threads wait in await(), the third task sits in the queue and never starts At least as many pool threads as barrier parties, or virtual threads
acquire() inside try, release() in finally On interruption, release() runs without acquire() — the permits multiply acquire() before try (example)
release() forgotten on one of the branches Permits “leak”; after a while every thread is stuck in acquire() try/finally right after acquire()
The same thread calling acquire() twice on Semaphore(1) The thread waits for itself: a semaphore isn’t reentrant For a critical section, use ReentrantLock
Empty catch (BrokenBarrierException e) {} in a loop The thread goes to the next round with a broken barrier and gets the exception again right away Exit the loop or create a new barrier
A slow or failing barrierAction All parties wait while it runs; an exception in it breaks the barrier Keep the action short, do heavy work after the barrier

A stuck synchronizer is easy to spot in a thread dump: jstack shows threads in WAITING (parking) with CountDownLatch.await, CyclicBarrier.await or Semaphore.acquire in the stack. The deadlock detector ThreadMXBean.findDeadlockedThreads() doesn’t find such hangs: latches and semaphores have no owner, so there’s no “thread A waits for thread B” cycle (how real deadlocks are found is shown in How to Detect a Deadlock).

Synchronizers and Virtual Threads

Synchronizers from java.util.concurrent wait via LockSupport.park(), so a virtual thread waiting in await() or acquire() is unmounted from its carrier thread and doesn’t occupy it. Thousands of virtual threads at one barrier or semaphore hold only a handful of OS threads. A waiting thread is in the WAITING or TIMED_WAITING state, not BLOCKED (the difference is explained in BLOCKED vs WAITING).

With virtual threads, Semaphore is the standard way to limit concurrency. With platform threads, the load on a database or an external service was capped by the pool size: a pool of 10 threads means at most 10 requests. Virtual threads aren’t pooled — you create one per task — and JEP 444 explicitly recommends a semaphore for limiting concurrent access to a resource. DownloadLimiter above works exactly this way: ten virtual threads, seven of them parked in acquire() without holding carriers, and only three talking to the “server” at once.

Frequently Asked Questions

How do I make a CountDownLatch reusable?

You can’t: CountDownLatch has no reset method, and that’s by design — the latch records a one-time event. For repeating rounds, create a new latch per round, or use CyclicBarrier if the parties themselves wait, and Phaser if the number of parties changes. The comparison is in CountDownLatch vs CyclicBarrier.

What does CyclicBarrier.await() return?

The arrival index of the current thread: getParties() - 1 for the first to arrive and 0 for the last. You can use it to pick a “leader” for the round without a barrierAction: if (barrier.await() == 0) { … } runs the code in exactly one thread — the last to arrive. The difference from barrierAction is that the other threads are no longer waiting at that moment; they run in parallel.

Can a Semaphore limit requests to N per second?

On its own, a semaphore limits the number of concurrent operations, not their rate: short requests will pass through three permits hundreds of times per second. For a rate limit, permits aren’t returned after the request but replenished once a second by a scheduler: scheduler.scheduleAtFixedRate(() -> { semaphore.drainPermits(); semaphore.release(n); }, 1, 1, TimeUnit.SECONDS). This works because a semaphore has no owner, but for serious limits people usually reach for a ready-made library (for example, Resilience4j RateLimiter or Guava RateLimiter).

Which is better for limiting concurrency: Semaphore or newFixedThreadPool(n)?

A pool limits the number of threads, and therefore everything those threads do. A semaphore limits access to a specific resource: tasks can compute anything in parallel, but only n of them hit the database at once. With platform threads a pool is often enough; with virtual threads only a semaphore works, because virtual threads aren’t pooled (see Synchronizers and Virtual Threads).

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.