Search

Tuesday, June 16, 2015

How to use CyclicBarrier in Java - Concurrency Tutorail

This is the second part of my concurrency tutorial, in first part, you have learned how to use CountDownLatch and in this part, you will learn how to use CyclicBarrier class in Java. CyclicBarrier is another concurrency utility introduced in Java 5 which is used when a number of threads (also known as parties) wants to wait for each other at a common point, also known as barrier before starting processing again. Its similar to CountDownLatch but instead of calling countDown() each thread calls await() and when last thread calls await() which signals that it has reached barrier, all thread started processing again, also known as barrier is broken. You can use CyclicBarrier wherever you want to use CountDownLatch, but opposite is not possible because you can not reuse the latch once count reaches to zero. Some of the common usage of CyclicBarrier is in writing unit test for concurrent program, to simulate concurrency in test class or calculating final result after individual task has completed.

In this tutorial, I will show you an example of how four worker thread waits for other before starting again. As I told in previous article, concurrency is hard to master, sometime even if you read couple of articles on one topic, you don't get what you are looking for. If you understand how and where to use CountDownLatch and CyclicBarrier, then only you will feel confident. Books are also good for mastering concurrency, and one book in particular is very useful to learn multi-threading and concurrency in Java. You guessed it right, I am talking about Java Concurrency in Practice by Brian Goetz, I strongly recommend this book to anyone seriously wants to master threading and concurrency in Java. If you can't get first hand, get second hand, if you can't buy then lend it from library but if you are serious about Java concurrency, you should read it.
Read more »

No comments:

Post a Comment