Barriers & Latches
Making a group of threads meet at a point: the one-shot CountDownLatch, the reusable CyclicBarrier, the flexible Phaser, how a broken barrier releases everyone, and how to build a latch and a barrier from a condition variable.
Overview
Some coordination is not about protecting data but about timing a group. The main thread must not serve traffic until the database, the cache and the search index are all ready. In a simulation, no worker may start step 2 until every worker has finished step 1. Latches and barriers are the tools for these meeting points.
The two differ in who waits and whether they can be reused. A latch is a gate that opens once: some threads count it down, others wait for it to reach zero, and after that it stays open. A barrier is a meeting point for a fixed group: each member waits until all have arrived, then all go on together, and the barrier resets for the next round.
The family at a glance
Java ships four of these tools and Python ships one. They differ in four ways: who waits, when the gate opens, whether it can be used again, and whether the group can change size.
- Java CountDownLatch(n): any thread that calls await() waits. The gate opens once countDown() has been called n times, by anyone. It cannot be reused, because the count cannot be reset, and the number of parties is fixed.
- Java CyclicBarrier(n, action): the n parties themselves wait. It opens when all n have called await(), and the action runs first. It resets automatically after each round, and the number of parties is fixed.
- Java Phaser: the registered parties wait. It opens when all of them arrive at the current phase. It is reusable, and its phases are numbered. The group can change: parties join with register() and leave with arriveAndDeregister().
- Java Exchanger: two threads meet. When both arrive, each receives the other's object. It is reusable and always works on a pair.
- Python threading.Barrier(n, action, timeout): the n parties wait until all n have called wait(). It is reusable, and the number of parties is fixed.
Python's standard library has no latch, so the next section builds one from a Condition.
Interview questions
- What is a CountDownLatch and when do you use it?
- How does a CyclicBarrier differ from a CountDownLatch?
- What happens if one thread fails or times out while others wait at a barrier?
- Implement a reusable barrier from a lock and a condition variable.
- What is a Phaser and when would you use it over a CyclicBarrier?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio