Week 81 — What is the purpose of the `CyclicBarrier` class and how can it be used?

Question of the Week #81
What is the purpose of the CyclicBarrier class and how can it be used?
4 Replies
Eric McIntyre
Eric McIntyre5mo ago
CyclicBarrier class is used to make threads wait for each other. When multiple threads have some subtask to do, and output of these subtasks needed to be combined as a final output, then the CyclicBarrier class is used.
Submission from rakin235
Eric McIntyre
Eric McIntyre5mo ago
CyclicBarier is a synchronizer, it means allowing the set of threads to wait each other to reach a common execution point. For example, we have lots of thread and these thread will have a numbers, and we need to show each thread in a logical sort of order, otherwise we could not able to understand which thread is coming first or last. And it will be barier to another thread in this way. We can also calledd a barrier for CyclicBarier class
Submission from mufa__
Eric McIntyre
Eric McIntyre4w ago
Barriers allow threads to await on it until a certain point where the barrier is opened and all threads waiting on it are released and can continue execution. A CyclicBarrier opens as soon as a specified number of threads are waiting on it.
CyclicBarrier barrier = new CyclicBarrier(10);//create a barrier that is broken when 10 threads wait on it
for(int i=0; i<10; i++){
final int threadId = i;
new Thread(()->{
try{
System.out.println("thread "+ threadId +" is waiting...");
barrier.await();
System.out.println("thread "+ threadId +" is continuing...");
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}catch(BrokenBarrierException e){
System.out.println("barrier has been broken in an unexpected way");
}
}).start();
}
CyclicBarrier barrier = new CyclicBarrier(10);//create a barrier that is broken when 10 threads wait on it
for(int i=0; i<10; i++){
final int threadId = i;
new Thread(()->{
try{
System.out.println("thread "+ threadId +" is waiting...");
barrier.await();
System.out.println("thread "+ threadId +" is continuing...");
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}catch(BrokenBarrierException e){
System.out.println("barrier has been broken in an unexpected way");
}
}).start();
}
This should print thread N is waiting... for N with different Ns from 0 to (excluding) 10 before any thread N is continuing is printed. Then, all thread N is continuing messages are printed. What makes CyclicBarrier different from other barriers is that it can be reused by threads calling await() again after it has been opened. In this case, it starts again and reopens when the specified number of threads are waiting on that barrier once more.
Want results from more Discord servers?
Add your server