Skip to content
Java CyclicBarrier: Reusable Thread Barrier with Callback for Parallel Aggregation

Java CyclicBarrier: Reusable Thread Barrier with Callback for Parallel Aggregation

This article explains Java's CyclicBarrier synchronization utility, highlighting its reusability and callback support compared to CountDownLatch, and demonstrates its use in two examples: a basic three-thread barrier with a callback and a parallel array sum calculation where threads compute partial sums and aggregate at the barrier.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture

CyclicBarrier is a Java synchronization utility that lets multiple threads wait at a barrier point until all threads have arrived, after which they continue execution. Unlike CountDownLatch, CyclicBarrier can be reused after the barrier is tripped and supports an optional callback task that runs when all threads reach the barrier.

Basic CyclicBarrier Demo

The first example creates a CyclicBarrier for three threads with a callback that prints a message when all threads arrive. Each thread prints a message before calling barrier.await(), then prints another message after passing the barrier.

package com.sample.interview.multithread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        int n = 3;
        CyclicBarrier barrier = new CyclicBarrier(n, new Runnable() {
            public void run() {
                System.out.println("执行回调,所以线程都已经达到屏障");
            }
        });

        Thread t1 = new Thread(new ThreadDemo(barrier, "任务1"));
        Thread t2 = new Thread(new ThreadDemo(barrier, "任务2"));
        Thread t3 = new Thread(new ThreadDemo(barrier, "任务3"));

        t1.start();
        t2.start();
        t3.start();
    }

    static class ThreadDemo implements Runnable {
        private final CyclicBarrier barrier;
        private final String name;

        public ThreadDemo(CyclicBarrier barrier, String name) {
            this.barrier = barrier;
            this.name = name;
        }

        public void run() {
            try {
                System.out.println(name + "达到屏障之前");
                // 等待其他线程
                barrier.await();
                System.out.println(name + "线程通过屏障");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}

Output shows the three threads reaching the barrier in arbitrary order, then the callback executes, followed by each thread proceeding past the barrier:

任务1达到屏障之前
任务3达到屏障之前
任务2达到屏障之前
执行回调,所以线程都已经达到屏障
任务2线程通过屏障
任务1线程通过屏障
任务3线程通过屏障

Parallel Array Sum with CyclicBarrier

A more practical example splits an array of 10 integers among three worker threads. Each thread computes a partial sum of its assigned segment, stores it in a shared partialSums array, then waits at the barrier. The barrier's callback aggregates the partial sums into a total and prints the result.

package com.sample.interview.multithread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierSum {
    private static final int[] arr = new int[] {1,2,3,4,5,6,7,8,9,10};
    private static final int THREAD_COUNT = 3;
    private static int[] partialSums;
    private static volatile int totalSum = 0;

    public static void main(String[] args) {
        partialSums = new int[THREAD_COUNT];
        CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () -> {
            // 当所有线程到达屏障时,汇总部分和
            for (int sum : partialSums) {
                totalSum += sum;
            }
            System.out.println("数组总和为: " + totalSum);
        });

        int chunkSize = arr.length / THREAD_COUNT;
        for (int i = 0; i < THREAD_COUNT; i++) {
            int start = i * chunkSize;
            int end = (i == THREAD_COUNT - 1) ? arr.length : start + chunkSize;
            new Thread(new Worker(i, start, end, barrier)).start();
        }
    }

    static class Worker implements Runnable {
        private final int id;
        private final int start;
        private final int end;
        private final CyclicBarrier barrier;

        public Worker(int id, int start, int end, CyclicBarrier barrier) {
            this.id = id;
            this.start = start;
            this.end = end;
            this.barrier = barrier;
        }

        @Override
        public void run() {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += arr[i];
            }
            partialSums[id] = sum;
            try {
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}

This pattern is well-suited for scenarios where multiple threads perform independent computations and the results need to be combined, such as parallel aggregation, map-reduce style tasks, or multi-phase algorithms requiring synchronization between phases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConcurrencySynchronizationMultithreadingParallel ProcessingCountDownLatchCyclicBarrierThread Coordination
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.