What is CyclicBarrier inward Java
CyclicBarrier inward Java is a synchronizer introduced inward JDK v on java.util.Concurrent bundle along alongside other concurrent utility similar Counting Semaphore, BlockingQueue, ConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which nosotros convey seen inward the finally article What is CountDownLatch inward Java in addition to allows multiple threads to hold back for each other (barrier) earlier proceeding. The divergence betwixt CountDownLatch in addition to CyclicBarrier is an besides really popular multi-threading interview question inward Java. CyclicBarrier is a natural requirement for a concurrent programme because it tin live used to perform concluding business office of the delineate of piece of work i time private tasks are completed. All threads which wait for each other to accomplish barrier are called parties, CyclicBarrier is initialized alongside a pose out of parties to hold back in addition to threads hold back for each other past times calling CyclicBarrier.await() method which is a blocking method inward Java in addition to blocks until all Thread or parties telephone yell upwards await(). In full general calling await() is yell out that Thread is waiting on the barrier. await() is a blocking telephone yell upwards precisely tin live timed out or Interrupted past times other thread. In this Java concurrency tutorial, nosotros volition run into What is CyclicBarrier inward Java and an instance of CyclicBarrier on which 3 Threads volition hold back for each other earlier proceeding further.
Difference betwixt CountDownLatch in addition to CyclicBarrier inward Java
In our last article, nosotros convey to run into how CountDownLatch tin live used to implement multiple threads waiting for each other. If you lot hold back at CyclicBarrier it besides the does the same affair precisely at that topographic point is dissimilar you lot can non reuse CountDownLatch i time the count reaches null land you lot tin reuse CyclicBarrier past times calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is a adept for onetime events similar application start-up fourth dimension in addition to CyclicBarrier tin live used to inward instance of the recurrent lawsuit e.g. concurrently calculating a solution of the big occupation etc. If you lot similar to acquire to a greater extent than nearly threading in addition to concurrency inward Java you lot tin besides banking concern tally my post on When to role Volatile variable inward Java and How Synchronization industrial plant inward Java.
CyclicBarrier inward Java – Example
thread started their execution from that point. Its much clear alongside the output of next instance of CyclicBarrier inward Java:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java programme to demonstrate how to role CyclicBarrier inward Java. CyclicBarrier is a
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java programme to demonstrate how to role CyclicBarrier inward Java. CyclicBarrier is a
* novel Concurrency Utility added inward Java v Concurrent package.
*
* @author Javin Paul
*/
public class CyclicBarrierExample {
//Runnable delineate of piece of work for each thread
private static class Task implements Runnable {
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (InterruptedException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (BrokenBarrierException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) {
//creating CyclicBarrier alongside 3 parties i.e. 3 Threads needs to telephone yell upwards await()
final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
@Override
public void run(){
//This delineate of piece of work volition live executed i time all thread reaches barrier
System.out.println("All parties are arrived at barrier, lets play");
}
});
//starting each of thread
Thread t1 = new Thread(new Task(cb), "Thread 1");
Thread t2 = new Thread(new Task(cb), "Thread 2");
Thread t3 = new Thread(new Task(cb), "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
Output:
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All parties convey arrived at barrier, lets play
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier
* @author Javin Paul
*/
public class CyclicBarrierExample {
//Runnable delineate of piece of work for each thread
private static class Task implements Runnable {
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
barrier.await();
System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
} catch (InterruptedException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (BrokenBarrierException ex) {
Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) {
//creating CyclicBarrier alongside 3 parties i.e. 3 Threads needs to telephone yell upwards await()
final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
@Override
public void run(){
//This delineate of piece of work volition live executed i time all thread reaches barrier
System.out.println("All parties are arrived at barrier, lets play");
}
});
//starting each of thread
Thread t1 = new Thread(new Task(cb), "Thread 1");
Thread t2 = new Thread(new Task(cb), "Thread 2");
Thread t3 = new Thread(new Task(cb), "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
Output:
Thread 1 is waiting on barrier
Thread 3 is waiting on barrier
Thread 2 is waiting on barrier
All parties convey arrived at barrier, lets play
Thread 3 has crossed the barrier
Thread 1 has crossed the barrier
Thread 2 has crossed the barrier
When to role CyclicBarrier inward Java
Given the nature of CyclicBarrier it tin live really handy to implement map trim back form of delineate of piece of work similar to fork-join framework of Java 7, where a big delineate of piece of work is broker downwardly into smaller pieces in addition to to consummate the delineate of piece of work you lot demand output from private pocket-size delineate of piece of work e.g. to count population of Republic of Republic of India you lot tin convey four threads which count population from North, South, East, in addition to West in addition to i time consummate they tin hold back for each other, When finally thread completed their task, Main thread or whatsoever other thread tin add together effect from each zone in addition to impress total population. You tin role CyclicBarrier inward Java :
1) To implement multi actor game which tin non start out until all actor has joined.
2) Perform lengthy calculation past times breaking it into smaller private tasks, In general, to implement Map trim back technique.
Important indicate of CyclicBarrier inward Java
1. CyclicBarrier tin perform a completion delineate of piece of work i time all thread reaches to the barrier, This tin live provided land creating CyclicBarrier.
2. If CyclicBarrier is initialized alongside 3 parties agency 3 thread needs to telephone yell upwards await method to suspension the barrier.
3. The thread volition block on await() until all parties accomplish to the barrier, unopen to other thread interrupt or await timed out.
4. If unopen to other thread interrupts the thread which is waiting on barrier it volition throw BrokernBarrierException equally shown below:
java.util.concurrent.BrokenBarrierException
at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
5.CyclicBarrier.reset() pose Barrier on its initial state, other thread which is waiting or non however reached barrier volition destination alongside java.util.concurrent.BrokenBarrierException.
That's all on What is CyclicBarrier inward Java When to role CyclicBarrier inward Java in addition to a Simple Example of How to role CyclicBarrier inward Java . We convey besides seen the divergence betwixt CountDownLatch in addition to CyclicBarrier inward Java in addition to got unopen to thought where nosotros tin role CyclicBarrier inward Java Concurrent code.
Further Learning
Multithreading in addition to Parallel Computing inward Java
Java Concurrency inward Practice - The Book
Why to hold back in addition to notify methods are declared inward Object class