CyclicBarrier

The CyclicBarrier class in Java is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. Once all threads have reached the barrier point, they are all released to continue their execution. CyclicBarrier is reusable after the barrier is tripped, which makes it suitable for iterative processes where the barrier needs to be reused multiple times.

Key Features

  • Parties: The number of threads that must invoke await() before the barrier is tripped.
  • Runnable Barrier Action: An optional Runnable that is executed once the last thread arrives at the barrier. This action is executed in one of the threads that reached the barrier.
  • Cyclic: The barrier is reusable, hence the name “cyclic.”

Example Usage

Here’s an example demonstrating the use of CyclicBarrier:

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

public class CyclicBarrierExample {
    private static final int NUMBER_OF_THREADS = 3;
    private static final CyclicBarrier BARRIER = new CyclicBarrier(NUMBER_OF_THREADS, () -> {
        System.out.println("All parties have arrived at the barrier, let's proceed");
    });

    public static void main(String[] args) {
        for (int i = 0; i < NUMBER_OF_THREADS; i++) {
            new Thread(new Task()).start();
        }
    }

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is doing some work");
                Thread.sleep(1000); // Simulate work
                System.out.println(Thread.currentThread().getName() + " is waiting at the barrier");
                BARRIER.await(); // Wait at the barrier
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException | BrokenBarrierException e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
        }
    }
}

Explanation

  1. Define the CyclicBarrier:
  • The CyclicBarrier is initialized with the number of threads that must reach the barrier (NUMBER_OF_THREADS), and an optional barrier action which is a Runnable that runs once all threads have reached the barrier.
   private static final CyclicBarrier BARRIER = new CyclicBarrier(NUMBER_OF_THREADS, () -> {
       System.out.println("All parties have arrived at the barrier, let's proceed");
   });
  1. Create and Start Threads:
  • In the main method, a loop starts the specified number of threads, each running an instance of Task.
   for (int i = 0; i < NUMBER_OF_THREADS; i++) {
       new Thread(new Task()).start();
   }
  1. Task Implementation:
  • Each thread simulates some work by sleeping for a while, then calls BARRIER.await() to wait at the barrier.
  • When the specified number of threads have called await(), they all proceed and execute the barrier action if provided.
   static class Task implements Runnable {
       @Override
       public void run() {
           try {
               System.out.println(Thread.currentThread().getName() + " is doing some work");
               Thread.sleep(1000); // Simulate work
               System.out.println(Thread.currentThread().getName() + " is waiting at the barrier");
               BARRIER.await(); // Wait at the barrier
               System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
           } catch (InterruptedException | BrokenBarrierException e) {
               Thread.currentThread().interrupt();
               e.printStackTrace();
           }
       }
   }

Key Points

  • Reusability: The barrier can be reused after the threads have crossed it. This makes CyclicBarrier suitable for iterative processes like parallel computing.
  • Barrier Action: An optional Runnable can be executed once all threads reach the barrier, providing a way to perform a collective action before the threads proceed.
  • Exception Handling:
  • InterruptedException: Thrown if the current thread is interrupted while waiting.
  • BrokenBarrierException: Thrown if another thread was interrupted or timed out while the current thread was waiting.

Advanced Usage

Resetting the Barrier:
The barrier can be reset manually using the reset() method. This will move the barrier back to its initial state, but any threads currently waiting will receive a BrokenBarrierException.

Timed Wait:
You can specify a timeout when calling await(), which will throw a TimeoutException if the barrier is not tripped within the specified time.

BARRIER.await(2, TimeUnit.SECONDS);

Summary

CyclicBarrier is a powerful synchronization tool in Java that enables a fixed number of threads to wait for each other at a common barrier point. It supports reusability and can execute a barrier action when all threads reach the barrier, making it suitable for a variety of concurrent programming tasks. Understanding how to use CyclicBarrier effectively can greatly enhance your ability to handle complex synchronization scenarios in Java.

1 thought on “CyclicBarrier”

  1. Tell me, the wallet Electrum doesn’t accept the private key 27bd43c2e9354 from 0x36011bD1E6F4aa3BB48f03305eF2f5F66bF034A8 address, what should I do?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.