Working with Synchronizers
1. Using CountDownLatch
| API | Use |
|---|---|
new CountDownLatch(n) | Initial count |
countDown() | Decrement |
await() | Block until 0 |
| One-shot | Cannot reset |
Example: Wait for N workers
var latch = new CountDownLatch(workers);
for (var w : tasks) exec.submit(() -> { try { w.run(); } finally { latch.countDown(); } });
latch.await();
2. Using CyclicBarrier
| API | Use |
|---|---|
new CyclicBarrier(parties[, action]) | Synchronization point |
await() | Wait for all parties |
| Reusable | Auto-resets after trip |
| Broken | Interrupt or timeout breaks barrier |
3. Using Semaphore
| API | Use |
|---|---|
new Semaphore(permits[, fair]) | Resource pool |
acquire([n]) | Block for permits |
release([n]) | Return permits |
tryAcquire([t, u]) | Non-blocking / timed |
4. Using Exchanger
| API | Use |
|---|---|
exchange(v) | Swap values between two threads |
| Pair | Both threads block until both arrive |
| Use | Producer/consumer buffer swap |
5. Using Phaser
| API | Use |
|---|---|
register / bulkRegister | Add parties dynamically |
arriveAndAwaitAdvance | Like CyclicBarrier |
arriveAndDeregister | Leave |
| Phases | Numbered, multi-stage |
6. Understanding Use Cases for Each
| Synchronizer | Best For |
|---|---|
| CountDownLatch | One-time wait for N events |
| CyclicBarrier | Repeated all-meet rendezvous |
| Semaphore | Resource limiting / rate limiting |
| Exchanger | Pairwise data swap |
| Phaser | Dynamic parties + multi-phase |
7. Combining Multiple Synchronizers
| Pattern | Combination |
|---|---|
| Bounded parallelism | Semaphore + ExecutorService |
| Phased pipeline | Phaser per stage |
| Startup gate | Two CountDownLatches (start, done) |
8. Avoiding Common Pitfalls
| Pitfall | Fix |
|---|---|
| Forget release() on exception | Use try/finally |
| Latch never reaches 0 | Decrement in finally block |
| Broken barrier | Catch BrokenBarrierException |
| Deadlock with multiple latches | Consistent ordering |
9. Using LockSupport
| API | Use |
|---|---|
park() | Block current thread |
parkNanos(t) | Timed |
unpark(thread) | Wake target |
| Permit | Per-thread, single permit |
| Use | Building blocks for custom locks |
10. Implementing Custom Synchronizers
| Base | Use |
|---|---|
AbstractQueuedSynchronizer | Foundation for ReentrantLock, Semaphore |
| Override | tryAcquire / tryRelease (exclusive) or shared variants |
| State | Single int held by AQS |