Backend Development 11 min read

Understanding Java Concurrency Utilities: CyclicBarrier, CountDownLatch, Semaphore, and Exchanger

This article provides a comprehensive overview of Java's core concurrency utilities—CyclicBarrier, CountDownLatch, Semaphore, and Exchanger—explaining their purposes, internal mechanisms, constructors, usage patterns, and code examples to help developers master multithreaded programming.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Understanding Java Concurrency Utilities: CyclicBarrier, CountDownLatch, Semaphore, and Exchanger

This article concludes a series on multithreading, aiming to help readers thoroughly understand Java concurrency utilities and their practical applications.

It introduces four commonly used tools—CyclicBarrier, CountDownLatch, Semaphore, and Exchanger—describing the scenarios each fits and their key characteristics.

CyclicBarrier allows a group of threads to wait until a common barrier point is reached; it reuses the barrier after release. Internally it relies on ReentrantLock and Condition . Constructors include CyclicBarrier(int parties) and CyclicBarrier(int parties, Runnable barrierAction) . Important fields are parties , count , barrierAction , and generation . The following internal workflow is illustrated:

M- await : waiting state
M- await(long timeout, TimeUnit unit) : timed wait
M- dowait
    - try to acquire lock
    - if generation broken, throw exception
    - if thread interrupted, terminate CyclicBarrier
    - decrement count
    - if count == 0, trigger Runnable and wake all threads, update generation
    > exit conditions:
        - last thread arrives (index == 0)
        - timeout occurs
        - a thread interrupts current thread
        - a thread interrupts another waiting thread
        - barrier timeout
        - reset() called, resetting barrier to initial state
SC- Generation : describes generation updates; when all parties arrive, generation advances; broken flag indicates interruption.
M- breakBarrier : terminates all threads
M- nextGeneration : wake all threads, reset count and generation
M- reset : reset barrier to initial state
M- getNumberWaiting : obtain number of waiting threads
M- check if CyclicBarrier is broken

A usage example from Gitee is referenced.

CountDownLatch blocks one or more threads until a set of operations performed by other threads completes. It is built on AQS via an internal Sync class. Key methods:

> CountDownLatch relies on Sync extending AQS
> sync:
    : tryAcquireShared obtains sync state
    : tryReleaseShared releases sync state
> await():
    : thread waits until count reaches zero or is interrupted
    : sync.acquireSharedInterruptibly(1)
> getState(): returns current count value
> doAcquireSharedInterruptibly: spin-wait for state
> countDown(): decrements count; when zero, releases all waiting threads via AQS releaseShared

Reference implementations on Gitee are cited.

Semaphore is a counting lock that controls access to a set of shared resources. It maintains a permit set; acquire() blocks when permits are exhausted, and release() adds a permit. Constructors: Semaphore(int permits) (non‑fair) and Semaphore(int permits, boolean fair) . Fairness determines whether the thread must be at the head of the CLH queue. Code illustration:

> acquire() obtains a permit via AQS acquireSharedInterruptibly(int arg)
> Fair mode:
    : check if thread is at CLH queue head
    : obtain current permit
    : update remaining permits after acquisition
    : CAS to set new permit count
> Non‑fair mode:
    : no CLH head check needed

When the permit count is 1, the semaphore behaves like a mutex.

Exchanger provides a synchronization point where two threads can exchange objects. Each thread calls exchange() , pairing with a partner thread; it can be viewed as a bidirectional SynchronousQueue . The article notes limited use cases and leaves detailed source analysis for future work.

The article also offers analogies to help understand the tools: CyclicBarrier is likened to a school field‑trip where all students must be present before proceeding, while CountDownLatch resembles a teacher waiting for all children to leave before finishing work. It highlights that CyclicBarrier can be reset, whereas CountDownLatch cannot.

Reference links to the Gitee source code for each utility are provided for further exploration.

JavaconcurrencySemaphoreCountDownLatchCyclicBarrierExchanger
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.