Java Lock--cyclicbarrier

Source: Internet
Author: User

Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3533995.html

Cyclicbarrier Introduction

Cyclicbarrier is a synchronous helper class that allows a group of threads to wait for each other until a common barrier point (common barrier points) is reached. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.

Note Compare Countdownlatch and Cyclicbarrier:
Countdownlatch's role is to allow 1 or n threads to wait for other threads to complete execution, while Cyclicbarrier allows n threads to wait for each other.
Countdownlatch counters cannot be reset, cyclicbarrier counters can be reset and used, so it is called a circular barrier.


List of Cyclicbarrier functions

Cyclicbarrier (int parties) creates a new cyclicbarrier that starts when a given number of participants (threads) are waiting, but does not perform a predefined operation when the barrier is started. Cyclicbarrier (int parties, Runnable barrieraction) creates a new cyclicbarrier that starts when a given number of participants (threads) are waiting and starts barrier Performs a given barrier operation, which is performed by the last thread that enters barrier. int await () waits until all participants have already raised the await method in this barrier. The int await (long timeout, timeunit unit) waits until all participants have invoked the await method on this barrier, or exceeds the specified wait time. int getnumberwaiting () returns the number of participants currently waiting at the barrier. int Getparties () returns the number of participants that are required to start this barrier. Boolean IsBroken () queries whether this barrier is in a corrupt state. void Reset () resets the barrier to its initial state.

cyclicbarrier Data Structure

The UML class diagram for Cyclicbarrier is as follows:

Cyclicbarrier is the "Reentrantlock object lock" and "condition Object Trip", which is implemented by an exclusive lock. Below through the source code to analyze exactly how to achieve.

Cyclicbarrier Source Analysis (based on jdk1.7.0_40)

Cyclicbarrier full source (based on jdk1.7.0_40)

View Code

The Cyclicbarrier is implemented by Reentrantlock (exclusive lock) and condition. Below, we analyze the 3 core functions in Cyclicbarrier: constructors, await () to make an analysis.

1. Constructors

Cyclicbarrier has a total of 2 constructors: Cyclicbarrier and Cyclicbarrier (int parties, Runnable barrieraction). The 1th constructor is called the 2nd constructor to implement, the following 2nd constructor of the source code.

public Cyclicbarrier (int parties, Runnable barrieraction) {    if (parties <= 0) throw new IllegalArgumentException () ;    Parties means "the number of threads that must reach barrier at the same time."    this.parties = parties;    Count indicates the number of threads in the waiting state.    This.count = parties;    Barriercommand represents "the action that will be performed when a parties thread arrives at barrier."    This.barriercommand = barrieraction;}

2. Wait for the function

The await () method in Cyclicbarrier.java is as follows:

public int await () throws Interruptedexception, Brokenbarrierexception {    try {        return dowait (false, 0L);    } catch (timeoutexception toe) {        throw new Error (toe);//cannot happen;    }}

description : Await () is implemented through Dowait ().

private int Dowait (Boolean timed, Long Nanos) throws Interruptedexception, Brokenbarrierexception, Timeoutexc    eption {final Reentrantlock lock = This.lock;    Get the exclusive lock (lock) Lock.lock ();        try {//save "current Generation" final Generation g = Generation;        If "Current generation is corrupted", an exception is thrown.        if (g.broken) throw new Brokenbarrierexception ();        If the current thread is interrupted, Cyclicbarrier is terminated through Breakbarrier (), and all waiting threads in the Cyclicbarrier are awakened.            if (thread.interrupted ()) {breakbarrier ();        throw new Interruptedexception ();       }//Will "Count counter"-1 int index =--count;       If index=0, it means "there are parties threads reaching barrier".           if (index = = 0) {//tripped Boolean ranaction = false;               try {//if Barriercommand is not NULL, the action is performed.               Final Runnable command = Barriercommand;               if (command! = null) Command.run ();               Ranaction = true; Wake up all waiting threads, and updateGeneration               Nextgeneration ();           return 0;           } finally {if (!ranaction) breakbarrier ();        }}//When the front thread has been blocked until "there are parties threads reaching barrier" or "the current thread is interrupted" or "timed out" one of the 3 occurrences,//When the frontline friend continues to execute. for (;;)                {try {//If not ' timeout wait ', call Awati () to wait; otherwise, call Awaitnanos () to wait.                if (!timed) trip.await ();            else if (Nanos > 0L) Nanos = Trip.awaitnanos (Nanos);                } catch (Interruptedexception IE) {//If the thread is interrupted during the wait, the following function is executed.                    if (g = = Generation &&! G.broken) {breakbarrier ();                throw ie;                } else {Thread.CurrentThread (). interrupt ();            }}//If "current generation is corrupted", an exception is thrown.            if (g.broken) throw new Brokenbarrierexception (); Returns index if "generation has been upgraded".            if (g! = generation) return index;            If it is a "timeout wait" and the time has passed, the cyclicbarrier is terminated by Breakbarrier (), and all the waiting threads in the Cyclicbarrier are awakened.                If (timed && Nanos <= 0L) {breakbarrier ();            throw new TimeoutException ();    }}} finally {//release "exclusive Lock (Lock)" Lock.unlock (); }}

Description : The Role of dowait () is to cause the current thread to block until one of the 3 "Parties threads arrives barrier" or "current thread is interrupted" or "timed out" occurs, and the current line friend continues to execute.
Generation is a member traversal of Cyclicbarrier, which is defined as follows:

Private Generation Generation = new Generation ();p rivate static class Generation {    Boolean broken = false;}

In Cyclicbarrier, the same batch of threads belongs to the same generation, that is, the same generation;cyclicbarrier through the Generation object, the record belongs to which generation.
When a parties thread arrives at Barrier,generation, it will be replaced by a replacement.

(02) If the current thread is interrupted, that is, thread.interrupted () is true, the Cyclicbarrier is terminated by Breakbarrier (). The source code of Breakbarrier () is as follows:

private void Breakbarrier () {    Generation.broken = true;    Count = parties;    Trip.signalall ();}

Breakbarrier () Sets the current interrupt token broken to true, which means "break the generation" and, at the same time, sets the Count=parties, which re-initializes the count, and finally, through the Signalall () Wakes up all the waiting threads on the cyclicbarrier.

(03) "Count Counter"-1, that is--count, then determine whether "there are parties threads to reach barrier", that is, index is not 0.
When index=0, if Barriercommand is not NULL, executing the Barriercommand,barriercommand is the Runnable object that is passed in when we create the cyclicbarrier. Then, call Nextgeneration () to do the replacement work, nextgeneration () The source code is as follows:

private void Nextgeneration () {    trip.signalall ();    Count = parties;    Generation = new Generation ();}

First, it calls Signalall () to wake up all the waiting threads on the cyclicbarrier, then initializes the count, and finally, updates the value of generation.

(04) in for (;;) The loop. Timed is used to indicate whether a "timeout wait" thread is currently present. If not, wait through trip.await (), otherwise call Awaitnanos () to wait for the timeout.

Examples of using Cyclicbarrier

Example 1
When you create a new 5 thread, and the 5 threads reach a certain condition, they continue to run backwards.

 1 Import java.util.concurrent.CyclicBarrier; 2 Import java.util.concurrent.BrokenBarrierException;     3 4 public class CyclicBarrierTest1 {5 6 private static int SIZE = 5; 7 private static cyclicbarrier CB; 8 public static void Main (string[] args) {9 cb = new Cyclicbarrier (SIZE); 11 12//New 5 tasks for (i NT I=0; i<size; i++) New Innerthread (). Start (),}16 static class Innerthread extends Thread{18 public v OID run () {try {System.out.println (Thread.CurrentThread (). GetName () + "Wait for CYCLICB Arrier. ");                 21 22//The number of participants in the CB is added 123 cb.await (); The number of participants in the CB is equal to 5 o'clock, and the subsequent execution 26 System.out.println (Thread.CurrentThread (). GetName () + "continued."); (Brokenbarrierexception e) {e.printstacktrace ();} catch (Interrup    Tedexception e) {e.printstacktrace (); 31         }32}33}34} 

Operation result :

Thread-1 wait for cyclicbarrier.thread-2 wait for cyclicbarrier.thread-3 wait for cyclicbarrier.thread-4 wait for CYCLICBA Rrier. Thread-0 wait for cyclicbarrier.thread-0 continued. Thread-4 continued. Thread-2 continued. Thread-3 continued. Thread-1 continued.

The result is a new 5 threads in the main thread, all of which call cb.await () wait. All these threads wait until all the threads in the CB reach barrier, and these lines friend continue to run!

Example 2

Create a new 5 thread to perform a task when these 5 threads reach a certain condition.

 1 Import java.util.concurrent.CyclicBarrier; 2 Import java.util.concurrent.BrokenBarrierException;     3 4 public class CyclicBarrierTest2 {5 6 private static int SIZE = 5; 7 private static cyclicbarrier CB; 8 public static void Main (string[] args) {9 cb = new Cyclicbarrier (SIZE, New Runnable () {One public         void Run () {System.out.println ("Cyclicbarrier ' s parties is:" + cb.getparties ()); 13}14 }); 15 16//New 5 tasks for (int i=0; i<size; i++) New Innerthread (). Start (); 19}20 2 1 static class Innerthread extends thread{22 public void run () {% try {System. Out.println (Thread.CurrentThread (). GetName () + "Wait for Cyclicbarrier.");                 25 26//The number of participants in the CB is added 127 cb.await (); The number of participants in CB is equal to 5 o'clock. 30 System.out.println (Thread.CurrentThread (). GetName () + "continued."); 31} catch (Brokenbarrierexception e) {e.printstacktrace ();) catch (Interruptedexception e) {e.printstacktrace (); 35}36}37}38}

Operation result :

Thread-1 wait for cyclicbarrier.thread-2 wait for cyclicbarrier.thread-3 wait for cyclicbarrier.thread-4 wait for CYCLICBA Rrier. Thread-0 wait for Cyclicbarrier.cyclicbarrier ' s parties is:5thread-0 continued. Thread-4 continued. Thread-2 continued. Thread-3 continued. Thread-1 continued.

The result is a new 5 threads in the main thread, all of which call cb.await () wait. All these threads wait until all threads in the CB reach barrier, and the runnable task that is registered when the new CB is executed.

Java Lock--cyclicbarrier

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.