When to reset CyclicBarrier in java multithreading

前端 未结 1 1568
后悔当初
后悔当初 2021-01-02 03:14

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

In the example 1,

相关标签:
1条回答
  • 2021-01-02 03:37

    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.

    0 讨论(0)
提交回复
热议问题