Overview
from the user's point of view, Aqs functions can be divided into two categories: exclusive and shared functions. Its subclasses, either implement and use its exclusive functionality of the API, or use the function of shared locks, instead of using two sets of APIs, even its subclass Reentrantreadwritelock, is also through two internal classes: Read lock and write lock, respectively implemented by two sets of APIs to achieve.
Aqs Main properties, interfaces
Public abstract class Abstractqueuedsynchronizer extends Abstractownablesynchronizer implements Java.io.Serializable {
Synchronization status Value private volatile int state;
Queue header node, generally acquires the lock thread at the head node private transient volatile Node head;
Team tail node private transient volatile node tail;
Queue Cache Object Static final class Node {}
Get exclusive resources, template method public final void acquire (int arg) {if (!tryacquire (ARG) && acquirequeued (add Waiter (node.exclusive), Arg) selfinterrupt (); }
Subclass Implementation Protected Boolean tryacquire (int arg) {throw new unsupportedoperationexception (); }
Release exclusive resource, template method public final Boolean release (int arg) {if (Tryrelease (ARG)) {Node h = head; if (h! = NULL && H.waitstatus! = 0) Unparksuccessor (h); return true; } return false; }
Frees the resource, the subclass implements protected Boolean tryrelease (int arg) {throw new unsupportedoperationexception (); }
Get shared resource, template method public final void acquireshared (int arg) {if (tryacquireshared (ARG) < 0) Doacquire Shared (ARG); }
To obtain a shared resource, the subclass implements protected int tryacquireshared (int arg) {throw new unsupportedoperationexception (); }
Release a shared resource, template method public final Boolean releaseshared (int arg) {if (tryreleaseshared (ARG)) {Doreleasesh Ared (); return true; } return false; }
To release a shared resource, the subclass implements protected Boolean tryreleaseshared (int arg) {throw new unsupportedoperationexception (); }
Is it exclusive? Subclass Implementation Protected Boolean isheldexclusively () {throw new unsupportedoperationexception (); }}
Aqs is a typical template method pattern: Aqs defines template methods, subclasses implement concrete methods.
Template method Pattern: Defines the framework for an algorithm in an operation, and delays some steps into subclasses. The template method pattern allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
The template method pattern is a kind of inheritance-based code reuse technique , which is a kind of behavior-type pattern .
Class diagram
This article introduces the exclusive and shared two modes from the Aqs two typical application classes Reeantrantlock and Countdownlatch respectively.
CAS operations
Many of the thread-safe operations in the JDK depend on the CAS + loop lock-free mode, which is used extensively in Aqs.
Private static final unsafe unsafe = unsafe.getunsafe (); Private static final long stateoffset; Private static final long headoffset; Private static final long tailoffset; Private static final long waitstatusoffset; Private static final long nextoffset; static {try {Stateoffset = Unsafe.objectfieldoffset (abstractqueuedsynchronizer.class.g Etdeclaredfield ("state")); Headoffset = Unsafe.objectfieldoffset (AbstractQueuedSynchronizer.class.getDeclaredField ("Head")); Tailoffset = Unsafe.objectfieldoffset (AbstractQueuedSynchronizer.class.getDeclaredField ("tail")); Waitstatusoffset = Unsafe.objectfieldoffset (Node.class.getDeclaredField ("Waitstatus")); Nextoffset = Unsafe.objectfieldoffset (Node.class.getDeclaredField ("Next")); } catch (Exception ex) {throw new Error (ex);} }/** * Set head node with expected NULL */private FInal boolean compareandsethead (Node update) {return Unsafe.compareandswapobject (this, headoffset, NULL, update); }/** * Set tail node */private Final Boolean Compareandsettail (node expect, node update) {return unsafe. Compareandswapobject (this, tailoffset, expect, update); }/** * Sets a node's Waitstatus */private static final Boolean Compareandsetwaitstatus (node node, int expect, int update) { Return Unsafe.compareandswapint (node, Waitstatusoffset, expect, update); }/** * Sets a node for next */private static final Boolean Compareandsetnext (node node, Node expect, node update) {return UNSAF E.compareandswapobject (node, Nextoffset, expect, update); }
Reentrantlock
Reentrantlock will ensure that only one thread executes this code at the same time, or that only one thread of the lock method will return at the same moment, and the other threads will be suspended until the lock is acquired. In fact, Reentrantlock implementation is an exclusive lock function.
The Reentranctlock internally has an abstract static class sync, inherited from Aqs, overriding the Tryrelease and isheldexclusively methods.
Reentranctlock also has Fairsync and nonfairsync two classes representing both fair and non-fair locks.
Fair Lock: Each thread grabs the lock in the order in which it calls the lock method sequentially, in order to get the lock, similar to queuing.
Unfair lock: Each thread grabs the lock in a variable order, who is lucky and who gets to the lock.
Fair lock
Calling the lock method, the subclass calls the corresponding lock method, which is the abstract method inside the sync class, implemented by subclasses Fairsync and Nonfairsync.
For Fairsync implementations are as follows:
The Acquire method is actually the template method inside the Aqs:
Tryacquire is a method that a subclass needs to implement, and the Addwaiter method is to wrap a thread that does not acquire a lock into a queue of node objects.
protected final Boolean tryacquire (int acquires) {final Thread cu Rrent = Thread.CurrentThread (); int c = GetState (); if (c = = 0) {//if state = = 0 indicates that the lock is not occupied if (!hasqueuedpredecessors () && Compareand SetState (0, acquires)) {//If there are no other threads in the queue stating that no thread is occupying the lock, acquire=1//will update the state via CAS operation, and if the lock is successfully marked, subsequent calls will be due to expected Does not fail for 0.
Setexclusiveownerthread (current); return true; }} else if (current = = Getexclusiveownerthread ()) {//Can be re-entered if the thread has acquired the lock int nextc = C + acquires; if (NEXTC < 0) throw new Error ("Maximum lock count Exceeded"); SetState (NEXTC); return true; } return false; }
If the successful acquisition of the lock returns True, otherwise returns false and puts the current thread into the queue called Addwaiter (node.exclusive), Arg), before taking a look at the Node data structure:
Static final class Node {//Node type: Exclusive and shared//flag is a shared node static final node shared = new node (); Flag with exclusive node waiting for static final node EXCLUSIVE = null; Node Status: SIGNAL, CANCELLED, CONDITION, PROPAGATE//Thread (node) has been canceled, due to timeouts or interrupt, the node to this state is not changed, and the thread will not be blocked again. static final int CANCELLED = 1; Subsequent threads need to wake up, the successor node of the current node is blocked (or is about to block), and the current node must wake the subsequent node before releasing or canceling static final int SIGNAL =-1; The thread waits for the conditional static final int CONDITION =-2; Marked unconditional transmission. Releaseshared should be propagated to other nodes, this only allows setting the head node static final int PROPAGATE =-3; Node Status: SIGNAL, CANCELLED, CONDITION, PROPAGATE, 0, non-negative indication does not require SIGNAL, and is initialized to 0.
Describes the state of the node, Aqs queue, when there is concurrency, will certainly save a certain number of nodes, each node represents the state of a thread, and some threads may not wait for the lock
You need to discard the competition, exit the queue, and some threads will resume execution after waiting for some conditions to be met. volatile int waitstatus; Volatile Node prev; Volatile Node next; volatile thread thread; Thread node nextwaiter;//type node (thread thread, node mode) {//used by addwaiter This.nextwaiter = m Ode This.thread = thread; }}
Private node Addwaiter (node mode) {
Create nodes Node = new (Thread.CurrentThread (), mode); If the queue is not empty, the CAS is directly into the queue, and if it fails, it spins into the queue until it succeeds. Node pred = tail; if (pred! = null) { Node.prev = pred; if (Compareandsettail (pred, node)) { pred.next = node; return node; } } Enq (node);//Enter Queue return node; }
After you put the node in the queue, you also need to suspend the thread, which is done by acquirequeued.
The queue structure of the AQS is composed of nodes of node type, with at least two variables: one wrapper thread and one encapsulated node type. The first time the node is inserted, the first node is an empty node, which means that one thread has acquired the lock, in fact, the first node of the queue represents the node holding the lock.
Spin-in queue
Private node Enq (final node node) {for (;;) { Node t = tail; if (t = = null) {///must initialize, if the queue is empty, create an empty node if (Compareandsethead (new Node ())) tail = head; } else {/ /into queue, unsuccessful, then in loop, success exits Node.prev = t; if (Compareandsettail (t, node)) { t.next = node; return t;}}}
Final Boolean acquirequeued (final node node, int arg) { Boolean failed = true; try { Boolean interrupted = false; for (;;) { final Node p = node.predecessor ();
If the pre node of the current node is the head node, it is the first node to wait for a lock (head is the node that currently holds the lock) and therefore attempts to acquire the lock if (p = = head && tryacquire (ARG)) { Sethead ( node); If the lock succeeds, the head node is removed, the current node becomes the head node p.next = null;//help GC failed = false; return interrupted; }
Detects the status of the previous node to see if the front thread needs to be suspended; only the previous node of the current node is signal, the current node can suspend if (Shouldparkafterfailedacquire (p, node) && parkandcheckinterrupt ())//hangs interrupted = true; } } finally { if (failed) Cancelacquire (node); } }
At this point, a thread of contention for the lock Ends: (1) Success (2) the entry queue is suspended.
If the thread is suspended, it waits for the next wake-up attempt to resume the lock, and the Aqs queue is listed as FIFO.
Here's a look at the release lock process:
Call the release of Aqs:
The Tryrelease method for Reentrantlock calls is implemented in sync:
Protected Final Boolean tryrelease (int releases) { int c = getState ()-releases;
If the thread that freed the lock and the thread that occupies the lock are not the same, throw a nonnegative monitor exception if (Thread.CurrentThread () = Getexclusiveownerthread ()) throw new Illegalmonitorstateexception (); Boolean free = false;
Because it is possible to re-enter the lock, not every release of the lock C equals zero, until the last time the lock is released, the AQS does not need to record the thread that occupies the lock if (c = = 0) {Free = true; Setexclusiveownerthread (null); } SetState (c); return free; }
If the queue is not empty, you need to wake up the subsequent wait nodes:
private void Unparksuccessor (node node) {/* * * If status is negative (i.e., possibly needing signal) try * To clear in anticipation of signalling. It is OK if the this * fails or if status are changed by waiting thread. */int ws = Node.waitstatus; if (WS < 0) compareandsetwaitstatus (node, WS, 0); Set Waitstatus to 0 and the state will not change after */* Thread to Unpark are held in successor, which is normally * just The next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled suc Cessor. *///If the successor of the head node is canceled or NULL, then the reverse traversal, looking for the non-canceled node as the impending wake thread node s = node.next; if (s = = NULL | | s.waitstatus > 0) {s = null; for (node t = tail; t! = null && t! = Node; t = t.prev) if (t.waitstatus <= 0) s = t; } if (s! = null) Locksupport.unpark (S.THREAD); }
Non-fair lock
The only difference from the fair lock is that the lock is acquired in different ways, and the non-fair lock is a preemptive acquisition lock.
Direct CAs modifies the state once (thread preemption acquires the lock) if it returns successfully, otherwise it is queued.
Multithreaded-abstractqueuedsynchronizer (AQS)