Java CyclicBarrier

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.

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.

more information could be found at CyclicBarrier in Oracle

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

CyclicBarrier is a natural requirement for a concurrent program because it can be used to perform final part of the task once individual tasks  are completed. All threads which wait for each other to reach barrier are called parties, CyclicBarrier is initialized with a number of parties to wait and threads wait for each other by calling CyclicBarrier.await() method which is a blocking method in Java and  blocks until all Thread or parties call await(). In general calling await() is shout out that Thread is waiting on the barrier. await() is a blocking call but can be timed out or Interrupted by other thread.

The difference between CountDownLatch and CyclicBarrier: we have seen how CountDownLatch can be used to implement multiple threads waiting for each other. The CyclicBarrier also the does the same thing but  CountDownLatch cannot be not reused once the count reaches zero while CyclicBarrier can be reused by calling reset() method which resets Barrier to its initial State. Therefore the CountDownLatch is a good for one-time events like application start-up time but CyclicBarrier can be used in case of the recurrent event e.g. concurrently calculating a solution of the big problem etc.


Create a model class

Create a class which holds the list of Person object

Create below three different service classes to fetch data from different sources for Person object.

Fetch data from file

Fetch data from database

Fetch data from REST service

Create below class to start different services on separate threads to fetch data and once all data are available then start the main thread

Run the above class, you will get below output

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.