Saturday, July 21, 2018

What do you know about CyclicBarrier in java?

Problem statement: Write a cab transport service where passengers will come one by one and join the queue but they can't board the cab or cab won't move until there are 3 passengers waiting in the queue.
  1. CyclicBarrier is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. Using this we can synchronised the threads which are processing through some algorithm
  5.  Using this we can make threads wait at a point of code until specific number of threads have reached that point of code.Threads will be ordered to wait on call of await() method
  6. CyclicBarrier can be instantiated as: CyclicBarrier obj = new CyclicBarrier(n) where n is an interger and also that specific number.
[1]:

import java.util.concurrent.CyclicBarrier;

public class CabBooking {
    public static void main(String args[]) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        Thread t1 = new Thread(new CabService(cyclicBarrier));
        t1.setName("Passenger-1");
        t1.start();
        Thread.sleep(5000);

        Thread t2 = new Thread(new CabService(cyclicBarrier));
        t2.setName("Passenger=-2");
        t2.start();
        Thread.sleep(5000);

        Thread t3 = new Thread(new CabService(cyclicBarrier));
        t3.setName("Passenger-3");
        t3.start();
        Thread.sleep(5000);
    }
}
[2]:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CabService implements Runnable {
    CyclicBarrier cyclicBarrier;
    public CabService(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        try {
            System.out.println("++++++ " + Thread.currentThread().getName() + " has arrived");
            try {
                cyclicBarrier.await();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("****** " + Thread.currentThread().getName() + " is going to board the cab");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Output:
++++++ Passenger-1 has arrived
++++++ Passenger=-2 has arrived
++++++ Passenger-3 has arrived
****** Passenger-3 is going to board the cab
****** Passenger-1 is going to board the cab
****** Passenger=-2 is going to board the cab
ref: click for oracle doc

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...