SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 12 / 19

Middle

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.

wait for N tasks, onceN threads wait togethercap concurrent entriesCoordinate threads?CountDownLatchCyclicBarrierSemaphoreWait for cache warm-upAt most 20 callsto partner API

3 points to say:

  1. Latch: wait for N events, single use, e.g. wait for 3 caches to warm up before taking traffic.
  2. 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.
  3. Always use the timeout variants (tryAcquire(100, MILLISECONDS)) and release() in finally: 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.