Java Multithreading Series--"Juc lock" 05 of the Unfair lock

Source: Internet
Author: User
Tags cas

Get an unfair lock (based on jdk1.7.0_40)

Unfair locks and fair locks the process is the same on the method of acquiring locks, and their differences are mainly expressed in the "mechanism of trying to acquire locks". Simply put, the "fair lock" is a fair policy every time it tries to acquire a lock (according to the wait queue), while the "unfair lock" is a non-fair policy for each attempt to acquire a lock (ignoring the wait queue, trying to acquire the lock directly, and if the lock is free to get the state, acquire the lock).
In the previous "Java Multithreading Series--" Juc lock "03 of the Fair Lock (A)", has described in detail the acquisition of a fair lock process and mechanism; below, the process of obtaining an unfair lock through code analysis is below.

1. Lock ()

Lock () is implemented in the Nonfairsync class of Reentrantlock.java, and its source code is as follows:

 final " Span style= "COLOR: #0000ff" >void   lock () {  If  (compareandsetstate (0, 1 else   acquire ( 1  

Description :
Lock () determines whether the "lock" is idle by Compareandset (0, 1). Yes, "current thread" directly acquires "lock"; otherwise, call acquire (1) to acquire the lock.
Compareandsetstate () is a CAS function that compares and sets the state of the current lock. If the lock has a status value of 0, the lock's state value is set to 1.
(Setexclusiveownerthread) The role of Thread.CurrentThread () is to set the "current thread" as the holder of the "lock".

Comparison of "fair lock" and "unfair lock" about lock ()

Fair Lock   -the Lock () function of fair lock, will call acquire (1--Non-fair lock will first determine whether the state of the current lock is idle, if it is, do not queue, but directly acquire the lock.

2. Acquire ()

Acquire () is implemented in Aqs, and its source code is as follows:

 Public Final void Acquire (int  arg) {    if (!tryacquire (ARG) &&         Acquirequeued (Addwaiter (node.exclusive), arg))        selfinterrupt ();

(01) "Current thread" first attempts to acquire a lock through Tryacquire (). If it succeeds, it returns directly; if the attempt fails, it goes to the wait queue, sorts it, and then acquires the lock.
(02) The current thread is joined to the end of the CLH queue (non-blocking FIFO queue) by Addwaiter (node.exclusive) in the case of an attempt by the "current threads" to fail.
(03) Then, call acquirequeued () to get the lock. In acquirequeued (), the current thread waits for all threads in the CLH queue to execute and release the lock before it can get the lock and return. If the current thread is interrupted during the hibernation wait, call Selfinterrupt () to generate an interrupt on its own.

Comparison of "fair lock" and "unfair lock" about acquire ()

Fair and unfair locks, only the Tryacquire () function is implemented differently, that is, the mechanism in which they attempt to acquire a lock is different. This is what we call "the difference between their acquisition lock strategy"! In the "Java Multithreading series --" Juc lock "03 of the Fair Lock (A)", has described in detail the acquire () involved in the various functions. Only the function Tryacquire () with their differences are described here.

The non-fair lock Tryacquire () is implemented in the Nonfairsync class of Reentrantlock.java, with the following source code:

protected Final boolean tryacquire (int  acquires) {    return  Nonfairtryacquire (acquires);}

Nonfairtryacquire () is implemented in the Reentrantlock.java sync class with the following source code:

Final BooleanNonfairtryacquire (intacquires) {    //get "Current thread"    FinalThread current =Thread.CurrentThread (); //get the state of a "lock"    intc =getState (); //c=0 means that "locks are not owned by any thread lock"    if(c = = 0) {        //If the lock is not owned by any of the thread locks, the state of the lock is set to acquires by using the CAS function. //at the same time, set "current thread" as the holder of the lock.         if(Compareandsetstate (0, acquires))            {Setexclusiveownerthread (current); return true; }    }    Else if(Current = =Getexclusiveownerthread ()) {        //if the holder of the "lock" is already a "current thread",//The state of the lock is updated.         intNEXTC = C +acquires; if(NEXTC < 0)//Overflow            Throw NewError ("Maximum Lock count Exceeded");        SetState (NEXTC); return true; }    return false;}

Description :
According to the code, we can analyze that the function of Tryacquire () is to try to acquire a lock.
(01) If the "lock" is not owned by any thread, the state of "lock" is set by the CAS function as acquires, and the "Current thread" is set as the holder of the lock and then returns TRUE.
(02) If the "lock" Holder is already the current thread, the state of the lock will be updated.
(03) If the above two cases are not considered, the attempt fails.

Comparison of "fair lock" and "unfair lock" about Tryacquire ()

Fair and non-fair locks, they try to acquire locks in different ways. Fair Lock when attempting to acquire a lock, even if the "lock" is not held by any thread lock, it will also determine whether it is the CLH waiting queue header; Instead of a fair lock when trying to acquire a lock, if the lock is not held by any thread, it acquires the lock directly regardless of where it is in the CLH queue.

Releasing an unfair lock (based on jdk1.7.0_40)

An unfair lock and a fair lock are the same method and strategy for releasing the lock.

Summarize
The difference between a fair lock and a non-fair lock is the difference in the mechanism of acquiring a lock. Table now, when attempting to acquire a lock-a fair lock, acquires the lock only if the current thread is CLH waiting for the queue's header, rather than a fair lock, which acquires the lock directly, regardless of the order of the CLH waiting queue, as long as the current lock is idle.
Only when an unfair lock attempts to acquire a lock fails does it go into the CLH waiting queue sort like a fair lock.

Reference:

Http://www.cnblogs.com/skywang12345/p/3496651.html

Java Multithreading Series--"Juc lock" 05 of the Unfair lock

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.