Mastering Java’s CyclicBarrier: Synchronize Threads with Ease

This article explains Java’s CyclicBarrier synchronization barrier introduced in JDK 1.5, detailing its constructors, key methods such as await() and reset(), usage patterns for coordinating multiple threads in performance testing, and provides a complete demo with code examples and practical tips for handling timeouts and exceptions.

FunTester
FunTester
FunTester
Mastering Java’s CyclicBarrier: Synchronize Threads with Ease

Overview

CyclicBarrier, also known as a synchronization barrier, was added to the JDK in version 1.5. It allows a group of threads to wait at a common point until all threads have reached that point, after which they can all proceed. This mechanism is especially useful in performance testing scenarios where many virtual users must synchronize at specific stages.

Constructors

The class provides two main constructors: public CyclicBarrier(int parties) – specifies the number of threads that must call await() before the barrier is tripped. public CyclicBarrier(int parties, Runnable barrierAction) – in addition to the thread count, defines an action to execute once the barrier is tripped (often illustrated with a “starting gun” metaphor).

Key Methods

await() – Called by a thread to indicate it has reached the barrier and to wait for the remaining threads. An overloaded version accepts a timeout and a TimeUnit parameter. If the timeout expires, a TimeoutException is thrown, and the waiting threads receive a BrokenBarrierException.

If the calling thread is the last to arrive and a barrierAction was supplied, that action is executed before the method returns. The method also throws InterruptedException if the waiting thread is interrupted.

reset() – Returns the barrier to its initial state, causing any waiting threads to receive a BrokenBarrierException. This is useful for reusing the same barrier across multiple test cycles.

Implementation Details

public CyclicBarrier(int parties) { this(parties, null); }
public CyclicBarrier(int parties, Runnable barrierAction) { if (parties <= 0) throw new IllegalArgumentException(); this.parties = parties; this.count = parties; this.barrierCommand = barrierAction; }
public int await() throws InterruptedException, BrokenBarrierException { return dowait(false, 0L); }
public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException { return dowait(true, unit.toNanos(timeout)); }
public void reset() { final ReentrantLock lock = this.lock; lock.lock(); try { breakBarrier(); nextGeneration(); } finally { lock.unlock(); } }

Practical Demo

The following demo creates a CyclicBarrier for two threads, adds a simple logging action, and shows how to handle normal await, timeout await, and barrier reset scenarios.

public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(2, () -> logger.warn("very good")); new Thread(() -> { logger.info("111111111"); try { barrier.await(1, TimeUnit.SECONDS); sleep(1); barrier.await(); } catch (Exception e) { e.printStackTrace(); } }).start(); new Thread(() -> { sleep(2); logger.info("222222222"); try { barrier.await(); barrier.await(); } catch (Exception e) { e.printStackTrace(); } }).start(); testOver(); }

Running the demo produces output similar to:

INFO-> 当前用户:fv,IP:192.168.0.107,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.6 INFO-> 111111111 INFO-> 222222222 WARN-> very good WARN-> very good Process finished with exit code 0

This example demonstrates how the barrier synchronizes the two threads, how the optional action is executed by the last arriving thread, and how timeout handling affects the flow.

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.

Javaconcurrencythread synchronizationCyclicBarrierJDK1.5
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
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.