Talk about high concurrency (27) Parsing java.util.concurrent components (ix) Understanding Reentrantlock can be re-entered lock

Source: Internet
Author: User

In this article, Reentrantlock can be re-entered, and the reentrant lock provided in the Juc is a blocking reentrant lock based on AQS implementation. This is a conversation. High concurrency (16) implements a simple reentrant lock that simulates the implementation of a reentrant lock. The features of the reentrant lock are:

1. is a mutex, based on the AQS mutual exclusion mode implementation, that is, only one thread into the critical section, wake up the next thread can only release a waiting thread

2. reentrant, by setting a field exclusiveownerthread to indicate the thread that is currently acquiring the lock. The get lock operation is if the current thread is a thread that has already acquired a lock, then the fetch operation succeeds. The current status as a counter to obtain the number of locks, re-enter the first add 1, release one time minus 1, until the status of 0

3. A reentrant lock can be associated with multiple condition condition objects to manipulate multiple conditional queues. The condition interface provides conditional queue operations for explicit blocking/waking threads. This is more flexible than built-in locks and built-in conditional queues, with 1 objects with only 1 built-in locks and one built-in conditional queue. Watch this chat. High concurrency (14) Understanding the threads in Java, conditional queuing, condition, and implementing a blocking queue


Take a look at Reentrantlock's code. It also provides the sync class to inherit Aqs, extending functionality by implementing TRYXXX.

1. Nonfairtryacquire () is a non-fair tryacquire operation that ignores the Aqs wait queue, attempts to acquire the lock directly by judging the state, and sets the current thread to the thread that acquires the lock to support reentrant

2. The Tryrelease () method releases the lock by modifying the state, and if the status is 0, the exclusiveownerthread is set to empty, then the thread competes

3. The Newcondition () method creates a Conditionobject each time to represent 1 conditional queues. In the previous article on Aqs, it was said that the lock was not acquired immediately after waking from the conditional queue, but rather from the conditional queue to the synchronization queue or to a competition lock. The data structure of the queue lock provides a first-come-first-serve feature and reduces the contention for locks

Abstract static class Sync extends Abstractqueuedsynchronizer {private static final long Serialversionuid = 51795        23762034025860L; /** * Performs {@link lock#lock}.         The main reason for subclassing * are to allow fast path for Nonfair version.        */abstract void lock ();  /** * performs Non-fair trylock.         Tryacquire is * implemented in subclasses, but both need Nonfair * try for Trylock method.            */FINAL Boolean nonfairtryacquire (int acquires) {final Thread current = Thread.CurrentThread ();            int c = GetState ();                    if (c = = 0) {if (compareandsetstate (0, acquires)) {Setexclusiveownerthread (current);                return true;                }} else if (current = = Getexclusiveownerthread ()) {int NEXTC = c + acquires; if (NEXTC < 0)//overflow throw new Error ("Maximum lock count exceeded ");                SetState (NEXTC);            return true;        } return false;            } Protected Final Boolean tryrelease (int releases) {int c = getState ()-releases;            if (Thread.CurrentThread ()! = Getexclusiveownerthread ()) throw new Illegalmonitorstateexception ();            Boolean free = false;                if (c = = 0) {free = true;            Setexclusiveownerthread (NULL);            } setState (c);        return free;            } Protected Final Boolean isheldexclusively () {//While we must in general read state before owner, We don ' t need to the check if current thread is owner return getexclusiveownerthread () = = Threa        D.currentthread ();        } final Conditionobject Newcondition () {return new Conditionobject (); }//Methods relayed from outer class final Thread GetownER () {return getState () = = 0? null:getexclusiveownerthread ();        } final int Getholdcount () {return isheldexclusively ()? GetState (): 0;        } Final Boolean isLocked () {return getState ()! = 0;         }/** * Reconstitutes This lock instance from a stream. * @param s The stream * * private void ReadObject (Java.io.ObjectInputStream s) throws Java.io.IOE            Xception, ClassNotFoundException {s.defaultreadobject (); SetState (0); Reset to unlocked State}}

The Fairsync and Nonfairsync implementations of fair lock and non-fair lock are also provided. As with the meaning of fairness in the previous semaphore, the unfairness is manifested in whether the fetch operation waits for the first-coming thread in the Aqs queue, and once the unfair acquisition lock fails, it enters the Aqs queue and waits, Aqs queue is the FIFO queue

1. You can see the lock operation of the non-fair lock, first try to get the lock with the quickest path, if get failed, call Aqs queue with acquire operation.

2. The tryacquire operation of Fair Lock when the state is 0, wait for the first-come thread to get the lock, and if there is a first-come thread, enter the Aqs queue. If the thread that is currently acquiring the lock is itself, the lock is acquired directly, and the state is added 1, which reflects the reentrant

Static final class Nonfairsync extends Sync {private static final long serialversionuid = 7316153563782823691L;  /** * performs lock.         Try immediate barge, backing up to normal * acquire on failure. */FINAL void lock () {if (compareandsetstate (0, 1)) Setexclusiveownerthread (Thread.curre            Ntthread ());        else acquire (1);        } Protected Final Boolean tryacquire (int acquires) {return Nonfairtryacquire (acquires); }}/** * Sync object for Fair locks * * Static final class Fairsync extends Sync {private static        Final long serialversionuid = -3000897897090466540l;        Final void Lock () {acquire (1);  }/** * Fair version of Tryacquire.         Don ' t grant access unless * recursive call or no waiters or is first. */Protected Final Boolean tryacquire (int acquires) {Final Thread current = Thread.CurrentThread ();            int c = GetState ();                     if (c = = 0) {if (!hasqueuedpredecessors () && compareandsetstate (0, acquires)) {                    Setexclusiveownerthread (current);                return true;                }} else if (current = = Getexclusiveownerthread ()) {int NEXTC = c + acquires;                if (NEXTC < 0) throw new Error ("Maximum lock count Exceeded");                SetState (NEXTC);            return true;        } return false; }    }

The default Reentrantlock uses a non-fair lock

Public Reentrantlock () {        sync = new Nonfairsync ();    }

The Reentrantlock provides

1. Interruptible and non-disruptive lock operation

2. The Trylock () method is provided for unfair acquisition of the lock once, if unsuccessful, the return

3. Trylock (long timeout, timeunit unit) Limited time lock is provided


public void Lock () {        sync.lock (),    } public void lockinterruptibly () throws Interruptedexception {Sync.acqu    ireinterruptibly (1);    }public Boolean Trylock () {return sync.nonfairtryacquire (1); }public boolean trylock (long timeout, timeunit unit) throws Interruptedexception {return Sync.tryacquir    Enanos (1, Unit.tonanos (timeout));    }public Condition newcondition () {return sync.newcondition (); }


Talk about high concurrency (27) Parsing java.util.concurrent components (ix) Understanding Reentrantlock can be re-entered 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.