How does CyclicBarrier behave in multithreaded code?

CyclicBarrier is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point before proceeding. This is particularly useful in scenarios where multiple threads need to coordinate their progress, such as in simulations, parallel computations, or any other type of concurrent programming.

When the threads reach the barrier, they are released all at once, allowing them to continue their execution in a coordinated fashion. If a thread arrives at the barrier and there are still other threads that have not yet reached it, that thread will wait until the others arrive.

It's important to note that the barrier can be reset after all threads have crossed it, allowing it to be reused. However, exceptions can occur if one of the waiting threads is interrupted or times out, which can lead to the barrier being tripped and the threads being released prematurely.

Example:


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

public class CyclicBarrierExample {
    private static final int NUMBER_OF_THREADS = 3;

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_THREADS, () -> {
            System.out.println("All threads reached the barrier, proceeding...");
        });

        for (int i = 0; i < NUMBER_OF_THREADS; i++) {
            final int threadId = i;
            new Thread(() -> {
                try {
                    System.out.println("Thread " + threadId + " is doing some work...");
                    Thread.sleep((long) (Math.random() * 1000)); // simulate work
                    System.out.println("Thread " + threadId + " is waiting at the barrier");
                    barrier.await(); // wait for others at the barrier
                    System.out.println("Thread " + threadId + " has crossed the barrier");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
    

CyclicBarrier multithreading thread synchronization concurrent programming Java concurrency