View the ReentrantLock source code understanding record !, Reentrantlock source code

Source: Internet
Author: User

View the ReentrantLock source code understanding record !, Reentrantlock source code

ReentrantLock lock = new ReentrantLock (); lock. lock (); lock. unlock (); // when class X {// is used in the ReentrantLock source code to instantiate ReentrantLock, // If the boolean parameter is added, // true is the fair mode, // flase is the unfair mode, // The default value is unfair. In unfair mode, the new thread may not be able to get the lock first, and later it may not be able to get the lock ReentrantLock lock = new ReentrantLock (); public void m () {lock. lock (); try {//... method body} finally {lock. unlock () ;}}// lock in fair mode. The final void lock () {acquire (1 );}/ /In unfair mode, the lock will first attempt to set the current thread as the exclusive owner thread according to the result returned by the compareAndSetState method, // if it fails, perform the acquire operation again. Final void lock () {// compareAndSetState is set based on cas. // if the current status value is equal to the expected value, // The synchronization status is set to the specified update value. // CompareAndSetState (0, 1) the expected value is 0, and the value is changed to 1. // if the current state value is 0, the state value is set to 1, // set the current thread to exclusive. If (compareAndSetState (0, 1) // set the current Thread to the exclusive owner Thread setExclusiveOwnerThread (Thread. currentThread (); else acquire (1) ;}// use the exclusive mode to ignore interruptions. Public final void acquire (int arg) {if (! TryAcquire (arg) & acquireQueued (addWaiter (Node. EXCLUSIVE), arg) selfInterrupt (); // interrupt thread} protected final boolean tryAcquire (int acquires) {return nonfairTryAcquire (acquires);} // execute an unfair tryLock. // TryAcquire is implemented in the subclass, but it is unfair to try the trylock method. Final boolean nonfairTryAcquire (int acquires) {// obtain the current Thread final Thread current = Thread. currentThread (); // get the value of state int c = getState (); // if the value of state is null, no one uses the lock // if the expected value is 0, set state to the set value if (c = 0) {if (compareAndSetState (0, acquires) {setExclusiveOwnerThread (current); return true ;}} // if the value of state is not 0, determine whether the exclusive owner thread is its own. // If the exclusive owner thread is its own, state value plus the value 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;} static final class Node {// indicates the tag of the Node waiting in the sharing mode. static final Node SHARED = new Node (); // indicates the tag of the Node waiting in exclusive mode. static final Node EXCLUSIVE = null; // The waiting thread in the synchronization queue has timed out or has been interrupted. // The waiting thread needs to be canceled from the synchronization queue, when the node enters this state, the static final int CANCELLED = 1; // the thread of the subsequent node is in the waiting state, and if the thread of the current node is released The synchronization status or the node is canceled. // The subsequent node will be notified, so that the thread of the subsequent node can run static final int SIGNAL =-1; // The node is waiting in the queue, the node thread waits on the Condition. // when other threads call the Signal () method for the Condition, the node will be transferred from the waiting queue to the synchronization queue, static final int CONDITION =-2; // indicates that the next shared synchronization state acquisition will be unconditionally propagated to static final int PROPAGATE =-3; // The waiting status of the thread volatile int waitStatus;} // create a Node private Node addWaiter (Node mode) for the current thread and the specified mode) {Node node = new Node (Thread. c UrrentThread (), mode); Node pred = tail; if (pred! = Null) {// if the end node is not null // you can specify the parent node of the newly created node as the end node. prev = pred; // determine whether the current status value is equal to the expected end node pred // if the end node of the expected value is equal to the end node, update the current synchronization status value to the end node if (compareAndSetTail (pred, node )) {// The successor node of the last node is the newly created node pred. next = node; return node; }}enq (node); return node;} private Node enq (final Node node) {(;;) {// get the last Node node Node t = tail; if (t = null) {// initialize the synchronization queue // create a new node new Node () as the header node // use the header node as the end node // at this time, the End Node of the queue and the header node are the same node // Since enq is an endless loop, the system checks whether the end Node is empty again, // you have set the header Node and the end Node, and enter the else statement if (compareAndSetHead (new Node () tail = head ;} else {// The tail node is not empty. Set the forward node of the input node as the tail node. prev = t; if (compareAndSetTail (t, node) {// judge whether the node is the expected tail node t. if so, update the tail node t to node, // set the successor node of t as the input node, and the end node is the input node t. next = node; return t ;}}// the synchronization status is continuously obtained in an endless loop.
// If it cannot be obtained, the thread in the Node will be blocked. // The blocked thread can only rely on the outgoing queue operation of its precursor node or the blocked thread to interrupt the final boolean acquireQueued (final Node node, int arg) {boolean failed = true; try {boolean interrupted = false; for (;) {// obtain the final node p = Node of the node. predecessor (); if (p = head & tryAcquire (arg) {// if the forward node of the input node is head, // if the current thread can still obtain the lock, set the passed node to head setHead (node); p. next = null; // help GC failed = false; return interrupted ;} // The supervisor checks and updates the status of nodes that fail to be obtained. // parkAndCheckInterrupt blocks the current thread and returns whether the thread is interrupted. if (shouldParkAfterFailedAcquire (p, node) & parkAndCheckInterrupt ()) interrupted = true ;}} finally {if (failed) // cancel an ongoing Retrieval Attempt cancelAcquire (node) ;}/// check and update the status of the node that failed to be retrieved. Private static boolean shouldParkAfterFailedAcquire (Node pred, Node node) {int ws = pred. waitStatus; if (ws = Node. SIGNAL) // returns true if the thread is blocked. Return true; if (ws> 0) {do {node. prev = pred. prev;} while (pred. waitStatus> 0); pred. next = node;} else {// judge the waitStatus value of the pred Node, whether it is the expected ws // If yes, update it to node. SIGNAL, blocking pred compareAndSetWaitStatus (pred, ws, Node. SIGNAL);} return false ;}


  

 

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.