Java Concurrency-reentrantlock source code Analysis

Source: Internet
Author: User

1 About reentrant Locks

Reentrantlock is a reentrant synchronization tool class based on the AQS implementation, which provides two types of Synchronizer implementations, namely, fair lock Fairsync and non-fair lock Nonfairsync. It provides an unconditional, polling, timed, and interruptible lock-fetching operation, all of which are explicitly locked and unlocked. Trylock (),trylock (Long, Timeunit) , respectively, provides a polling-able, timed lock acquisition method. Lock () provides a way to poll for locks unconditionally. lockinterruptibly () provides an interruptible way to obtain locks. Reentrantlock It provides two kinds of locking mechanisms, which are created by default to be non-fair locks. The AQS class structure diagram is as follows:

In a fair lock, the thread is in the order in which they make the request, if the lock is occupied by a thread or there is a waiting thread in the AQS queue, the request thread will queue up until the lock is acquired. Source:

Final void Lock () {     acquire (1);}

An unfair lock attempts a CAS operation to acquire a lock when the request acquires a lock, and is queued if the attempt fails. In a competitive situation, the performance of an unfair lock is higher than a fair lock because an active thread can attempt to acquire a lock more quickly than to recover a blocking line and allocate the lock to it for a short period of time (the wake-up operation of the thread takes extra time, and there is a serious delay between the call to the thread's true operation).

Final void Lock () {            if (compareandsetstate (0, 1))                Setexclusiveownerthread (Thread.CurrentThread ());            else                acquire (1);          } <span style= "Font-family:calibri;" > </span>
2 Nonfairsync Lock

An unfair lock acquisition process that allows queue jumping and directly tries CAS operations.

3 Acquire (1) process

The fetch process for acquire is to try to acquire the lock first, and if it fails, add the current node from the end of the queue to the AQS queues. The operation return value is empty. Interrupts the current thread if the thread is not identified as true when it waits for the procedure.

4 Tryacquire (1) process

The tryacquire (1) operation returns a Boolean type that identifies whether the lock was successfully acquired. If the CAS failure returns false when idle, if the current thread holds the lock, then the thread is re-entering the operation, adding the number of times the lock is re-entered, which returns true. Otherwise the fetch operation fails and returns false.

5 Addwaiter Queue Process

Addwaiter encapsulates the current thread as a queue node and repeatedly attempts to insert the node into the AQS wait queue in a for loop until the operation successfully returns to the node . AQS maintains a list of two properties ofhead and tail , all of which are empty at the beginning. When you add the first node, you first create a virtual head node (that is, a node with no information for new node) and point tail to head. The new node is inserted from the end of the team with CAS Atomic Operations, and the insert operation is added to the wait queue when the thread cannot acquire the lock in the For loop.

6 acquirequeued Queued Thread get lock process

Obtaining a failed lock will continue to retry until the thread is blocked or the lock is acquired. The operation return value is a thread break identity that, if interrupted during blocking, returns true to the acquire operation, which interrupts itself. Why is there such a judgment? I understand: To ensure that the interrupt signal is not flooded during thread blocking. If, after the thread has been Park , the other thread sends the interrupt signal to it, it normally cannot respond to the request. This is necessary for the Parkandcheckinterrupt operation, which checks the interrupt flag and notifies the thread when it is called to interrupt itself. (That is, the acquire selefintrupt () operation).

7 Shouldparkafterfailedacquire

A node attempts to acquire a lock operation, after which failure determines whether the thread needs to be suspended based on the state of the precursor node, which returns a Boolean type value that identifies whether the current node needs to be suspended. The specific process is as follows:

At this point, the lock acquisition operation Flow is described. The result of the reentrantlock Lock operation is that either the thread is suspended or the loop polls for the lock until it is successfully set to a state of 1(occupied state) and then is removed from the queued queue.

8 Unlock Operation analysis

The lock release operation can only be carried out if the front thread is the holder of the lock, or illegalmonitorstateexceptionwill be thrown. Attempts to release the lock and, if it is successful and waits for the queue to be non-empty, wakes its successor. During the wake-up of the successor, the Unpark of the Locksupport is invoked only if its successor is non-empty and non-canceled, otherwise it is looped until it finds a subsequent node that can be recalled.

Java Concurrency-reentrantlock source code Analysis

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.