CyclicBarrier in Java with Examples: The Reusable Rendezvous Point

  • Last Updated: October 20, 2026
  • By: javahandson
  • Series
img

CyclicBarrier in Java with Examples: The Reusable Rendezvous Point

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.

Three threads arriving at a CyclicBarrier at different times and crossing together once the last one arrives, then the barrier resetting for the next round

Figure 1: Threads pause at the barrier and cross together once the last one arrives. The barrier then resets for the next round.

1. What Is a CyclicBarrier in Java?

Let me start with a picture you already know from daily life.

1.1 The Barrier Idea — Everyone Waits for Everyone

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.

  • You fix the number of threads up front. This value is called the party count.
  • Each thread reaches the barrier and pauses there.
  • The barrier releases everyone together once the count is met.

1.2 A Quick Real-Life Analogy

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.

2. How a CyclicBarrier Works Internally

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.

2.1 await() and the Trip Count

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.

  • parties is the total number of threads the barrier expects.
  • Each await() call parks one more thread at the barrier.
  • The final await() trips the barrier and frees the whole group.

2.2 What await() Returns

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");
}

2.3 The Lock and the Generation

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.

2.4 A Step-by-Step Trip Walkthrough

Let us trace one round with three parties. It makes the counter idea concrete.

  • Thread A finishes first and calls await(). The waiting count becomes 1. A sleeps.
  • Thread B arrives next and calls await(). The waiting count becomes 2. B sleeps.
  • Thread C arrives last and calls await(). The count now matches the parties value.
  • That last call trips the barrier. The barrier runs the action, if any, then wakes A and B.
  • All three return from await() together. The counter resets to zero for the next round.

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.

3. Creating a CyclicBarrier

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");
});
  • CyclicBarrier(int parties) — waits for the given number of threads.
  • CyclicBarrier(int parties, Runnable action) — does the same, plus runs a bonus task on each trip.

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.

4. A Complete CyclicBarrier Example

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.

4.1 Reading the Output

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

4.2 Why This Pattern Helps

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.

5. The Optional Barrier Action

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.

5.1 Who Runs the Barrier Action, and When

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();
        }
    }
}
  • The action runs exactly once per trip.
  • It runs on the last-arriving thread, not a fresh one.
  • It fully finishes before the other threads wake up and continue.

5.2 A Note on Ordering

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.

6. Reusing the Barrier Across Rounds

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.

6.1 The Cyclic Part in Action

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.

6.2 A Simple Mental Model

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.

6.3 When a Barrier Is Too Much

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.

7. Handling a Broken Barrier

Threads do not always behave. One might get interrupted. One might run out of time. When that happens, the barrier “breaks.”

7.1 What a Broken Barrier Means

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.”

  • An interrupt on any waiting thread breaks the barrier.
  • A timeout on a timed await() also breaks it.
  • Every thread still waiting then receives a BrokenBarrierException.

7.2 Resetting a Barrier

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()
}

7.3 Why Timed Waits Matter

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.

8. Useful Methods of CyclicBarrier

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.

MethodWhat 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

8.1 A Quick Look at getNumberWaiting()

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());

9. CountDownLatch vs CyclicBarrier

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.

Side by side comparison of CountDownLatch counting down to zero once versus CyclicBarrier resetting after each trip

Figure 2: A CountDownLatch counts down once and retires. A CyclicBarrier resets and runs again.

9.1 The Core Difference

  • A CountDownLatch counts down to zero once. After that it is done. You cannot reuse it.
  • A CyclicBarrier resets after every trip. You reuse it for many rounds.
  • With a latch, the waiting threads and the counting threads can be different sets.
  • With a barrier, the waiting threads are the same threads that count.
FeatureCountDownLatchCyclicBarrier
ReusableNo, one-shotYes, cyclic
Who waitsAny thread can waitThe arriving threads wait
What triggers itcountDown() calls reach zeroAll parties call await()
Built-in actionNoYes, an optional barrier action
Common useWait for startup or tasks to finishSync threads in repeated phases

9.2 A Simple Way to Remember It

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.

9.3 A Quick Decision Checklist

Still unsure which one to grab? Run through these quick questions.

  • Do you need the wait to repeat? If yes, choose a barrier.
  • Is it a single, one-time event? If yes, choose a latch.
  • Must some work run once each round? A barrier action fits well.
  • Do waiters and signalers differ? A latch handles that split cleanly.

10. Common Mistakes and Best Practices

A barrier is easy to use, but a few traps catch beginners. Keep this short list handy.

  • Wrong party count: If parties is larger than your thread count, the barrier never trips, and threads wait forever.
  • Swallowing exceptions: Never hide a BrokenBarrierException. Log it, or react to it properly.
  • Heavy barrier action: Keep the action short. It blocks every thread from moving on.
  • No timeout in production: Prefer the timed await(). It saves you from frozen threads.
  • Mixing up tools: For a single wait, pick a latch. For repeated waits, pick a barrier.

11. Real-World Use Cases

Where does a barrier truly shine? It shines anywhere work happens in matched steps.

  • Parallel computation: Split a big array into parts. Each thread handles one part. The barrier waits, and then you merge the parts.
  • Simulations and games: Every actor computes one tick. The barrier syncs the tick. Then the next tick begins.
  • Multiplayer round loading: Hold the round until all players finish loading the level.
  • Concurrency testing: Release many threads at the exact same instant to stress a system under load.

11.1 A Closer Look at Parallel Work

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.

12. FAQ’s on CyclicBarrier in Java

Q: What is CyclicBarrier in Java used for?

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.

Q: How is CyclicBarrier different from CountDownLatch?

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.

Q: What does the await() method do in CyclicBarrier?

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.

Q: What is a barrier action in CyclicBarrier?

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.

Q: What happens when a CyclicBarrier breaks?

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.

Q: Can a CyclicBarrier be reused?

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.

13. Conclusion

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.

14. Further Reading

Leave a Comment