Multithreading: CyclicBarrier lets a fixed set of threads rendezvous

A CyclicBarrier constructed for N parties makes await() block each of them until all N have arrived, then releases everyone together. Because the barrier can be reused for another phase, the point is that all participants cross it as a group.

Code
CyclicBarrier barrier = new CyclicBarrier(2);
List<String> log = Collections.synchronizedList(new ArrayList<>());
Runnable task = () -> {
    try {
        log.add("arrived");
        barrier.await();
        log.add("passed");
    } catch (Exception e) { }
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
long arrivedCount = log.stream().filter(s -> s.equals("arrived")).count();
long passedCount = log.stream().filter(s -> s.equals("passed")).count();
System.out.println("Both threads arrived: " + (arrivedCount == 2));
System.out.println("Both threads passed the barrier: " + (passedCount == 2));
Output
Both threads arrived: true
Both threads passed the barrier: true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms