Sunday, June 18, 2017

CyclicBarrier



What does CyclicBarrier do ?

Await will suspend itself until N number of threads have invoked await on the barrier. So if you define new CyclicBarrier(3) than once 3 threads invoke await the barrier will allow threads to continue.

Basically it is used to Synchronize tasks in a common point

The CyclicBarrier class is initialized with an integer number, which 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. When the thread calls that method, 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, it wakes up all the threads that were waiting and continues with its job.

One interesting advantage of the CyclicBarrier class is that you can pass an additional
Runnable object as an initialization parameter, and the CyclicBarrier class executes this
object as a thread when all the threads have arrived to the common point. This characteristic
makes this class adequate for the parallelization of tasks using the divide and conquer
programming technique.
Example : Suppose T1 prints 1,3,5 etc and T2 prints 2,5,6 etc and T3 prints 3,6,9 how does main print 1,2,3,4,5,6,


class ThreadTest {
 private CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
      @Override
     public void run() {
           System.out.println(oddNumberGenerator.result);
         System.out.println(evenNumberGenerator.result);
     }
 });

 private NumberGenerator oddNumberGenerator = new NumberGenerator(1,11,2);
 private NumberGenerator evenNumberGenerator = new NumberGenerator(2,10,2);

 public void generateSeries(){
     oddNumberGenerator.generateNumbers();
     evenNumberGenerator.generateNumbers();
 }

 class NumberGenerator {
     private Thread thread;
     private int result;

     private NumberGenerator(final int initialValue, final int maxValue,final int stepSize) {
         this.thread = new Thread(new Runnable() {
             @Override
             public void run() {
                 for (int i = initialValue; i <= maxValue; i = i + stepSize) {
                     try {
                         result = i;
                         cyclicBarrier.await();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     } catch (BrokenBarrierException e) {
                         e.printStackTrace();
                     }
     }
             }
         });
     }
     public void generateNumbers() {
          thread.start();
     }
 }
 main(String[] args){
     new ThreadTest().generateSeries();
 }
}
ok

No comments: