What is CyclicBarrier in Java
2016-04-13 11:31
429 查看
转自:http://javarevisited.blogspot.hk/2012/07/cyclicbarrier-example-java-5-concurrency-tutorial.html
What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like
Counting Semaphore,
BlockingQueue,
ConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which we have seen in last article
What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. Difference between CountDownLatch and CyclicBarrier is a also very
popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for concurrent program because it can be used to perform final part of task once individual tasks are completed. All threads which
wait for each other to reach barrier are called parties, CyclicBarrier is initialized with number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is a
blocking method in Java and blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on barrier. await() is a blocking call but can be timed out or Interrupted by other thread. In this Java concurrency
tutorial we will see What is CyclicBarrier in Java and an example of CyclicBarrier on which three Threads will wait for each other before proceeding further.
Difference between CountDownLatch and CyclicBarrier in Java
In our
last article we have see how CountDownLatch can be used to implement multiple
threads waiting for each other. If you look at CyclicBarrier it also the does the same thing but there is a different you
can not reuse CountDownLatch once count reaches zero while you can reuse CyclicBarrier by calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is good for one time event like application start-up
time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently calculating solution of big problem etc. If you like to learn more about threading and concurrency in Java you can also check my post on
When to use Volatile variable in Java and
How Synchronization works in Java.
Now
we know what is CyclicBarrier in Java and it's time to see example of CyclicBarrier in Java. Here is a simple example of CyclicBarrier in Java on which we initialize CyclicBarrier with 3 parties, means in order to cross barrier, 3 thread needs to call await()
method. each thread calls await method in short duration but they don't proceed until all 3 threads reached barrier, once all thread reach barrier, barrier gets broker and each
thread started there execution from that point. Its much clear with the output of following example of CyclicBarrier in Java:
import
java.util.concurrent.BrokenBarrierException;
import
java.util.concurrent.CyclicBarrier;
import
java.util.logging.Level;
import
java.util.logging.Logger;
/**
* Java program to demonstrate how to use CyclicBarrier in Java. CyclicBarrier is a
* new Concurrency Utility added in Java 5 Concurrent package.
*
* @author Javin Paul
*/
public class CyclicBarrierExample
{
//Runnable task 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 with 3 parties i.e. 3 Threads needs to call await()
final CyclicBarrier cb =
new CyclicBarrier(3,
new Runnable(){
@Override
public void run(){
//This task will be executed once 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 are 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 use CyclicBarrier in Java
Given the nature of CyclicBarrier it can be very handy to implement map reduce kind of task similar to
fork-join framework of Java 7, where a big task is broker down into smaller pieces and to complete the task you need output from individual small task e.g. to count population of India you can have 4 threads which counts population from North, South, East
and West and once complete they can wait for each other, When last thread completed there task, Main thread or any other thread can add result from each zone and print total population. You can use CyclicBarrier in Java :
1) To implement multi player game which can not begin until all player has joined.
2) Perform lengthy calculation by breaking it into smaller individual tasks, In general to implement Map reduce technique.
Important point of CyclicBarrier in Java
1. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while creating CyclicBarrier.
2. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
3.
Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out.
4. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as shown below:
java.util.concurrent.BrokenBarrierException
at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
5.CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException.
That's all on What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to use CyclicBarrier in Java . We have also seen difference between CountDownLatch and CyclicBarrier in Java and got some idea where we can use
CyclicBarrier in Java Concurrent code.
Other Java thread and concurrency tutorials from Javarevisited Blog
Why wait and notify methods are declare in Object class
How to aovid deadlock in Java by carefully coding
What is race condition in concurrent Java program
How to write thread-safe class in Java
Difference between Runnable and Thread in Java
Read more: http://javarevisited.blogspot.com/2012/07/cyclicbarrier-example-java-5-concurrency-tutorial.html#ixzz45fpbp1Sl
What is CyclicBarrier in Java
CyclicBarrier in Java is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utility like
Counting Semaphore,
BlockingQueue,
ConcurrentHashMap etc. CyclicBarrier is similar to CountDownLatch which we have seen in last article
What is CountDownLatch in Java and allows multiple threads to wait for each other (barrier) before proceeding. Difference between CountDownLatch and CyclicBarrier is a also very
popular multi-threading interview question in Java. CyclicBarrier is a natural requirement for concurrent program because it can be used to perform final part of task once individual tasks are completed. All threads which
wait for each other to reach barrier are called parties, CyclicBarrier is initialized with number of parties to be wait and threads wait for each other by calling CyclicBarrier.await() method which is a
blocking method in Java and blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on barrier. await() is a blocking call but can be timed out or Interrupted by other thread. In this Java concurrency
tutorial we will see What is CyclicBarrier in Java and an example of CyclicBarrier on which three Threads will wait for each other before proceeding further.
Difference between CountDownLatch and CyclicBarrier in Java
In our
last article we have see how CountDownLatch can be used to implement multiple
threads waiting for each other. If you look at CyclicBarrier it also the does the same thing but there is a different you
can not reuse CountDownLatch once count reaches zero while you can reuse CyclicBarrier by calling reset() method which resets Barrier to its initial State. What it implies that CountDownLatch is good for one time event like application start-up
time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently calculating solution of big problem etc. If you like to learn more about threading and concurrency in Java you can also check my post on
When to use Volatile variable in Java and
How Synchronization works in Java.
CyclicBarrier in Java – Example
Now
we know what is CyclicBarrier in Java and it's time to see example of CyclicBarrier in Java. Here is a simple example of CyclicBarrier in Java on which we initialize CyclicBarrier with 3 parties, means in order to cross barrier, 3 thread needs to call await()
method. each thread calls await method in short duration but they don't proceed until all 3 threads reached barrier, once all thread reach barrier, barrier gets broker and each
thread started there execution from that point. Its much clear with the output of following example of CyclicBarrier in Java:
import
java.util.concurrent.BrokenBarrierException;
import
java.util.concurrent.CyclicBarrier;
import
java.util.logging.Level;
import
java.util.logging.Logger;
/**
* Java program to demonstrate how to use CyclicBarrier in Java. CyclicBarrier is a
* new Concurrency Utility added in Java 5 Concurrent package.
*
* @author Javin Paul
*/
public class CyclicBarrierExample
{
//Runnable task 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 with 3 parties i.e. 3 Threads needs to call await()
final CyclicBarrier cb =
new CyclicBarrier(3,
new Runnable(){
@Override
public void run(){
//This task will be executed once 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 are 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 use CyclicBarrier in Java
Given the nature of CyclicBarrier it can be very handy to implement map reduce kind of task similar to
fork-join framework of Java 7, where a big task is broker down into smaller pieces and to complete the task you need output from individual small task e.g. to count population of India you can have 4 threads which counts population from North, South, East
and West and once complete they can wait for each other, When last thread completed there task, Main thread or any other thread can add result from each zone and print total population. You can use CyclicBarrier in Java :
1) To implement multi player game which can not begin until all player has joined.
2) Perform lengthy calculation by breaking it into smaller individual tasks, In general to implement Map reduce technique.
Important point of CyclicBarrier in Java
1. CyclicBarrier can perform a completion task once all thread reaches to barrier, This can be provided while creating CyclicBarrier.
2. If CyclicBarrier is initialized with 3 parties means 3 thread needs to call await method to break the barrier.
3.
Thread will block on await() until all parties reaches to barrier, another thread interrupt or await timed out.
4. If another thread interrupt the thread which is waiting on barrier it will throw BrokernBarrierException as shown below:
java.util.concurrent.BrokenBarrierException
at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
5.CyclicBarrier.reset() put Barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException.
That's all on What is CyclicBarrier in Java , When to use CyclicBarrier in Java and a Simple Example of How to use CyclicBarrier in Java . We have also seen difference between CountDownLatch and CyclicBarrier in Java and got some idea where we can use
CyclicBarrier in Java Concurrent code.
Other Java thread and concurrency tutorials from Javarevisited Blog
Why wait and notify methods are declare in Object class
How to aovid deadlock in Java by carefully coding
What is race condition in concurrent Java program
How to write thread-safe class in Java
Difference between Runnable and Thread in Java
Read more: http://javarevisited.blogspot.com/2012/07/cyclicbarrier-example-java-5-concurrency-tutorial.html#ixzz45fpbp1Sl
相关文章推荐
- Java NIO使用及原理分析 (一)
- java 常用23中设计模式
- java并发:线程池、饱和策略、定制、扩展
- What is CountDownLatch in Java
- Spring框架下的单元测试方法
- Spring+Struts+Hibernate框架详解
- Java ClassLoader基础及加载不同依赖 Jar 中的公共类
- Java文件操作
- [Java] 匿名内部类
- LeetCode Power of Three JAVA
- [Java] 内部类的用法
- Java 并发专题 :FutureTask 实现预加载数据 在线看电子书、浏览器浏览网页等
- Java中,当表单含有文件上传时,提交数据的如何读取(感谢作者分享)
- java notify() 线程协作
- 用java写简单的web服务器,在宿舍提供视频播放
- org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
- 深入研究java.lang.Runtime类
- Java学习·eclipse换主题颜色
- Spring4.1 cache 应用
- Spring4搭建+REST在Spring上搭建