Pre-JDK 5 used synchronized for multi-thread locks, and JDK 5 used Java. util. Concurrent. locks. Lock as the interface. In addition, java. util. Concurrent. locks. readwritelock provides a pair of locks for concurrent read/write. Reentrantlock Is A reentrant lock class in Java. util. Concurrent. locks. It has better performance and can be interrupted under high competition conditions. In-depth analysis of the source code of reentrantlock helps us understand the underlying mechanisms such as thread scheduling, lock implementation, interruption, and signal triggering to achieve better concurrent programs.
Let's take a look at the most common reentrantlock code lock.
public void lock() { sync.lock(); }
The code is very simple. directly call the lock method of the member variable sync.
/** Synchronizer providing all implementation mechanics */ private final Sync sync;
Sync is the abstract static internal class of reentrantlock that inherits abstractqueuedsynchronizer. Many operations are actually implemented through abstractqueuedsynchronizer. abstractqueuedsynchronizer is a very important type, many implementations in the concurrent package depend on him. The complete design idea can refer to the http://gee.cs.oswego.edu/dl/papers/aqs.pdf
. Fairsync and nonfairsync are specific sub-classes, which correspond to fair locks and non-fair locks respectively. In fact, both of them are similar. I know that one of them is similar to the other. In reality, the throughput of the fair lock is much smaller than that of the unfair lock. So the following analysis takes the unfair lock as an example. Before specific implementation, we have to say abstractqueuedsynchronizer. The two most important data members are implemented by the current lock status and waiting for the linked list.
/** * Head of the wait queue, lazily initialized. Except for * initialization, it is modified only via method setHead. Note: * If head exists, its waitStatus is guaranteed not to be * CANCELLED. */ private transient volatile Node head; /** * Tail of the wait queue, lazily initialized. Modified only via * method enq to add new wait node. */ private transient volatile Node tail; /** * The synchronization state. */ private volatile int state;
State records the number of times the current lock is locked. If it is 0, it is not locked. Locks are implemented by changing the state. The function compareandsetstate is used to change the state. CAS primitive is called to ensure the atomicity of operations. Node is a static internal class. The important fields are as follows:
/*** The waiting status of a node. A node may be in the following states: * cancelled = 1: The Node operation is interrupted due to timeout or the corresponding thread. The node should not be left in this status. Once this status is reached, it will be kicked out from the chlorophyll queue. * Signal =-1: The successor node of the node is (or will become) blocked State (for example, through locksupport. park () operation), so once a node is released (unlocked) or canceled, you need to wake up (locksupport. unpack () its successor node. * Condition =-2: indicates that the thread corresponding to the node is blocked because it does not meet a condition. * 0: normal. All new non-condition nodes are in this status. * A non-negative value indicates that the node does not need to be notified (awakened ). */Volatile int waitstatus;/*** the previous node of this node. The waitstatus of a node depends on the status of the previous node. */Volatile node Prev;/*** the next node of this node. Whether the next node is awakened (uppark () depends on whether the current node is released. */Volatile node next;/*** the thread bound to the node. */Volatile thread;/*** the node for the next condition, because the condition mode is exclusive, * therefore, there is a simple queue to describe the thread nodes on condition. */Node nextwaiter;
Another important attribute is in abstractqueuedsynchronizer's parent class abstractownablesynchronizer.
/** * The current owner of exclusive mode synchronization. */ private transient Thread exclusiveOwnerThread;
After learning about these basics, let's look at the lock function of nonfairsync.
/*** Performs lock. try immediate barge, backing up to normal * acquire on failure. */final void lock () {// If the lock is not locked by any thread, use CAs to preemptible if (compareandsetstate (0, 1 )) // If the lock is successfully obtained, set the current thread to the lock owner setexclusiveownerthread (thread. currentthread (); else // If the lock has been occupied, try to lock, acquire (1 );}
The acquir method is provided by abstractqueuedsynchronizer.
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
1. If tryacquire (ARG) is successful, there is no problem. The lock has been obtained and the entire lock () process ends. If the request fails, perform operation 2.
2. addwaiter creates an exclusive node and adds the node to the end of the chlorophyll Queue (analyzed later ). Operation 3.
3. The acquirequeued spin attempts to obtain the lock. The failure depends on the previous node to determine whether to suspend (Park () until the lock is successfully obtained. Operation 4.
4. If the current thread has been interrupted, selfinterrupt will interrupt the current thread (clear the interrupt bit ).
This is a bit complicated. Next we will analyze it step by step.
Tryacquire is replaced by nonfairsync override and directly calls sync. nonfairtryacquire. The Code is as follows:
/*** 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 the lock is idle, try to lock if (C = 0) {// set the current thread as the lock owner if (compareandsetstate (0, acquires) {setexclusiveownerthread (current); Return true ;}} // if the current thread is the lock owner, modify the lock status count 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 ;}
A little familiar, with nonfairsync
The lock function of is a bit similar. If this method fails, false is returned, that is, tryacquire fails. acquirequeued (addwaiter (node. Exclusive), ARG) is performed ). Let's first look at the addwaiter function.
/** * Creates and enqueues node for given thread and mode. * * @param current the thread * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared * @return the new node */ private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; if (pred != null) { node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; }
Encapsulate the current thread into a node and then put it into the node queue of abstractqueuedsynchronizer. The case that the queue is empty and multi-thread concurrency is considered here, so the processing is quite tangled, but the code is not complicated and can be understood with patience. The above is a part of a node, such as a queue. The new node is returned only when the queue is not empty and the new node is successfully inserted to the end. Otherwise, Enq (node) is enabled.
/*** Inserts node into queue, initializing if necessary. see picture above. * @ Param node the node to insert * @ return node's predecessor */private node Enq (final node) {for (;) {node T = tail; // if it is null, create the header node if (t = NULL) {// must initialize node H = new node (); // dummy header H. next = node; node. prev = H; If (compareandsethead (H) {tail = node; return H ;}// if the queue is not empty due to concurrency, put the current node at the end of the else {node. prev = T; If (compareandsettail (T, node) {T. next = node; return t ;}}}}
The next step is to call the acquirequeued method to enable the thread to go to the disabled state and try to get the lock every time it is awakened. If it fails, the thread will continue to be disabled.
/*** Acquires in exclusive uninterruptible mode for thread already in * queue. used by condition wait methods as well as acquire. ** @ Param node the node * @ Param Arg the acquire argument * @ return {@ code true} if interrupted while waiting */FINAL Boolean acquirequeued (final node, int Arg) {try {Boolean interrupted = false; For (;) {final node P = node. predecessor (); // if the current node is directly behind the head The attempt to obtain the lock will not compete with other threads in the waiting queue, but will compete with the thread that tries to obtain the lock and has not yet entered the waiting queue. This is an important difference between unfair locks and fair locks. If (P = Head & tryacquire (ARG) {sethead (node); p. next = NULL; // help GC return interrupted;} // if it is not a successor to the head or the lock fails to be obtained, check whether the current thread needs to be disabled // yes, until it is locked. release wakeup or thread interruption if (shouldparkafterfailedacquire (p, node) & parkandcheckinterrupt () interrupted = true ;}} catch (runtimeexception ex) {cancelacquire (node ); throw ex ;}}
Shouldparkafterfailedacquire does a very important task: clears the waiting queue according to the status and sets the waiting signal. Here, we need to first describe waitstatus, which is a member variable of the static internal class node of abstractqueuedsynchronizer, used to record the thread Wait Status of the node. the waiting status is 0 when the queue is started. If the waiting status is canceled, it is set to node. cancelled. If the thread needs to wake up when the lock is released, other threads in the waiting queue will be set to node. signal, there is also a status node. condition is not discussed here.
/*** Checks and updates status for a node that failed to acquire. * returns true if thread shoshould block. this is the main signal * control in all acquire loops. requires that Pred = node. prev ** @ Param Pred node's predecessor holding status * @ Param node the node * @ return {@ code true} If thread shocould block */Private Static Boolean shouldparkafterfailedacquire (node Pred, node node) {int Ws = Pred. waitstatus; If (Ws = node. signal)/** if the waitstatus of the previous node is set to signal, that is, the previous node has not obtained the lock, * returns true, indicating the current node (thread) it should be Park () */return true; If (WS> 0) {/** if the waiting status of the previous node is waitstatus> 0, that is, if the previous node is cancelled, * remove the previous node and recursive this operation until the waitstatus of all previous nodes is <= 0. */Do {node. prev = Pred. prev;} while (Pred. waitstatus> 0); Pred. next = node;} When else {// equals 0 // The waiting status of the previous node is waitstatus = 0, and the status bit of the previous node is changed to singal, // indicates that a node is waiting for processing. You need to determine whether the park () compareandsetwaitstatus (Pred, WS, node. signal);}/** here, false must be returned. It is possible that the front node has released the lock, * However, because its waitstatus is not set to signal when the lock is released, it does not trigger the wake-up Wait thread operation. * Therefore, you must use return false to retry obtaining the lock */return false ;}
If shouldparkafterfailedacquire returns true, parkandcheckinterrupt is called.
. The implementation is as follows. It is easy to directly disable the thread and wait for it to be awakened or interrupted. I have done some homework on thread. interrupted () in Java. Here the thread is blocked. When waking up, the lock will be obtained again. If it fails, the thread will continue to be blocked. Even thread. interrupted () cannot be interrupted. The threads that want to interrupt and exit after waiting for a long time can call reentrantloc. lockinterruptibly ().
/** * Convenience method to park and then check if interrupted * * @return {@code true} if interrupted */ private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }