Java CyclicBarrier synchronize tasks in a common point

Introduction

The Java concurrency API CyclicBarrier class allows the synchronization of two or more threads in a determined point.

The CyclicBarrier class is constructed with an integer number.

The number is is the number of threads that will be synchronized in a determined point.

When one of those threads arrives to the determined point, it calls the await() method to wait for the other threads.

The CyclicBarrier class blocks the thread that is sleeping until the other threads arrive.

When the last thread calls the await() method of the CyclicBarrier class, CyclicBarrier class wakes up all the threads that were waiting and continues with its job.

The CyclicBarrier class can accept an additional Runnable object as an initialization parameter.

The CyclicBarrier class executes this object as a thread when all the threads have arrived to the common point.



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

public class Main {
  public static void main(String[] args) {
    int PARTICIPANTS = 5;
    Merger grouper = new Merger();

    CyclicBarrier barrier = new CyclicBarrier(PARTICIPANTS, grouper);
    Finder searchers[] = new Finder[PARTICIPANTS];
    for (int i = 0; i < PARTICIPANTS; i++) {
      searchers[i] = new Finder(barrier);
      Thread thread = new Thread(searchers[i]);
      thread.start();/*from   w  w  w  .  j  a  va 2s.c om*/
    }
    System.out.printf("The main thread has finished.\n");
  }
}

class Merger implements Runnable {

  public Merger() {

  }
  @Override
  public void run() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Merger:");
  }
}

class Finder implements Runnable {
  private int firstRow;
  private int lastRow;
  private final CyclicBarrier barrier;
  public Finder(CyclicBarrier barrier) {
    this.barrier = barrier;
  }


  @Override
  public void run() {
    System.out.printf("%s: Processing lines from %d to %d.\n", Thread.currentThread().getName(), firstRow, lastRow);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Finding:");

    System.out.printf("%s: Lines processed.\n", Thread.currentThread().getName());
    try {
      barrier.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (BrokenBarrierException e) {
      e.printStackTrace();
    }
  }

}

class DataSet {

  public DataSet() {
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("working:");
  }
}



PreviousNext

Related