CountDownLatch and CyclicBarrier for multi-thread processing in Java

Source: Internet
Author: User

CountDownLatch

Literally, it means the inverted counting latches. As we will talk about later, the synchronization here allows one or more threads to wait, knowing that a series of operations performed by other threads are completed. CountDownLatch is constructed by a count (number) parameter, while await () blocks the current thread until countDown () reduces the count to 0, and then all blocking threads are released, that is, the threads that call the await method return immediately. Note that this is a one-time operation. That is to say, the count cannot be automatically reset. If you want to do this, the CyclicBarrier operation is fine.

CountDownLatch is very useful. When it is constructed with count = 1, this is equivalent to a switch. All threads that call the await method are waiting until one thread calls countDown (), countDownLatch is constructed by using count = N, so that one thread can wait for N other threads to complete the operation, or one operation is done N times.

Simple demo:

A group of worker threads use two CountDownLatch

The first is the start signal, which is used to prevent workers from starting operations in advance until the (driver) conveyor belt is ready.

The second is the completion signal, which makes the conveyor wait until all workers are finished.

Class Driver {//...
Void main () throws InterruptedException {
CountDownLatch startSignal = new CountDownLatch (1 );
CountDownLatch doneSignal = new CountDownLatch (N );

For (int I = 0; I & lt; N; ++ I) // Create and start a thread
New Thread (new Worker (startSignal, doneSignal). start ();

DoSomethingElse (); // prepare for the conveyor belt.
StartSignal. countDown (); // minus 0, the worker can start
DoSomethingElse ();
DoneSignal. await (); // wait until all workers finish the task

}
}

Class Worker implements Runnable {
Private final CountDownLatch startSignal;
Private final CountDownLatch doneSignal;
Worker (CountDownLatch startSignal, CountDownLatch doneSignal ){
This. startSignal = startSignal;
This. doneSignal = doneSignal;
}
Public void run (){
Try {
StartSignal. await (); // The worker waits for the switch to open
DoWork (); // do things
DoneSignal. countDown (); // after completing the operation, subtract 1 from countdownlatch.
} Catch (InterruptedException ex) {}// return;
}

Void doWork (){... }
}

Another typical example is to divide the problem into N parts and execute each part through the thread. Specifically, the thread is queued into an Executor object. Call the execute method. After a part of the execution is completed, the latch is subtracted from 1. When the value is reduced to 0, The await method can be called to continue running. When repeated counting is required, replace it with javasicbarrier.

Class Driver2 {//...
Void main () throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch (N );
Executor e =...

For (int I = 0; I & lt; N; ++ I) // Create and start the thread
E.exe cute (new WorkerRunnable (doneSignal, I ));

DoneSignal. await (); // wait for all threads to finish

}
}

Class WorkerRunnable implements Runnable {
Private final CountDownLatch doneSignal;
Private final int I;
WorkerRunnable (CountDownLatch doneSignal, int I ){
This. doneSignal = doneSignal;
This. I = I;
}
Public void run (){
Try {
DoWork (I );
DoneSignal. countDown ();
} Catch (InterruptedException ex) {}// return;
}

Void doWork (){... }
}
 
CyclicBarrier

Literally, the loop fence. The synchronization here allows a series of threads to wait for each other until everyone comes to the front of a barrier. It is very useful when the program waits for each other, it is called a loop because when all the waiting threads are released, javasicbarrier can be reused.

At the same time, javasicbarrier supports an optional Runnable parameter. When all threads come before the barrier, the program starts to execute the runable thread action. When a state shared by all threads needs to be updated, this action is very useful. The example is an example of parallel decomposition.

Class Solver {
Final int N;
Final float [] [] data;
Final javasicbarrier barrier;

Class Worker implements Runnable {
Int myRow;
Worker (int row) {myRow = row ;}
Public void run (){
While (! Done ()){
ProcessRow (myRow );

Try {
Barrier. await ();
} Catch (InterruptedException ex ){
Return;
} Catch (BrokenBarrierException ex ){
Return;
     }
   }
 }

}

Public Solver (float [] [] matrix ){
Data = matrix;
N = matrix. length;
Barrier = new CyclicBarrier (N,
New Runnable (){
Public void run (){
MergeRows (...);
}
});
For (int I = 0; I <N; ++ I)
New Thread (new Worker (I). start ();

WaitUntilDone ();

}
}

Here, each worker thread processes a row of the matrix and waits before the barrier until all rows are processed completely. After all rows are processed

Barrier = new CyclicBarrier (N,
New Runnable (){
Public void run (){
MergeRows (...);
                               }
});


The Runnable parameter is executed to merge these rows. Once the correct result waitUntilDown () is obtained, true is returned, and all threads terminate.

If the barrier executes this action and does not respond to the waiting threads so that the threads can perform other operations, we can write

Barrier. await ()


Change

If (barrier. await () = 0 ){
// Record the position of this iteration
   }


If a thread leaves barrier too early due to interruption, failure, or timeout, all threads will cause exceptions through BrokenBarrierException.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.