對於可重入鎖(ReentrantLock)的使用以及它的實現我們都已經熟悉了,本文來探究與其緊密相關的條件隊列的具體實現。
在java中,所謂的條件(condition)是在已經持有鎖的情況下,由newCondition方法創建出來。我們使用它做await或者signal等操作,效果是釋放鎖進入相關的條件隊列,以及傳遞喚醒信號。那麼也就是說調用await直到返回,會發生如下三件事:
- 釋放鎖
- 嘗試進入相關條件隊列並阻塞
- 重新獲取鎖
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
這是個可中斷版本:- 如果中斷,拋出InterruptedException異常(此時還未釋放鎖)。
- 構造相關隊列上的節點。
- 保存鎖的state狀態值,遞減statue值,喚醒鎖隊列中下一個線程。
- 當前線程不在鎖隊列中時,嘗試阻塞當前線程(park),檢查中斷狀態,並在中斷時嘗試從條件隊列中移動節點到鎖隊列(這一步可能會合signal發生競爭,這裏使用CAS-waitStatue來協作),保存中斷狀態值interruptMode。
- 節點已處於鎖隊列,調用acquireQueued,執行正常的鎖獲取流程,並且根據返回值與interruptMode配合重置interruptMode的值。
- 取消不要的節點(輔助操作)。
- 根據interruptMode來拋出InterruptedException或者重置異常狀態,當然可能什麼都不做。
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* Splice onto queue and try to set waitStatus of predecessor to
* indicate that thread is (probably) waiting. If cancelled or
* attempt to set waitStatus fails, wake up to resync (in which
* case the waitStatus can be transiently and harmlessly wrong).
*/
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
這裏的重點是transferForSignal方法:- 嘗試CAS節點的waitStatue值,假如失敗,說明已經不爲Node.CONDITION,返回false引起嘗試下一個。
- 進入鎖隊列,並且嘗試CAS前驅節點的waitStatue改爲Node.SIGNAL,假如失敗(前驅節點被取消),則喚醒當前節點(個人認爲這一步不是必須,因爲解鎖操作中會保持喚醒)。
- 返回true結束。
public final long awaitNanos(long nanosTimeout)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
final long deadline = System.nanoTime() + nanosTimeout;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
transferAfterCancelledWait(node);
break;
}
if (nanosTimeout >= spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
nanosTimeout = deadline - System.nanoTime();
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return deadline - System.nanoTime();
}
超時版本改變了在條件隊列中的阻塞方式,採用了限時阻塞,並且在超時情況下直接調用了轉移節點的方法,返回值表示剩餘時間。