Skip to main content

Threads in Java - CyclicBarrier (Part 14)

This is a utility that makes threads to wait for each other. Sometimes we face a condition where we need to perform different parts of a computation and in the end, we want to combine the results of each computation. Such use cases can be easily achieved via CyclicBarrier.

What is CyclicBarrier?

A CyclicBarrier is used when multiple threads carry out different parts of a task and in the end, we need to combine the results of all the subtasks in the final result.
Once a thread completes the subtask assigned to it, it calls await() method and wait for other threads to complete their respective subtasks. This is called reaching the barrier. Once all threads reach the barriers, then the threads proceed further.

Working

  • First, we create an instance of the CycclicBarrier with the number of threads that the barriers should wait upon.
CyclicBarrier cyclicBarrier = new CyclicBarrier(numberOfThreads);
  • Now, the thread does some execution and calls the await() method.
public void run() {
    // Some code
    cyclicBarrier.await();
}
  • Once the number of threads that called the await() method equals the numberOfThreads, then the barrier gives way for the waiting threads.

In a nutshell

The waiting thread waits at the CyclicBarrier until -
  • The last thread arrives (calls await()).
  • The thread is interrupted by another thread (another thread calls its interrupt() method).
  • Another waiting thread is interrupted.
  • Another waiting thread times out when waiting at the barrier.
  • The reset() method is called by an external thread.

Action

A CyclicBarrier action is nothing but a Runnable task which is executed when the last thread arrives. We can pass the Runnable in the constructor as below - 
Runnable myRunnable = ...;
CyclicBarrier cyclicBarrier = new CyclicBarrier(numberOfThreads, myRunnable);

Code example

Below is the code example of CyclicBarrier -

Output

ThreadB is waiting on the barrier
ThreadA is waiting on the barrier
ThreadC is waiting on the barrier
This is the action. All the threads have crossed the barrier
ThreadA has crossed the barrier
ThreadB has crossed the barrier
ThreadC has crossed the barrier

Conclusion

Congratulations!! 🙋 today we discussed ReentrantLock class in java with an example and its use cases. I hope you enjoyed this post.

You can find the complete code of this project on my GitHub in this commit. Feel free to fork or open issues, if any.

I would love to hear your thoughts on this and would like have suggestions from you to make it better. 

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊

Comments

Popular posts from this blog

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…