How do CountDownLatch, CyclicBarrier and Semaphore differ? Give backend examples?
Short answer
CountDownLatch lets threads wait until a counter reaches 0 (single use), CyclicBarrier lets N threads wait for each other and then proceed together (reusable), Semaphore limits how many threads enter at once using permits. In a backend, Semaphore is the most common: it caps concurrent calls to a dependency.
3 points to say:
- Latch: wait for N events, single use, e.g. wait for 3 caches to warm up before taking traffic.
- Barrier: N threads wait for each other, reusable each round; Semaphore: permits cap entries, the right way to limit scarce resources even with virtual threads.
- Always use the timeout variants (
tryAcquire(100, MILLISECONDS)) andrelease()infinally: an extra release adds a permit.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.