Synchronizing tasks in a common point

The Java concurrency API provides a synchronizing utility that allows the synchronization of two or more threads at a determined point. It's the CyclicBarrier class. This class is similar to the CountDownLatch class explained in the Waiting for multiple concurrent events recipe in this chapter, but it presents some differences that make it a more powerful class.

The CyclicBarrier class is initialized with an integer number, which is the number of threads that will be synchronized at a determined point. When one of these threads arrives at the determined point, it calls the await() method to wait for the other threads. When the thread calls this method, the CyclicBarrier class blocks the thread that is sleeping until the other threads arrive. When the last thread calls the await() method of the CyclicBarrier object, it wakes up all the threads that were waiting and continues with its job.

One interesting advantage of the CyclicBarrier class is that you can pass an additional Runnable object as an initialization parameter, and the CyclicBarrier class executes this object as a thread when all the threads arrive at the common point. This characteristic makes this class adequate for parallelization of tasks using the divide and conquer programming technique.

In this recipe, you will learn how to use the CyclicBarrier class to synchronize a set of threads at a determined point. You will also use a Runnable object that will be executed after all the threads arrive at this point. In the example, you will look for a number in a matrix of numbers. The matrix will be divided into subsets (using the divide and conquer technique), so each thread will look for the number in one subset. Once all the threads have finished their respective jobs, a final task will unify their results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.214