---
title: Synchronizers In Java - CyclicBarrier
description: Synchronizers In Java - CyclicBarrier
---

[![e-Zest logo\_An accion lab company\_Colour](https://blog.e-zest.com/hubfs/images/Logos%20with%20Tagline/Corporate/SVG/e-Zest%20logo_An%20accion%20lab%20company_Colour.svg "e-Zest logo_An accion lab company_Colour")](https://www.e-zest.com/)

- [WORK](https://www.e-zest.com/our-work)
- [SERVICES](https://www.e-zest.com/our-services) 
    - [Product Engineering](https://www.e-zest.com/digital-product-engineering-services)
    - [Enterprise Data Services](https://www.e-zest.com/enterprise-data-services)
    - [Digital Commerce](https://www.e-zest.com/digital-commerce-services)
    - [Digital Operations](https://www.e-zest.com/digital-operations)
    - [Digital Consulting](https://www.e-zest.com/digital-transformation-consulting-services)
    - [Digital Experience Design](https://www.e-zest.com/digital-experience-design)
- [INSIGHTS](https://blog.e-zest.com/)
- [CAREERS](https://www.e-zest.com/careers)
- [ENTERPRISE DATA SERVICES](https://www.e-zest.com/enterprise-data-services)
- [GENERATIVE AI](https://www.e-zest.com/generative-ai)
- [Healthcare](https://healthcare.e-zest.com)
- [Contact Us](https://www.e-zest.com/contact-us)

- ![Elevating Product Engineering with AI and ML](https://blog.e-zest.com/hubfs/Elevating%20Product%20Engineering%20with%20AI%20and%20ML.jpg)

  [BLOGS](https://blog.e-zest.com)
  
  #### Elevating Product Engineering with AI and ML

  As technology evolves and customer choices broaden, there is an increasing ...

  [Read more](https://blog.e-zest.com/elevating-product-engineering-with-ai-and-ml)
- ![e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024](https://blog.e-zest.com/hubfs/e-Zest%20%E2%80%93%20An%20Accion%20Labs%20Company%20-%20Gets%20Recognition%20as%20a%20Contender%20in%20the%20ISG%20Provider%20LensTM%20Study%20on%20Digital%20Engineering%20Services%202024.jpg)

  [NEWS](https://blog.e-zest.com/news)
  
  #### e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024

  We are delighted to announce that e-Zest – An Accion Labs Company has been ...

  [Read more](https://blog.e-zest.com/news/e-zest-an-accion-labs-company-gets-recognition-as-a-contender-in-the-isg-provider-lens-study-on-digital-engineering-services-2024)
- ![e-Zest Solutions supports Digital Pune Mission](https://blog.e-zest.com/hubfs/blog-files/Digital%20Literacy%20Bus%20e-Zest.png)

  [CSR](https://blog.e-zest.com/csr)
  
  #### e-Zest Solutions supports Digital Pune Mission

  **Pune, India:** e-Zest Solutions, a leading digital technology innovation ...

  [Read more](https://blog.e-zest.com/csr/e-zest-solutions-supports-digital-pune-mission)

- [Work](https://www.e-zest.com/our-work)
- [Services](https://www.e-zest.com/our-services)
- [Insights](https://blog.e-zest.com)
- [Careers](https://www.e-zest.com/careers)
- [Enterprise Data](https://www.e-zest.com/enterprise-data-services)
- [Generative AI](https://www.e-zest.com/generative-ai)
- [Innovations](https://www.e-zest.com/innovations)
- [Healthcare](https://healthcare.e-zest.com)
- [About](https://www.e-zest.com/about-us)
- [Contact](https://www.e-zest.com/contact-us)

- [Blog](https://blog.e-zest.com/)
- [News](https://blog.e-zest.com/news)
- [CSR](https://blog.e-zest.com/csr)

- [![Linkedin Icon](https://blog.e-zest.com/hubfs/icons/linkedin_icon_white.svg)](https://www.linkedin.com/company/e-zest-solutions/)
- [![Twitter Icon](https://blog.e-zest.com/hubfs/twitter-logo-silhouette%20(5).svg)](https://twitter.com/ezest)
- [![Facebook Icon](https://blog.e-zest.com/hubfs/facebook-app-logo%20(4).svg)](https://www.facebook.com/61259256638)
- [![Instagram Icon](https://blog.e-zest.com/hubfs/instagram-logo%20(4).svg)](https://www.instagram.com/ezestsolutions/)
- [![Youtube Icon](https://blog.e-zest.com/hubfs/icons/youtube_icon_white.svg)](https://www.youtube.com/user/ezestcorporate)

[![Go to top icon](https://blog.e-zest.com/hubfs/AA%20Assets/top%20button.svg)](https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/#top)

Hit enter to search or ESC to close

Insights

e-Zest members share technology ideas to foster digital transformation.

- [Blog](https://blog.e-zest.com)
- [News](https://blog.e-zest.com/news)
- [Podcasts](https://www.e-zest.com/podcasts)
- [Healthcare](https://blog.e-zest.com/healthcare)
- [CSR](https://blog.e-zest.com/csr)
- [Whitepaper](https://blog.e-zest.com/whitepaper)
- [Playbook](https://blog.e-zest.com/playbook)
- [Media Kit](https://www.e-zest.com/media-kit)

# Synchronizers In Java - CyclicBarrier

[Madhura Oak](https://blog.e-zest.com/author/madhura-oak)  Dec 03, 2012

[CyclicBarrier](https://blog.e-zest.com/topic/cyclicbarrier) [Java](https://blog.e-zest.com/topic/java) [Multithreading](https://blog.e-zest.com/topic/multithreading) [Concurrency API](https://blog.e-zest.com/topic/concurrency-api) [Technology](https://blog.e-zest.com/topic/technology) [synchronizers](https://blog.e-zest.com/topic/synchronizers)

- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/&title=&summary=&source=>
- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/&text=Synchronizers%20In%20Java%20-%20CyclicBarrier>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/>
- <https://www.instagram.com/ezestsolutions/?u=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/>

Along with [`CountDownLatch`](https://blog.e-zest.com/blog/countdownlatch/), [`FutureTask`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html) and [`Semaphore`](https://blog.e-zest.com/blog/semaphore-in-java/), the Concurrency API in Java 5 also introduced a barrier – [`CyclicBarrier`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html). This class is used as a barrier for a set of threads, to keep them waiting until all the threads have reached it. Once all the threads reach the barrier, it is tripped, allowing them to perform further execution. The number of threads in `WAITING` state, which when reached should trip the barrier, is passed as an argument to the constructor of `CyclicBarrier`. A `Runnable` action to be performed when the barrier is tripped can also be defined optionally while instantiating `CyclicBarrier`. The last thread to enter the barrier executes this action before the other waiting threads are released. If the action throws exception, the barrier is broken and all the other threads receive a checked exception `BrokenBarrierException`.

Unlike `CountDownLatch` which is a one-time latch, the `CyclicBarrier` can be tripped multiple times. A `CyclicBarrier` is usually used when you want to execute a task more than once by dividing it into multiple subtasks. A separate thread executes each subtask and thus multiple threads execute the subtasks concurrently. When a thread completes the execution of its subtask, it waits until the barrier is tripped. When all the threads executing subtasks have completed their execution, the barrier is tripped to carry on the execution of next task. Some action also can be performed optionally, when all the threads have completed executing subtasks.

Like `CountDownLatch`, this class also provides `await()` method which when called by a thread makes it to go in `WAITING` state. The thread will keep waiting until the number of waiting threads is equal to the number passed to the `CyclicBarrier` constructor or the waiting thread is interrupted or the barrier is broken or reset. If the waiting thread is interrupted by any other thread, then the `InterruptedException` is thrown. Like any blocking method, `InterruptedException` needs to be handled when `await()` is called. If any other thread waiting at the barrier is interrupted, the barrier is broken and other waiting threads receive a `BrokenBarrierException`. If a thread is still running when the barrier is broken, it will get this exception when it calls the barrier’s `await()` method. The `Runnable` action is not executed for a broken barrier.

A timed `await(long timeout, TimeUnit unit)` method also exists in `CyclicBarrier`. This is used to specify the maximum time period for which a thread can wait for other threads to reach the barrier. If the timeout is elapsed before the barrier trips, the barrier is broken. When the await with timeout is called by a thread, it waits until the barrier is tripped or the timeout is elapsed or the thread is interrupted or the barrier is broken or reset. A checked exception `TimeoutException` also needs to be handled for the timed await method. This exception is thrown when the time period is elapsed before the barrier trips. When a thread times out, other threads receive a `BrokenBarrierException`.

The number of threads waiting at the barrier can be obtained by calling method `getNumberWaiting()`. The number of threads required to trip the barrier can be obtained by calling method `getParties()`. The `isBroken()` method returns true if the barrier is broken.

A barrier can be reset to its initial state by calling the `reset()` method.

**Example**

An example to demonstrate the use of `CyclicBarrier` is giving in Listing 1. The RNG class is a random number generator which generates the number of random numbers equal to the count passed in its constructor. The generated random numbers can be obtained by calling the `getResult()` method. The task is to generate 20 random numbers twice. This task is divided within 4 threads where each thread generates 5 random numbers. After all the threads have completed execution, the `RandomNumberAssembler` gets the random numbers generated by all threads and prints them. The Executor framework is used to generate the child threads which will generate random numbers. A common `CyclicBarrier` instance is shared between all the threads. Once a thread completes its random number generation it waits for the other threads to complete their execution. The last thread to finish the random number generation will cause the barrier to trip when it completes execution.

```

public class RNG implements Runnable {
    private Random random = new Random();
    private int count;
    private CclicBarrier barrier;
    private List<Integer> randomNumbers =
        new ArrayList<Integer>();

    public List<Integer> getResult() {
        return randomNumbers;
    }

    public RNG(int count,CyclicBarrier barrier) {
        this.count = count;
	this.barrier = barrier;
    }

    public void run() {
        randomNumbers.clear();
	for(int i=1; i <= count; i++) {
	    randomNumbers.add(Math.abs(random.nextInt(100)));
	}
	try {
	    barrier.await();
	} catch (InterruptedException e) {
	    randomNumbers.clear();
	} catch (BrokenBarrierException e) {
	    randomNumbers.clear();
        }
    }
}

public class RandomNumberAssembler implements Runnable {
    private List<RNG> rngs;

    public RandomNumberAssembler(List<RNG> rngs) {
        this.rngs = rngs;
    }

    public void run() {
        System.out.println("Random numbers.............");
	for(RNG rng : rngs) {
	    for(Integer randomNumber : rng.getResult()) {
	        System.out.println(randomNumber);
	    }
	}
    }
}

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        //generate 20 random numbers using 4 threads twice
	final int THREAD_COUNT = 4;
	final int RANDOM_NUMBER_PER_THREAD_COUNT = 5;
	final int TASK_COUNT = 2;

	List<RNG> rngs = new ArrayList<RNG>();
	RandomNumberAssembler assembler =
            new RandomNumberAssembler(rngs);
	CyclicBarrier barrier = new
            CyclicBarrier(THREAD_COUNT,assembler);
	for(int i=1; i <= THREAD_COUNT; i++) {
            rngs.add(new
                RNG(RANDOM_NUMBER_PER_THREAD_COUNT,
                barrier));
	}
	ExecutorService service =
            Executors.newFixedThreadPool(THREAD_COUNT);

	for (int k=1; k <= TASK_COUNT; k++) {
	    for(int i=1; i <= THREAD_COUNT; i++) {
	        service.submit(rngs.get(i-1));
	    }
	}
	service.shutdown();
    }
}
```

Listing 1. Generate 20 random numbers twice using 4 threads

**Difference between FutureTask and CyclicBarrier**

The above example can also be implemented by implementing `Callable` on `RNG` and using the `submit()` method of [`ExecutorService`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html) which returns the [`Future`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#get(long,%20java.util.concurrent.TimeUnit)) object.

If the timed await method is used in the original example to define the maximum time period for which a thread can wait for other threads to complete execution, similar behavior can be obtained by calling the `get()` method of `Future` with timeout. However, there is no implicit way to let the other threads know about this timeout. Also, there is no implicit way to avoid the action from being called when a thread times out. Such a behavior can be best implemented using `CyclicBarrier`.

- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/&text=Synchronizers%20In%20Java%20-%20CyclicBarrier>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/>
- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/synchronizers-in-java-cyclicbarrier/&title=&summary=&source=>

### Similar Blog

[Oracle NoSQL Database (ONDB) Relational databases have been around us for more than 20 years now. Needless to say, they are mature and an obvious choice for ... By Madhura Oak Dec 24, 2013](https://blog.e-zest.com/oracle-nosql-database-ondb/)

[Session State Isolation Techniques Isolation of data in a session is the trickiest part of session management. A session may constitute of multiple requests. ... By Madhura Oak Dec 02, 2013](https://blog.e-zest.com/session-state-isolation-techniques/)

[Session Management There are three ways of session management in n-tier applications: By Madhura Oak Nov 27, 2013](https://blog.e-zest.com/session-management/)

[Transaction and Query timeout Performance is one of the non-functional requirements of an application. It defines the acceptable maximum response time for ... By Madhura Oak Nov 25, 2013](https://blog.e-zest.com/transaction-and-query-timeout/)

[![Multiple Inheritance in Domain Model Design](https://blog.e-zest.com/hs-fs/file-3586010320-png/blog-files/uml-class-diagram-%E2%80%93-bridge-pattern.png) Multiple Inheritance in Domain Model Design While using multiple inheritance in domain model design you need to be cautious as programming languages such as Java do not ... By Madhura Oak Nov 13, 2013](https://blog.e-zest.com/multiple-inheritance-in-domain-model-design/)

## Helping Organizations Thrive in the Digital Age

[Contact Us](https://www.e-zest.com/contact-us)

- [About](https://www.e-zest.com/about-us)
- [Services](https://www.e-zest.com/our-services)
- [Work](https://www.e-zest.com/our-work)
- [Insights](https://blog.e-zest.com/)
- [Healthcare](https://healthcare.e-zest.com/)
- [Accion Labs](https://www.accionlabs.com/)

- <https://www.linkedin.com/company/e-zest-solutions/>
- <https://twitter.com/ezest>
- <https://www.facebook.com/eZest/>
- <https://www.instagram.com/ezestsolutions/>
- <https://www.youtube.com/user/ezestcorporate>

- Dallas
- Detroit
- Hannover
- Vienna
- London
- Pune

 © 2025 e-Zest Solutions

- [Privacy Policy](https://www.e-zest.com/privacypolicy)
- [Cookie Policy](https://www.e-zest.com/cookie-policy)

 Contact us

 Contact us

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.