CyclicBarrier is useful in situations where you want each thread in a set of threads to reach at specific execution point
before moving further.
How to implement?
CyclicBarrier constructor received two arguments.
No. of threads to reach the barrier. Minimum 1 is allowed here. Anything less than 1 will trigger IllegalArgumentException()
Optional runnable task to invoke, once all threads reach the barrier and before resuming threads blocked by barrier.
await() function is invoked in thread to make current thread wait until all other threads invoke await() i.e. reach the barrier or one of the
following situations occur
The last thread arrives
Some other thread interrupts the current thread
Some other thread interrupts one of the other waiting threads
Some other thread times out while waiting for barrier
Some other thread invokes reset on this barrier.
Example
Let’s make a simple program to demonstrate the behaviour of cyclic barrier. We create a CyclicBarrier which waits for await() method to
be invoked three times. In each thread, we wait for some random time and print data about thread. Finally, we print a message once each thread
reaches the barrier.
MyThread.java
Barrier Main class
Output
Repeating Cycle
Unlike CountDownLatch, CyclicBarrier is repeatable. We can again invoke await() of new threads and CyclicBarrier will trigger
completion tasks and release thread when a barrier is reached or any of above discussed situation occurs.
Modify the above example, add following code in BarrierApp.run()
Output for repeated cycle
Resetting Barrier
Calling reset on Barrier resets the barrier and throws BrokenBarrierException() if there are threads awaiting for barrier.
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.