The Plain Picture#
A starting gun that fires only after all 3 runners say "ready". (CountDownLatch)
A car park with 2 spaces: a car enters only if a space is free, and leaves one when it goes. (Semaphore)
A tour group that waits at each landmark until everyone has caught up, then moves on together. (CyclicBarrier)
The Real Names and Uses#
CountDownLatch(n) — threads call countDown(); await() blocks until the count reaches 0. One-shot.
CountDownLatch ready = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
int id = i;
pool.submit(() -> {
System.out.println("service " + id + " warmed up");
ready.countDown();
});
}
ready.await();
System.out.println("all services ready");service 1 warmed up
service 0 warmed up ← order varies — they ran concurrently
service 2 warmed up
all services ready ← only after all threeSemaphore(permits) — acquire() takes a permit (waiting if none are left), release() returns it. Perfect for limiting concurrency — for example,
the AI provider allows only 2 simultaneous requests from StudyBuddy:
Semaphore aiSlots = new Semaphore(2);
// each of 6 tasks:
aiSlots.acquire();
try {
callAiApi();
} finally {
aiSlots.release();
}semaphore(2): max concurrent AI calls = 2Six tasks, never more than two in flight. (Rate limiting across many servers needs a shared store like Redis instead — Rate Limiting and API Gateways (coming soon).)
CyclicBarrier(n) — n threads each call await() and all are released together when the n-th arrives; reusable for rounds (e.g. parallel simulation steps).
Phaser is a more flexible version.
Check yourself
2 questionsWhich tool would you use to cap simultaneous calls to an external API at 5?
Show answerHide answer
Semaphore(5), with acquire before and release in finally after each call.
CountDownLatch vs CyclicBarrier?
Show answerHide answer
A latch is one-shot and lets threads wait for a count of events; a barrier makes a fixed group of threads wait for each other, and can be reused for many rounds.