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.
- First, we create an instance of the CycclicBarrier with the number of threads that the barriers should wait upon.
- Now, the thread does some execution and calls the await() method.
- 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.
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 -
Below is the code example of CyclicBarrier -
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.
Happy Coding 😊