ReentrantLock與AQS
類結構
ReentrantLock實現了Lock, java.io.Serializable這兩個介面,裡面有三個靜態內部類:Sync、NonfairSync和FairSync。其中Sync繼承了AbstractQueuedSynchronizer,也就是AQS。另外兩個內部類是對抽象類Sync的實現。
加鎖
在JDK8中,加鎖的流程和JDK11有些區別,JDK8參考美團的程式碼:
// java.util.concurrent.locks.ReentrantLock#NonfairSync // 非公平鎖 static final class NonfairSync extends Sync { ... final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } ... } // java.util.concurrent.locks.ReentrantLock#FairSync static final class FairSync extends Sync { ... final void lock() { acquire(1); } ... }
而在JDK11中,,不管是構建ReentrantLock時,指定的是公平鎖還是非公平鎖,加鎖後都會進入下面的流程:
public void lock() {
sync.acquire(1);
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
其中,公平鎖和非公平鎖對tryAcquire()的實現有一些區別:
static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } } @ReservedStackAccess 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; } /** * Sync object for fair locks */ static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; /** * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. */ @ReservedStackAccess 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; } }
可以看出,無論是公平鎖還是非公平鎖,實現流程都是類似的,只是公平鎖需要通過hasQueuedPredecessors()判斷當前執行緒有沒有前驅節點,如果有的話就不去搶鎖,而是加入等待佇列後等待。
排隊
再看acquire():
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
當前執行緒會通過addWaiter()方法變為等待佇列上的一個節點,然後這個節點會傳入acquireQueued()去執行相應的流程:
private Node addWaiter(Node mode) {
Node node = new Node(mode);
for (;;) {
Node oldTail = tail;
if (oldTail != null) {
node.setPrevRelaxed(oldTail);
if (compareAndSetTail(oldTail, node)) {
oldTail.next = node;
return node;
}
} else {
initializeSyncQueue();
}
}
}
首先新建一個節點,然後採用自旋(for迴圈)的方式將節點加入等待佇列之中。此時會先獲取一下佇列的尾節點,但是由於此時可能有多個執行緒在操作這個佇列,所以僅僅能把當前節點指向這個獲取的尾節點,只有通過CAS(compareAndSetTail)判斷並修改尾節點為當前節點後,才能將剛才的尾節點指向噹噹前節點,否則就一直自旋,直到成功將節點加入佇列。如果當前沒有尾節點,就要將佇列初始化。最終將當前節點返回:
final boolean acquireQueued(final Node node, int arg) {
boolean interrupted = false;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node))
interrupted |= parkAndCheckInterrupt();
}
} catch (Throwable t) {
cancelAcquire(node);
if (interrupted)
selfInterrupt();
throw t;
}
}
自旋判斷當前節點的前驅節點是不是頭節點,如果是,就去嘗試獲取鎖。如果獲取失敗或者不是頭節點,就判斷當前節點是否需要阻塞,也就是當前執行緒是否需要掛起以避免空轉浪費CPU資源。這裡注意第7行的setHead(node)方法,實現是這樣:
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
因為當前節點的執行緒已經獲取了鎖,所以就把當前節點設定為虛節點,把不必要的屬性置為null。
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
}
return false;
}
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled. */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking. */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition. */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate.
*/
static final int PROPAGATE = -3;
如果前置節點的狀態是SIGNAL,就需要將當前執行緒掛起,其他情況都不掛起。但是由於自旋,這個方法會逐漸將所有空閒執行緒都掛起。具體流程由parkAndCheckInterrupt()執行:
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
當執行緒被喚醒後,執行緒會執行上面程式碼塊的第3行,return這個執行緒當前的中斷狀態。
喚醒
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
先去嘗試釋放資源,如果釋放成功,就把頭節點的後繼節點喚醒。因為剛才頭節點獲取鎖以後,就變成了虛節點,所以這裡喚醒的是頭節點的後繼節點:
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 this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
node.compareAndSetWaitStatus(ws, 0);
/*
* Thread to unpark is 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 successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node p = tail; p != node && p != null; p = p.prev)
if (p.waitStatus <= 0)
s = p;
}
if (s != null)
LockSupport.unpark(s.thread);
}
選擇去喚醒一個waitStatus狀態小於0的節點。為什麼倒著遍歷呢?因為之前構建等待佇列的時候,將當前節點掛在獲取的尾節點之後,可能存在多個執行緒併發的問題,更新尾節點要通過CAS。這時候如果正著遍歷就有斷鏈的危險。雖然說倒著遍歷,但是最終選擇的還是最靠近佇列頭的節點。
被喚醒的節點重新獲取鎖:
final boolean acquireQueued(final Node node, int arg) {
boolean interrupted = false;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node))
interrupted |= parkAndCheckInterrupt();
}
} catch (Throwable t) {
cancelAcquire(node);
if (interrupted)
selfInterrupt();
throw t;
}
}