CyclicBarrier

This Article is part of Series of Articles on Java 8 Concurrency Tutorial.
In this article, we’ll focus on a the concept of CyclicBarrier in the Java language.

CyclicBarrier

CyclicBarrier 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.

CyclicBarrier are Similar to CountDownLatch but CyclicBarrier provide some additional features like
Reseting CyclicBarrier & Supports an optional Runnable command that is run once per barrier point.

CyclicBarrier Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class CyclicBarrierWorker implements Runnable
{
private CyclicBarrier cyclicBarrier;
private int workerId;
private Random random;
public CyclicBarrierWorker(CyclicBarrier cyclicBarrier ,int id) {
this.cyclicBarrier=cyclicBarrier;
this.workerId=id;
this.random = new Random();

}
@Override
public void run() {
System.out.println("Starting worker ID " + this.workerId);
try {
Thread.sleep(random.nextInt(4000));
System.out.println("Worker " + workerId + " Completed it's work, Reducing count of cyclicBarrier " );
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public class CyclicBarrierExample {
public static void main(String[] args) {

CyclicBarrier cyclicBarrier = new CyclicBarrier(5, ()->System.out.println("Barrier point reach ::: All Task Completed"));
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
IntStream.range(1,6)
.forEach(cnt->{newFixedThreadPool.submit(new CyclicBarrierWorker(cyclicBarrier, cnt));
});
System.out.println("All Task Submited");
newFixedThreadPool.shutdown();
}
}
}

Key Points

CyclicBarrier(int parties, Runnable barrierAction) :
Creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and which will execute the given barrier action when the barrier is tripped, performed by the last thread entering the barrier.

getNumberWaiting()
Returns the number of parties currently waiting at the barrier.

reset
Resets the barrier to its initial state.

Share Comments