CyclicBarrier in Java with Examples: The Reusable Rendezvous Point
-
Last Updated: October 20, 2026
-
By: javahandson
-
Series

CyclicBarrier in Java explained with simple examples: how await() works, the barrier action, reuse across rounds, and CountDownLatch vs CyclicBarrier.
A CyclicBarrier in Java is a simple tool that makes a group of threads wait for each other. No thread moves ahead until every thread in the group has arrived. Think of it as a shared meeting point. Everyone gathers there first. Only then does the whole group move on together.
The name sounds heavy, but the idea is light. “Barrier” means a wall where threads pause. “Cyclic” means that wall works again and again. That second part is the real magic. We will come back to it soon.
In this guide we build a clear picture from scratch. First comes the core idea. Then we run real code. By the end, you will know exactly when to reach for a barrier. You will also know when to pick a simpler tool instead.

Figure 1: Threads pause at the barrier and cross together once the last one arrives. The barrier then resets for the next round.
Let me start with a picture you already know from daily life.
Imagine three friends who plan to enter a cinema hall together. The rule is simple. Nobody goes in alone. Each friend reaches the gate at their own pace. One of them waits at the gate. Soon the second one shows up and waits too. The moment the third friend arrives, all three walk in at once.
A barrier works in the very same way. You tell it how many threads to expect. Each thread does its own work. Then it calls a method and waits. When the last thread arrives, the barrier opens. Every thread then continues at the same time.
Picture a small group tour with a guide. The guide says one thing clearly. “We leave for the next spot only when all ten of us are back on the bus.” Early people wait. Late people rush. The bus starts only when the tenth person sits down. That bus is your barrier in code.
This analogy also hints at the “cyclic” trait. The bus does not retire after one stop. It waits, moves, and then waits again at the next stop. One bus handles the whole trip. In the same way, one barrier handles many rounds.
| 💡 Interview Insight A clean one-line answer works well here. A CyclicBarrier makes a fixed number of threads wait at a common point, and you can reuse it for the next round. |
The tool looks like magic from outside. Inside, it is just a counter and a lock. Once you see the counter, the whole thing makes sense.
When you create a barrier, you give it a number. This number is called the parties. It is the count of threads the barrier waits for.
The barrier keeps an internal counter. This counter starts at the parties value. Each time a thread calls await(), the count of waiting threads goes up by one. That thread then goes to sleep and holds its place.
The last thread plays a special role. Its await() call fills the final seat. This moment is called “tripping” the barrier. The barrier then wakes up every waiting thread. All of them return from await() together and carry on.
The await() method hands back a small number. This number is the arrival index of the thread. The last thread to arrive gets index zero. The first one to arrive gets parties minus one. Most of the time you ignore this value. Still, it helps when you want only one thread to run a special job.
int index = barrier.await();
// Only one thread will see index 0.
if (index == 0) {
System.out.println("I was the last to arrive this round");
}Want a peek under the hood? A barrier uses a ReentrantLock and a Condition inside. The lock guards the waiting count. Parked threads sleep on that Condition. A barrier also keeps a small object called the generation.
Each round gets a fresh generation. When the barrier trips, it swaps in a new generation and resets the count. That swap is how one barrier serves many rounds safely. A broken round simply marks its generation as broken.
| 💡 Interview Insight await() also comes in a timed form. Use await(5, TimeUnit.SECONDS) when a thread must not wait forever. Timed waits protect you from a thread that never shows up. |
Let us trace one round with three parties. It makes the counter idea concrete.
Notice the pattern in that trace. Only the final arrival does the heavy lifting. Earlier threads simply park and rest. This design keeps the barrier cheap and fair.
The class lives in the java.util.concurrent package. It gives you two constructors. Both read like plain English.
// Option 1: just the party count
CyclicBarrier barrier = new CyclicBarrier(3);
// Option 2: party count plus an action that runs when the barrier trips
CyclicBarrier barrier2 = new CyclicBarrier(3, () -> {
System.out.println("All three threads have arrived");
});Pick the first form for plain synchronization. Pick the second form when some work must happen once per round. We will see that bonus task in a moment.
Enough theory for now. Let us run some real code. Here three workers each finish a first task. Then they meet at the barrier. Only after all three arrive do they start the second task.
import java.util.concurrent.CyclicBarrier;
public class BarrierDemo {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 1; i <= 3; i++) {
final int id = i;
new Thread(() -> {
try {
System.out.println("Worker " + id + " doing part 1");
Thread.sleep(id * 500L); // different speeds
System.out.println("Worker " + id + " reached the barrier");
barrier.await(); // wait for the others
System.out.println("Worker " + id + " doing part 2");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}Run this, and the output tells a clear story. Each worker prints “part 1” at its own speed. Yet nobody prints “part 2” early. The barrier holds the fast workers until the slowest one catches up.
The exact order of lines may shift on each run. That is normal with threads. But one rule never breaks. No “part 2” line appears before all three “reached the barrier” lines. The barrier draws a firm line between the two stages.
Worker 1 doing part 1 Worker 2 doing part 1 Worker 3 doing part 1 Worker 1 reached the barrier Worker 2 reached the barrier Worker 3 reached the barrier Worker 1 doing part 2 Worker 2 doing part 2 Worker 3 doing part 2
Many real jobs run in stages. Stage two should not start until everyone finishes stage one. A barrier gives you that promise for free. You skip messy boolean flags. You skip random sleep calls. The result is code that is easy to read and trust.
Do you remember the second constructor? It takes a Runnable. We call this the barrier action. It is a small task that fires on its own when the barrier trips.
Here is the part many people miss. The barrier action does not run on a brand new thread. It runs on the last thread that arrives. And it runs before any waiting thread wakes up. So it is a safe spot to do work that should happen once per round.
import java.util.concurrent.CyclicBarrier;
public class BarrierActionDemo {
public static void main(String[] args) {
Runnable merge = () -> System.out.println(">> All parts done. Merging results.");
CyclicBarrier barrier = new CyclicBarrier(3, merge);
for (int i = 1; i <= 3; i++) {
final int id = i;
new Thread(() -> {
try {
System.out.println("Thread " + id + " finished its slice");
barrier.await();
System.out.println("Thread " + id + " moves on");
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}).start();
}
}
}This ordering gives you a strong guarantee. No worker thread sees stage-two work before the merge is done. So you do not need extra locks around that merge step. The barrier already draws a clean boundary for you. Keep the action small, though. A heavy action slows every thread down.
| 💡 Interview Insight The barrier action is perfect for merging results. Each thread fills its own slot during the round. The action then combines all slots in one clean, thread-safe step. |
Now we reach the heart of the topic. The word “cyclic” is not just for show. After a barrier trips, it resets on its own. The counter returns to the full parties value. The same barrier is ready for the next round right away.
import java.util.concurrent.CyclicBarrier;
public class RoundsDemo {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(2,
() -> System.out.println("--- round finished ---\n"));
Runnable task = () -> {
try {
for (int round = 1; round <= 3; round++) {
String name = Thread.currentThread().getName();
System.out.println(name + " running round " + round);
Thread.sleep((long) (Math.random() * 800));
barrier.await(); // same barrier, every round
}
} catch (Exception e) {
Thread.currentThread().interrupt();
}
};
new Thread(task, "T1").start();
new Thread(task, "T2").start();
}
}Two threads run three rounds here. In each round they do a bit of work. Then they meet at the barrier. The barrier releases them, resets itself, and waits again. One barrier object handles all three rounds with ease.
This reuse is the big win. You build the barrier once. Then you use it round after round. That approach saves objects and keeps your loop tidy.
Think of the barrier as a turnstile for a group. The gate stays shut while people gather. It opens once the full group is present. Then it closes again and gets ready for the next group. Nothing about the turnstile wears out between rounds.
| 💡 Interview Insight If your problem has repeated phases, such as steps in a simulation, a single CyclicBarrier handles every phase without any extra setup. |
What if you only need a single wait and never a second round? Then a barrier is overkill for the job. For that one-shot case, a different tool fits better. You can learn about it in the guide CountDownLatch in Java with Examples. A latch counts down once and then retires. A barrier keeps coming back for more.
Threads do not always behave. One might get interrupted. One might run out of time. When that happens, the barrier “breaks.”
A broken barrier cannot trip in the normal way. So every thread still waiting gets a BrokenBarrierException. This is Java’s way of saying one thing. “The group plan failed, so stop waiting.”
You can repair a broken barrier with reset(). This call clears the broken state and starts fresh. But use it with care. Any thread waiting at the exact time of reset will also get a BrokenBarrierException.
try {
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // keep the interrupt flag
} catch (BrokenBarrierException e) {
System.out.println("Barrier broke. Cleaning up this round.");
// Decide whether to retry, skip the round, or call barrier.reset()
}A plain await() can wait forever. That is risky in a real service. One stuck thread could freeze the whole group. A timed await() fixes this problem. It gives up after a set time and throws a TimeoutException. You then log the issue and recover with a clear head.
| 💡 Interview Insight Always wrap await() in a try-catch. Handle both InterruptedException and BrokenBarrierException. A silent failure here is very hard to debug later. |
A few helper methods make daily work easier. You will not touch all of them often. Yet they help a lot in interviews and in debugging.
| Method | What It Does |
|---|---|
| await() | Waits until all parties arrive at the barrier |
| await(timeout, unit) | Waits, but gives up after the given time limit |
| getParties() | Returns the total number of parties |
| getNumberWaiting() | Returns how many threads are waiting right now |
| isBroken() | Tells whether the barrier is in a broken state |
| reset() | Resets the barrier back to its fresh state |
This method helps most during debugging. It shows how many threads already sit at the barrier. A stuck program often has one missing thread. A quick print then reveals the gap fast.
System.out.println("Waiting now : " + barrier.getNumberWaiting());
System.out.println("Total parties: " + barrier.getParties());This comparison shows up in nearly every concurrency interview. Both tools make threads wait. Yet they solve two different problems. Let us keep the difference simple and clear.

Figure 2: A CountDownLatch counts down once and retires. A CyclicBarrier resets and runs again.
| Feature | CountDownLatch | CyclicBarrier |
|---|---|---|
| Reusable | No, one-shot | Yes, cyclic |
| Who waits | Any thread can wait | The arriving threads wait |
| What triggers it | countDown() calls reach zero | All parties call await() |
| Built-in action | No | Yes, an optional barrier action |
| Common use | Wait for startup or tasks to finish | Sync threads in repeated phases |
Use a latch when one event must finish before others may start. Use a barrier when a group must move in steps together. A latch means “wait for it.” A barrier means “wait for each other.”
There is one more clue in the names. A latch is a gate that locks open after one release. A barrier is a wall that keeps standing for the next crowd. Hold that image, and you will never swap them by mistake.
| 💡 Interview Insight The reuse point is the clincher. If the interviewer asks for repeated synchronization, the answer is CyclicBarrier, not CountDownLatch. |
Still unsure which one to grab? Run through these quick questions.
A barrier is easy to use, but a few traps catch beginners. Keep this short list handy.
Where does a barrier truly shine? It shines anywhere work happens in matched steps.
Parallel computation is the classic fit. Say you must process a huge data set. You split it into equal chunks. Each thread crunches one chunk on its own. Then all threads meet at the barrier. The barrier action merges the partial results into one answer. After that, the next phase can begin on clean data.
This pattern repeats in many systems. Scientific models use it. Image tools use it. Even some map-reduce style jobs use it. The shape is always the same: work, sync, merge, repeat.
A: CyclicBarrier is used to make a fixed number of threads wait for each other at a common point. No thread moves past the barrier until all of them arrive. It suits work that runs in matched phases, such as parallel computation or simulations.
A: A CountDownLatch counts down to zero only once and cannot be reused. A CyclicBarrier resets after every trip, so you can use the same object for many rounds. With a latch any thread can wait, while a barrier waits for the arriving threads themselves.
A: The await() method makes the calling thread pause at the barrier. It returns an arrival index, where the last thread to arrive gets zero. When the final thread calls await(), the barrier trips and releases everyone together.
A: A barrier action is an optional Runnable you pass to the constructor. It runs once each time the barrier trips. It runs on the last-arriving thread and finishes before the other threads continue, which makes it great for merging results.
A: A barrier breaks when a waiting thread is interrupted or a timed await() times out. Every thread still waiting then receives a BrokenBarrierException. You can call reset() to put the barrier back into a fresh, usable state.
A: Yes, and this is its main strength. After all parties arrive and the barrier trips, it resets automatically. The same barrier is then ready for the next round of synchronization.
A CyclicBarrier in Java is a clean way to make threads wait for each other. You set a party count. Each thread calls await(). The last arrival trips the barrier. After that, everyone moves on together.
Its best feature is reuse. The same barrier handles round after round with zero extra setup. Add an optional barrier action, and you gain a tidy spot to merge results or print a summary.
Keep the core rules in mind. Match the party count to your threads. Handle the broken state with care. Prefer timed waits in real systems. Do that, and barriers will make your multi-threaded code far easier to reason about.