Interview Focused: What is CyclicBarrier in Java? Only 10 Points.
1. Java.util.Concurrent.CyclicBarrier is a synchronization utility that allows a set of threads to wait for each other to reach a common barrier point.
2. 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.
3. One difference between CountdownLatch and CyclicBarrier is CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.
4. In CyclicBarrier all threads arrive and then wait for the last to arrive.
5. A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.
6.The CyclicBarrier uses an all-or-none breakage model for failed synchronization attempts: If a thread leaves a barrier point prematurely because of interruption, failure, or timeout, all other threads waiting at that barrier point will also leave abnormally via BrokenBarrierException (or InterruptedException if they too were interrupted at about the same time).
7. To create CyclicBarrier object, provide the number of Threads to wait to its constructor
- CyclicBarrier barrier = new CyclicBarrier(5, barrierAction);
- //Or
- CyclicBarrier barrier = new CyclicBarrier(5, Runnable);
To make a Thread wait,
- barrier.await();
8. reset() : Resets the barrier to its initial state.
9. CyclicBarrier can be used for map reduce kind of task similar to fork-join framework of Java 7, where a task is broker down into smaller tasks and different threads complete these tasks and contribute to a common pool of results which are brought together by the last Runnable thread which is provided to CyclicBarrier contructor to give the final result.
10. The popular download manager IDM is a good example of CyclicBarrier implemetation, where threads download part of file and the final thread brings together all the parts to contruct the complete file.
can u provide source code
ReplyDelete