Java Concurrency - 浅析 CyclicBarrier 的用法

时间:2022-02-09 15:53:14

The Java concurrency API provides a synchronizing utility that allows the synchronization of two or more threads in a determined point. It's the CyclicBarrier class. This class is similar to the CountDownLatch class, but presents some differences that make them a more powerful class.

The CyclicBarrier class is initialized with an integer number, which is the number of threads that will be synchronized in a determined point. When one of those threads arrives to the determined point, it calls the await() method to wait for the other threads. When the thread calls that 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 class, 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 have arrived to the common point. This characteristic makes this class adequate for the 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 in a determined point. You will also use a Runnable object that will execute after all the threads have arrived to that point. In the example, you will look for a number in a matrix of numbers. The matrix will be divided in 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 job, a final task will unify the results of them.

1. We're going to start the example by implementing two auxiliary classes. First, create a class named MatrixMock. This class will generate a random matrix of numbers between one and 10 where the threads are going to look for a number.

package com.packtpub.java7.concurrency.chapter3.recipe4.utils;

import java.util.Random;

/**
* This class generates a random matrix of integer numbers between 1 and 10
*
*/
public class MatrixMock { /**
* Bi-dimensional array with the random numbers
*/
private int data[][]; /**
* Constructor of the class. Generates the bi-dimensional array of numbers.
* While generates the array, it counts the times that appears the number we are going
* to look for so we can check that the CiclycBarrier class does a good job
* @param size Number of rows of the array
* @param length Number of columns of the array
* @param number Number we are going to look for
*/
public MatrixMock(int size, int length, int number){ int counter=0;
data=new int[size][length];
Random random=new Random();
for (int i=0; i<size; i++) {
for (int j=0; j<length; j++){
data[i][j]=random.nextInt(10);
if (data[i][j]==number){
counter++;
}
}
}
System.out.printf("Mock: There are %d ocurrences of number in generated data.\n",counter,number);
} /**
* This methods returns a row of the bi-dimensional array
* @param row the number of the row to return
* @return the selected row
*/
public int[] getRow(int row){
if ((row>=0)&&(row<data.length)){
return data[row];
}
return null;
} }

2. Implement a class named Results. This class will store, in an array, the number of occurrences of the searched number in each row of the matrix.

package com.packtpub.java7.concurrency.chapter3.recipe4.utils;

/**
* This class is used to store the number of occurrences of the number
* we are looking for in each row of the bi-dimensional array
*
*/
public class Results { /**
* Array to store the number of occurrences of the number in each row of the array
*/
private int data[]; /**
* Constructor of the class. Initializes its attributes
* @param size Size of the array to store the results
*/
public Results(int size){
data=new int[size];
} /**
* Sets the value of one position in the array of results
* @param position Position in the array
* @param value Value to set in that position
*/
public void setData(int position, int value){
data[position]=value;
} /**
* Returns the array of results
* @return the array of results
*/
public int[] getData(){
return data;
}
}

3. Now that you have the auxiliary classes, it's time to implement the threads. First, implement the Searcher class. This class will look for a number in determined rows of the matrix of random numbers. Create a class named Searcher and specify that it implements the Runnable interface.

package com.packtpub.java7.concurrency.chapter3.recipe4.task;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier; import com.packtpub.java7.concurrency.chapter3.recipe4.utils.MatrixMock;
import com.packtpub.java7.concurrency.chapter3.recipe4.utils.Results; /**
* Class that search for a number in a set of rows of the bi-dimensional array
*
*/
public class Searcher implements Runnable { /**
* First row where look for
*/
private int firstRow; /**
* Last row where look for
*/
private int lastRow; /**
* Bi-dimensional array with the numbers
*/
private MatrixMock mock; /**
* Array to store the results
*/
private Results results; /**
* Number to look for
*/
private int number; /**
* CyclicBarrier to control the execution
*/
private final CyclicBarrier barrier; /**
* Constructor of the class. Initializes its attributes
* @param firstRow First row where look for
* @param lastRow Last row where fook for
* @param mock Object with the array of numbers
* @param results Array to store the results
* @param number Number to look for
* @param barrier CyclicBarrier to control the execution
*/
public Searcher(int firstRow, int lastRow, MatrixMock mock, Results results, int number, CyclicBarrier barrier){
this.firstRow=firstRow;
this.lastRow=lastRow;
this.mock=mock;
this.results=results;
this.number=number;
this.barrier=barrier;
} /**
* Main method of the searcher. Look for the number in a subset of rows. For each row, saves the
* number of occurrences of the number in the array of results
*/
@Override
public void run() {
int counter;
System.out.printf("%s: Processing lines from %d to %d.\n",Thread.currentThread().getName(),firstRow,lastRow);
for (int i=firstRow; i<lastRow; i++){
int row[]=mock.getRow(i);
counter=0;
for (int j=0; j<row.length; j++){
if (row[j]==number){
counter++;
}
}
results.setData(i, counter);
}
System.out.printf("%s: Lines processed.\n",Thread.currentThread().getName());
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
} }

4. Implement the class that calculates the total number of occurrences of the number in the matrix. It uses the Results object that stores the number of appearances of the number in each row of the matrix to make the calculation. Create a class named Grouper and specify that it implements the Runnable interface.

package com.packtpub.java7.concurrency.chapter3.recipe4.task;

import com.packtpub.java7.concurrency.chapter3.recipe4.utils.Results;

/**
* Group the results of each Searcher. Sum the values stored in the Results object
* An object of this class is executed automatically by the CyclicBarrier when
* all the Searchers finish its job
*/
public class Grouper implements Runnable { /**
* Results object with the occurrences of the number in each row
*/
private Results results; /**
* Constructor of the class. Initializes its attributes
* @param results Results object with the ocurrences of the number in each row
*/
public Grouper(Results results){
this.results=results;
} /**
* Main method of the Grouper. Sum the values stored in the Results object
*/
@Override
public void run() {
int finalResult=0;
System.out.printf("Grouper: Processing results...\n");
int data[]=results.getData();
for (int number:data){
finalResult+=number;
}
System.out.printf("Grouper: Total result: %d.\n",finalResult);
} }

5. Finally, implement the main class of the example by creating a class named Main.

package com.packtpub.java7.concurrency.chapter3.recipe4.core;

import java.util.concurrent.CyclicBarrier;

import com.packtpub.java7.concurrency.chapter3.recipe4.task.Grouper;
import com.packtpub.java7.concurrency.chapter3.recipe4.task.Searcher;
import com.packtpub.java7.concurrency.chapter3.recipe4.utils.MatrixMock;
import com.packtpub.java7.concurrency.chapter3.recipe4.utils.Results; /**
* Main class of the example
*
*/
public class Main { /**
* Main method of the example
* @param args
*/
public static void main(String[] args) { /*
* Initializes the bi-dimensional array of data
* 10000 rows
* 1000 numbers in each row
* Looking for number 5
*/
final int ROWS=10000;
final int NUMBERS=1000;
final int SEARCH=5;
final int PARTICIPANTS=5;
final int LINES_PARTICIPANT=2000;
MatrixMock mock=new MatrixMock(ROWS, NUMBERS,SEARCH); // Initializes the object for the results
Results results=new Results(ROWS); // Creates an Grouper object
Grouper grouper=new Grouper(results); // Creates the CyclicBarrier object. It has 5 participants and, when
// they finish, the CyclicBarrier will execute the grouper object
CyclicBarrier barrier=new CyclicBarrier(PARTICIPANTS,grouper); // Creates, initializes and starts 5 Searcher objects
Searcher searchers[]=new Searcher[PARTICIPANTS];
for (int i=0; i<PARTICIPANTS; i++){
searchers[i]=new Searcher(i*LINES_PARTICIPANT, (i*LINES_PARTICIPANT)+LINES_PARTICIPANT, mock, results, 5,barrier);
Thread thread=new Thread(searchers[i]);
thread.start();
}
System.out.printf("Main: The main thread has finished.\n");
} }

The problem resolved in the example is simple. We have a big matrix of random integer numbers and you want to know the total number of occurrences of a number in this matrix. To get a better performance, we use the divide and conquer technique. We divide the matrix in five subsets and use a thread to look for the number in each subset. These threads are objects of the Searcher class.

We use a CyclicBarrier object to synchronize the completion of the five threads and to execute the Grouper task to process the partial results, and calculate the final one.

As we mentioned earlier, the CyclicBarrier class has an internal counter to control how many threads have to arrive to the synchronization point. Each time a thread arrives to the synchronization point, it calls the await() method to notify the CyclicBarrier object that has arrived to its synchronization point. CyclicBarrier puts the thread to sleep until all the threads arrive to their synchronization point.

When all the threads have arrived to their synchronization point, the CyclicBarrier object wakes up all the threads that were waiting in the await() method and, optionally, creates a new thread that executes a Runnable object passed as the parameter in the construction of CyclicBarrier (in our case, a Grouper object) to do additional tasks.

The CyclicBarrier class has another version of the await() method:

await(long time, TimeUnit unit): The thread will be sleeping until it's interrupted; the internal counter of CyclicBarrier arrives to 0 or specified time passes. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.

This class also provides the getNumberWaiting() method that returns the number of threads that are blocked in the await() method, and the getParties() method that returns the number of tasks that are going to be synchronized with CyclicBarrier.

Resetting a CyclicBarrier object

The CyclicBarrier class has some points in common with the CountDownLatch class, but they also have some differences. One of the most important differences is that a CyclicBarrier object can be reset to its initial state, assigning to its internal counter the value with which it was initialized.

This reset operation can be done using the reset() method of the CyclicBarrier class. When this occurs, all the threads that were waiting in the await() method receive a BrokenBarrierException exception. This exception was processed in the example presented in this recipe by printing the stack trace, but in a more complex application, it could perform some other operation, such as restarting their execution or recovering their operation at the point it was interrupted.

Broken CyclicBarrier objects

A CyclicBarrier object can be in a special state denoted by broken. When there are various threads waiting in the await() method and one of them is interrupted, this thread receives an InterruptedException exception, but the other threads that were waiting receive a BrokenBarrierException exception and CyclicBarrier is placed in the broken state.

The CyclicBarrier class provides the isBroken() method, then returns true if the object is in the broken state; otherwise it returns false.