In-depth analysis based on concurrent AQS (exclusive lock) re-entry lock (Reetrantlock) and its condition implementation principle __java concurrent programming

Source: Internet
Author: User
Tags cas
Turn from: http://blog.csdn.net/javazejian/article/details/75043422

From "Zejian's blog."

Related articles:

Deep understanding of Java type information (class object) and reflection mechanism

Deep understanding of Java Enum Types (enum)

Deep understanding of Java Annotation Types (@Annotation)

Deep understanding of the Java Class loader (ClassLoader)

Deep understanding of the synchronized implementation principle of Java concurrency

Java concurrent Programming-non-lock CAs and unsafe classes and their contract atomic

Deep understanding of the Java Memory Model (JMM) and volatile keywords

Deeply analyze the implementation principle of the AQS (exclusive lock) re-entry lock (Reetrantlock) based on concurrent and its condition

The implementation of shared locks based on concurrent AQS (based on signal volume semaphore)

Before reading this blog post, it is recommended that you have a CAS knowledge reserve, because the operation of CAS is ubiquitous in the implementation of Reetrantlock, without knowing that CAs can see another blog post of the blogger first. Java concurrent Programming-non-lock CAs and unsafe classes and their and contract atomic ", the following is the main content of this article

Lock interface reentrant lock Reetrantlock concurrent Base component Aqs and Reetrantlock Aqs working principle summary based on Reetrantlock analysis AQS Exclusive mode realization Process Reetrantlock non-fair lock Fair lock in Reetrantlock on the magical condition of synchronized and reentrantlock on the use case of condition interface condition-the principle of the realization of producer consumer mode condition

Lock Interface

We've talked about this before. The key word synchronized,synchronized for multithreading synchronization is implicit, that is, lock holding and releasing are implicit, we do not need to intervene, and this article we want to explain is the explicit lock, that is, lock holding and release must be manually written by us. In Java 1.5, the official included the lock interface in the concurrent, which provided the lock () method and the Unlock () method to support explicit lock and explicit release lock operations, with a simple understanding of code writing, as follows:

Lock lock = new Reentrantlock ();
Lock.lock ();
try{
    //Critical area ...
} finally{
    Lock.unlock ();
}
   
   
    
    1
    
    2
    
    3
    
    4
    
    5
    
    6
    
    7 1 2 3
    
    4 5 6-7
   
   

As the code shows (Reentrantlock is the implementation class for lock, which is later parsed), the current thread surrounds the critical area with the lock () method and Unlock (), and other threads cannot enter the critical section because the lock cannot be held until the current thread releases the lock, noting that the unlock ( The operation must be in the finally code block, which ensures that the thread eventually releases the lock normally even if the critical section executes throwing an exception, and the lock interface provides the following related methods of locking

Public interface Lock {//Lock void Lock ();

    unlock void unlock (); An interruptible fetch lock differs from lock () in that it responds to an interrupt operation that is interrupted in the process of getting//fetching a lock, noting that synchronized is an interruptible void lockinterruptibly () throws when acquiring a lock interrupte

    Dexception;

    Try a non-blocking fetch lock, return the result immediately after calling the method, return True if it is available, or false Boolean trylock (); Gets the lock based on the passed time period, returns False if the lock is not acquired within a specified time, returns True if the current thread is not in the specified time and gets the lock Trylock (long, Timeunit unit) throws Inter

    Ruptedexception;
    Gets the wait notification component, which binds to the current lock, only if the current thread acquires a lock//To call the () method of the component, and the current thread releases the lock after the call.
   
   
    
    Condition newcondition ();
    
    1 2 3 4 5 6 7 8 9 10 11
   
   
   
   
    
    12 13 14 15 16 17 18 19 20
    
    1 2 3 4 5 6 7 8 9 10 11
    
   12 13 14 15 16 17 18 19 20
   
    

Lock object Locks also provide other synchronization features that synchronized do not have, such as access to interruptible locks (synchronized are not available when waiting to acquire a lock), acquisition of timeout interrupt locks, multiple conditional variable condition waiting for the wake-up mechanism, This also makes lock locks more flexible to use. The following further analysis of the lock's implementation class Reetrantlock the lock. re-entry lock Reetrantlock

Re-entry lock REETRANTLOCK,JDK 1.5 new class, implementation of the lock interface, the role of the Synchronized keyword equivalent, but more flexible than synchronized. The Reetrantlock itself is also a lock that supports a re-enter, that is, the lock can support a thread to repeatedly lock resources, while also supporting fair and unfair locks. The so-called fairness and unfairness refers to the order of request, the first request to the lock must be acquired to the lock, then this is a fair lock, conversely, if the acquisition of the lock and there is no time in the order, such as the request after the thread may get to the lock, which is a fair lock, in general, is not, The efficiency of the unfair locking mechanism is often better than the mechanism of fair lock, but in some scenes, it may be more attention to the time sequence, so the fair lock nature is a good choice. It is important to note that Reetrantlock supports locking on the same line, but how many times the lock must be unlocked, so that the lock can be released successfully. Here's a look at Reetrantlock's simple use case:

Import Java.util.concurrent.locks.ReentrantLock;
    public class Reenterlock implements runnable{public static Reentrantlock lock=new Reentrantlock ();
    public static int i=0;
            @Override public void Run () {for (int j=0;j<10000000;j++) {lock.lock ();
            Support for Reentrant lock Lock.lock ();
            try{i++;
                }finally{//Perform two times unlock lock.unlock ();
            Lock.unlock (); }} public static void Main (string[] args) throws interruptedexception {Reenterlock tl=new reen
        Terlock ();
        Thread t1=new thread (TL);
        Thread t2=new thread (TL);
        T1.start (); T2.start ();
        T1.join (); T2.join ();
    Output Result: 20000000 System.out.println (i); 
    
    } 1 2 3 4 5 6 7 8 9 10
    
    11 12 13 14 1516 17 18 19 20 21 22 23 24 25 26
    
    27 28 29 30 1 2 3 4 5
    
    6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 2
   
    6 27 28 29 30

The code is very simple, we use two threads at the same time to operate the critical resources I, the implementation of the self-operation, using Reenterlock to lock, solve thread safety problems, there are two repeated lock, because the Reenterlock support reentry, so this is no problem, It is important to note that in the finally code block, a two-time unlock operation is required to truly successfully release the lock from the current thread of execution, from where the Reenterlock usage is very simple, in addition to implementing the Lock interface method, Reenterlock other methods are described below

//query the number of times the current thread has kept this lock.      
int Getholdcount ()//returns the thread that currently owns this lock, and returns NULL if the lock is not owned by any thread. 

Protected Thread GetOwner ();      
Returns a collection that contains the thread that may be waiting to acquire the lock, and maintains a queue within it, which is later analyzed. 

Protected collection<thread> getqueuedthreads ();   
Returns the number of thread estimates that are waiting to get this lock.

int Getqueuelength ();
Returns a collection that contains those threads that may be waiting for a given condition associated with this lock. 

Protected collection<thread> getwaitingthreads (Condition Condition);       
Returns the number of thread estimates waiting for the given condition associated with this lock.

int Getwaitqueuelength (Condition Condition);     
Queries whether a given thread is waiting to acquire this lock. 

Boolean hasqueuedthread (thread thread);     
Query if some threads are waiting to acquire this lock.

Boolean hasqueuedthreads ();     
Queries whether some threads are waiting for the given condition associated with this lock. 

Boolean haswaiters (Condition Condition);     
Returns true if the fairness of this lock is set to true.      
Boolean Isfair ()//queries whether the current thread maintains this lock.        
Boolean isheldbycurrentthread ()//query Whether this lock is persisted by any thread. Boolean islocked () 

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.