When to reset CyclicBarrier in java multithreading

半腔热情 提交于 2020-03-13 06:05:30

问题


I was reading CyclicBarrier in the following link http://java-latte.blogspot.in/2013/10/cyclicbarrier-in-java-concurrency.html.

In the example 1, CyclicRaceDemo.java main method, CyclicBarrier is being reused without calling reset method.

I ran the example and it worked fine. So, I am wondering what's the use of reset method. When should it be called? Or do we need to call it at all?


回答1:


A CyclicBarrier is cyclic because it can be reused without resetting. From the Javadoc

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

So in normal usage, once all the threads are collected and the barrier is broken, it resets itself and can be used again.

From the Javadoc for reset()

Resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a BrokenBarrierException. Note that resets after a breakage has occurred for other reasons can be complicated to carry out; threads need to re-synchronize in some other way, and choose one to perform the reset. It may be preferable to instead create a new barrier for subsequent use.

So reset causes any currently waiting threads to throw a BrokenBarrierException and wake immediately. reset is used when you want to "break" the barrier.

Note also the caveat - once the threads have been awoken forcibly it's tricky to synchronize them again.

TL;DR: you should never need to use reset() in normal circumstances.



来源:https://stackoverflow.com/questions/24104642/when-to-reset-cyclicbarrier-in-java-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!