JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Java CyclicBarrier Example

CyclicBarrier is synchronized aid which allows set of threads to wait for each other at common barrier points.It is called cyclic because it can be reused once waiting threads are released.
For example:
Let’s say you have 3 threads, you want all threads(terms as parties) to reach a common point and then only they should proceed ahead.In this case, you can use CyclicBarrier with 3 parties and once 3 threads reach a common point, you can call an event which will implement runnable interface and Three threads will be released.

Difference between CountDownLatch and CyclicBarrier

The major difference between CyclicBarrier and CoundDownLatch is that CyclicBarrier can be reused.You can not use CountDownLatch once used. You can read more differences between CountDownLatch and CyclicBarrier.

Java CyclicBarrier example:

Step 1: Create a file named “RunnableTask.java” in package .src.org.arpit.java2blog
This is a Runnable task which will be executed by each thread.
Step 2: Create a file named “CyclicBarrierFinishEvent.java” in package .src.org.arpit.java2blog
CyclicBarrierFinishEvent will be called when 3 parties (Initialized with CyclicBarrier object) reaches to a common barrier point.
Step 3: Create a file named “CyclicBarrierMain.java” in package .src.org.arpit.java2blog
Let’s run the program, then we will understand the output:
Thread-1 is waiting for 2 other threads to reach common barrier point
Thread-2 is waiting for 1 other threads to reach common barrier point
Thread-3 is waiting for 0 other threads to reach common barrier point
As 3 threads have reached common barrier point ,CyclicBarrrierFinishEvent has been triggered
You can update shared variables if any
As 3 threads have reached common barrier point Thread-3 has been released
As 3 threads have reached common barrier point Thread-1 has been released
As 3 threads have reached common barrier point Thread-2 has been released
Thread-4 is waiting for 2 other threads to reach common barrier point
Thread-5 is waiting for 1 other threads to reach common barrier point
Thread-6 is waiting for 0 other threads to reach common barrier point
As 3 threads have reached common barrier point ,CyclicBarrrierFinishEvent has been triggered
You can update shared variables if any
As 3 threads have reached common barrier point Thread-6 has been released
As 3 threads have reached common barrier point Thread-4 has been released
As 3 threads have reached common barrier point Thread-5 has been released
Below diagram will make you understand output better.
CyclicBarrier Output
That’s all about Java CyclicBarrier example.

.