All topics
library
advanced

Java Concurrency Utilities: CountDownLatch, CyclicBarrier, Semaphore

Coordinate thread execution with synchronization aids beyond wait/notify.

java.util.concurrent provides high-level synchronization aids that simplify common thread coordination patterns.

CountDownLatch = a rocket launch countdown (reaches zero, launches once, can't reuse). CyclicBarrier = a rowing team (all rowers synchronize their strokes, then go again). Semaphore = a parking lot with limited spaces (take a spot, return it when done).

Key Concepts

1
CountDownLatch: a one-time barrier. Initialize with count N. Threads call await() to block until the count reaches zero. Other threads call countDown() to decrement. Cannot be reset.
2
Use case: main thread waits for N worker threads to finish initialization.
3
CyclicBarrier: a reusable barrier. N threads call await() and all block until all N have arrived. Then all are released simultaneously. Can be reused for multiple rounds (cyclic).
4
Use case: phased computation — all threads must finish phase 1 before any starts phase 2.
5
Semaphore: controls access to a shared resource with a limited number of permits. acquire() takes a permit (blocks if none available). release() returns a permit.
6
Use case: connection pool — limit to N concurrent connections.
7
Phaser (Java 7): flexible, reusable barrier that supports dynamic participant count. Combines features of CountDownLatch and CyclicBarrier. More complex but more powerful.
8
Exchanger<V>: pairs two threads and lets them swap data at a synchronization point. Rarely used.