一:類ConditionObject,基礎(chǔ)操作和內(nèi)部結(jié)構(gòu)
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
/** First node of condition queue.
* 這里也是用的AQS中的Node,這里只是用到Node中的nextWaiter,不是pre和next,所以是一個(gè)單項(xiàng)鏈表。
* */
private transient Node firstWaiter;
/** Last node of condition queue. */
private transient Node lastWaiter;
/**
* Creates a new {@code ConditionObject} instance.
*/
public ConditionObject() { }
/**
* Adds a new waiter to wait queue.
* 往等待隊(duì)列中添加一個(gè)新的等待者。
* @return its new wait node
*/
private Node addConditionWaiter() {
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out. 如果最后一個(gè)等待著已經(jīng)被取消,則清除掉。
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters();
t = lastWaiter;
}
//這里就將waitStatus中的CONDITION狀態(tài)給用到了。
// Node.CONDITION的注釋中有說(shuō)明,該狀態(tài)表示節(jié)點(diǎn)在條件隊(duì)列中。
Node node = new Node(Thread.currentThread(), Node.CONDITION);
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
/**
* Unlinks cancelled waiter nodes from condition queue.
* Called only while holding lock. This is called when
* cancellation occurred during condition wait, and upon
* insertion of a new waiter when lastWaiter is seen to have
* been cancelled. This method is needed to avoid garbage
* retention in the absence of signals. So even though it may
* require a full traversal, it comes into play only when
* timeouts or cancellations occur in the absence of
* signals. It traverses all nodes rather than stopping at a
* particular target to unlink all pointers to garbage nodes
* without requiring many re-traversals during cancellation
* storms.
* 從條件隊(duì)列中將已取消的等待節(jié)點(diǎn)移除(取消鏈接)。只有在持有鎖的時(shí)候調(diào)用。
* 當(dāng)在條件等待期間發(fā)生取消時(shí),以及在插入新的等待者期間發(fā)現(xiàn)lastWaiter是已取消的時(shí)候,調(diào)用此函數(shù)。
* 需要這種方法來(lái)避免在沒(méi)有信號(hào)的情況下垃圾保留。
* 因此,即使它可能需要一個(gè)完整的遍歷,它也只有在沒(méi)有信號(hào)的情況下發(fā)生超時(shí)或取消才會(huì)起作用。
* 它遍歷所有節(jié)點(diǎn),而不是在特定目標(biāo)處停止,以取消所有指向垃圾節(jié)點(diǎn)的指針的鏈接,而無(wú)需在取消風(fēng)暴期間多次重新遍歷。
* 就是從頭到位遍歷,將所有取消的節(jié)點(diǎn)剔除。
*/
private void unlinkCancelledWaiters() {
Node t = firstWaiter;
Node trail = null;
while (t != null) {
Node next = t.nextWaiter;
if (t.waitStatus != Node.CONDITION) {
t.nextWaiter = null;
if (trail == null)
firstWaiter = next;
else
trail.nextWaiter = next;
if (next == null)
lastWaiter = trail;
}
else
trail = t;
t = next;
}
}
}
總結(jié):
- 此類中也是使用Node來(lái)維護(hù)了一個(gè)單向鏈表,維護(hù)所有等待該Condition的線程隊(duì)列,和AQS中的同步隊(duì)列不是一個(gè)隊(duì)列,
這兩個(gè)隊(duì)列是會(huì)交互的。 - 此類中的Node的waitStatus都是Condition,表示等待狀態(tài),表示該節(jié)點(diǎn)處于等待隊(duì)列中。
- 兩個(gè)基本的操作,添加新節(jié)點(diǎn)和刪除取消的節(jié)點(diǎn)。
二:await邏輯
public class ConditionObject implements Condition, java.io.Serializable {
/**
* Implements interruptible condition wait.
* 實(shí)現(xiàn)可中斷的條件等待。(下面的注釋已經(jīng)大體描述清楚每一步的邏輯了)
* <ol>
* <li> If current thread is interrupted, throw InterruptedException.
* 如果當(dāng)前線程已經(jīng)被中斷,則拋出InterruptedException。
*
* <li> Save lock state returned by {@link #getState}.
* getState方法返回保存的鎖狀態(tài)。
*
* <li> Invoke {@link #release} with saved state as argument,
* throwing IllegalMonitorStateException if it fails.
* 通過(guò)保存狀態(tài)作為參數(shù)來(lái)調(diào)用release方法,如果失敗則拋出IllegalMonitorStateException。
*
* <li> Block until signalled or interrupted.
* 阻塞至被信號(hào)通知或被中斷。
*
* <li> Reacquire by invoking specialized version of
* {@link #acquire} with saved state as argument.
* 通過(guò)調(diào)用acquire的專用版本并將保存的狀態(tài)作為參數(shù)來(lái)重新獲取
*
* <li> If interrupted while blocked in step 4, throw InterruptedException.
* 如果在步驟4中阻塞時(shí)被中斷,則拋出InterruptedException。
* </ol>
*/
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter(); //創(chuàng)建一個(gè)condition類型的Node并入鏈
int savedState = fullyRelease(node);//完全釋放并返回當(dāng)時(shí)的state
int interruptMode = 0;
//判斷是否在AQS的同步隊(duì)列中,不在表示還未signal,在了表示已經(jīng)被signal了
while (!isOnSyncQueue(node)) {
//1. fullyRelease后node不在AQS的同步隊(duì)列中了,所以會(huì)立即進(jìn)入該方法,后續(xù)該線程被park
//其他線程調(diào)用signal時(shí)會(huì)將此線程unpark,又會(huì)將此線程添加到AQS的同步隊(duì)列中去,結(jié)束wile循環(huán)。后面在看signal。
//2. 會(huì)不會(huì)此時(shí)已經(jīng)在AQS的同步隊(duì)列中了呢,應(yīng)該也是會(huì)的,就是此線程剛fullyRelease,
// 其它線程signal的時(shí)候又將該node給加到了同步隊(duì)列中,此時(shí)就不park了,直接往后執(zhí)行就可以了。
//3. 如果park之前被中斷了,那么此處的park會(huì)不起作用,直接往下繼續(xù)執(zhí)行。
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
//阻塞的過(guò)程中被中斷了,就直接break出來(lái)
//checkInterruptWhileWaiting用來(lái)檢測(cè)中斷的時(shí)機(jī)并將node加到AQS隊(duì)列中,后面再細(xì)看。
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
//acquireQueued需要再次獲取鎖資源
// 這里會(huì)存在獲取不到鎖資源的情況嗎?不會(huì),即使上面不是因?yàn)閟ignal喚醒而unpark,而是因?yàn)橹袛喽鴨拘眩瑥亩鴪?zhí)行到這里,
// acquireQueued也必須獲取到鎖,獲取不要會(huì)繼續(xù)給park住,然后排隊(duì)等待獲取,
// 而且acquireQueued方法是不支持中斷的,只能等到獲取成功才會(huì)繼續(xù)執(zhí)行。而且await之前執(zhí)行了lock操作,之后還會(huì)執(zhí)行unlock操作,
//如果說(shuō)獲取不到那不就出錯(cuò)了嘛。
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled 清理被取消的節(jié)點(diǎn)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);//將中斷狀態(tài)給報(bào)告出去
}
/**
* Invokes release with current state value; returns saved state.
* Cancels node and throws exception on failure.
* 使用當(dāng)前state值調(diào)用release;返回保存的state。失敗時(shí)取消節(jié)點(diǎn)并拋出異常。
*
* @param node the condition node for this wait
* @return previous sync state
*/
final int fullyRelease(Node node) {
boolean failed = true;
try {
int savedState = getState();
//為什么不是release(1)呢?因?yàn)槿绻强芍厝氲模热缯f(shuō)thread1鎖了2次,這個(gè)saveState為2,
//release(1)不會(huì)完全釋放當(dāng)前鎖,所以這個(gè)方法叫做fullyRelease,完全釋放。
//為什么又要返回這個(gè)savedState呢? thread1鎖了2次,await的時(shí)候會(huì)通過(guò)該方法釋放掉,其它線程會(huì)再次獲得鎖,
//那么等thread1被signal時(shí),會(huì)重新acquire(savedState)獲取鎖,并將state的設(shè)置到正確狀態(tài),
// thread1 lock了兩次,肯定會(huì)unlock兩次,如果state為1,第二次unlock時(shí)就會(huì)報(bào)錯(cuò)。
if (release(savedState)) {
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
/** Mode meaning to reinterrupt on exit from wait */
//該模式意味著退出等待時(shí)重新中斷,發(fā)出信號(hào)后被中斷
private static final int REINTERRUPT = 1;
/** Mode meaning to throw InterruptedException on exit from wait */
//模式意味著退出等待時(shí)拋出InterruptedException,發(fā)出信號(hào)前被中斷
private static final int THROW_IE = -1;
/**
* Checks for interrupt, returning THROW_IE if interrupted
* before signalled, REINTERRUPT if after signalled, or
* 0 if not interrupted.
* 檢查中斷,
* 如果在發(fā)出信號(hào)前被中斷,則返回THROW_IE,
* 發(fā)出信號(hào)后被中斷則返回REINTERRUPT,
* 沒(méi)有被中斷則返回0.
*/
private int checkInterruptWhileWaiting(Node node) {
return Thread.interrupted() ?
(transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
0;
}
/**
* Transfers node, if necessary, to sync queue after a cancelled wait.
* Returns true if thread was cancelled before being signalled.
* 如有必要,在取消等待后將節(jié)點(diǎn)傳輸?shù)酵疥?duì)列。如果線程在發(fā)出信號(hào)之前被取消,則返回true。
*
* @param node the node
* @return true if cancelled before the node was signalled
*/
final boolean transferAfterCancelledWait(Node node) {
if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
//場(chǎng)景:一個(gè)線程在await,其它線程一直沒(méi)有對(duì)其進(jìn)行signal,然后該線程又被interrupt了。
// await進(jìn)行park前,已經(jīng)將鎖給釋放掉了,中斷后會(huì)從park中醒過(guò)來(lái)繼續(xù)acquireQueued獲取鎖,
//acquireQueued操作的是同步隊(duì)列中的node,所以需要將node加到AQS的同步隊(duì)列中去。
enq(node);
return true;
}
/*
* If we lost out to a signal(), then we can't proceed
* until it finishes its enq(). Cancelling during an
* incomplete transfer is both rare and transient, so just
* spin.
* 如果我們輸給了一個(gè)signal(),直到它完成enq()否則我們無(wú)法繼續(xù)。
* 在不完全傳輸過(guò)程中的取消既罕見(jiàn)又短暫,所以只需旋轉(zhuǎn)即可。
*
* 啥意思呢? signal的第一步就會(huì)將node的狀態(tài)從CONDITION改為0,那么該方法上面的CAS操作將會(huì)失敗,
* 出現(xiàn)的原因是因?yàn)閕nterrupt和signal方法幾乎同時(shí)執(zhí)行,但是signal的CAS操作比此方法的CAS操作快了一步。
*/
while (!isOnSyncQueue(node))
// 循環(huán)一下等待node在signal中被enq到同步隊(duì)列中去。
Thread.yield();
return false;
}
/**
* Throws InterruptedException, reinterrupts current thread, or
* does nothing, depending on mode.
* 基于mode 來(lái)拋出InterruptedException、重新中斷當(dāng)前線程或者啥都不做。
*/
private void reportInterruptAfterWait(int interruptMode)
throws InterruptedException {
if (interruptMode == THROW_IE)
throw new InterruptedException();
else if (interruptMode == REINTERRUPT)
selfInterrupt();
}
}
總結(jié):
-
正常的等待邏輯比較直觀,分為以下幾步(一個(gè)線程await,一個(gè)線程signal):
- 1.0 lock()獲取鎖、await()等待。
- 1.1 addConditionWaiter創(chuàng)建一個(gè)Condition狀態(tài)的節(jié)點(diǎn)并加入到隊(duì)列。
- 1.2 fullyRelease 將鎖釋放,并保存好AQS中的狀態(tài)(savedState)。
- 1.3 park線程,等待其它線程signal通知。
- 1.4 其它線程調(diào)用signal,以及unlock,等待線程從park中喚醒
- 1.5 acquireQueued 重新獲取鎖,并將1.2中的savedState狀態(tài)從新設(shè)置到AQS的state字段。
- 1.6 執(zhí)行業(yè)務(wù)邏輯,最后釋放鎖 unlock()。
-
中斷發(fā)生,并且發(fā)生在signal之前(一個(gè)線程await,一個(gè)線程signal):
- 2.1 發(fā)生在park之前,那么park不起作用,直接往后執(zhí)行。
- 2.2 發(fā)生在park之后,線程從park中喚醒。
- 2.3 transferAfterCancelledWait 將node的狀態(tài)成功的從CONDITION改為0,并且將node添加到AQS的同步隊(duì)列。
- 2.4 上一步可能將node的狀態(tài)從CONDITION改為0失敗,表示signal已經(jīng)發(fā)生了,這時(shí)算作中斷發(fā)生在signal之后。
- 2.5 acquireQueued 重新獲取鎖,并將savedState狀態(tài)重新設(shè)置到AQS的state字段。
- 2.6 reportInterruptAfterWait 將拋出InterruptedException。
-
中斷發(fā)生,并且發(fā)生在signal之后
- 3.1 其它線程調(diào)用signal,以及unlock,等待線程從park中喚醒
- 3.2 acquireQueued 重新獲取鎖,并將savedState狀態(tài)重新設(shè)置到AQS的state字段。
- 3.3 reportInterruptAfterWait 將重新執(zhí)行Thread.interrupt().
多個(gè)線程await,被多次signal,每次signal則喚醒一個(gè)await的線程。
多個(gè)線程await,被signalAll同時(shí)喚醒,其實(shí)應(yīng)該說(shuō)是將等待隊(duì)列中的線程逐個(gè)喚醒。
三:signal邏輯
public class ConditionObject implements Condition, java.io.Serializable {
/**
* Moves the longest-waiting thread, if one exists, from the
* wait queue for this condition to the wait queue for the
* owning lock.
* 將等待時(shí)間最長(zhǎng)的線程(如果存在)從該條件的等待隊(duì)列移動(dòng)到擁有鎖的等待隊(duì)列。
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
* returns {@code false}
*/
public final void signal() {
if (!isHeldExclusively())
//如果不是當(dāng)前線程獲得的鎖,則拋出異常
throw new IllegalMonitorStateException();
Node first = firstWaiter;//firstWaiter表示等待時(shí)間最長(zhǎng)的節(jié)點(diǎn)。
if (first != null)
doSignal(first);
}
/**
* Removes and transfers nodes until hit non-cancelled one or
* null. Split out from signal in part to encourage compilers
* to inline the case of no waiters.
* 刪除和傳輸節(jié)點(diǎn),直到命中未取消的一個(gè)node或null。
* 從signal中分離出來(lái),部分是為了鼓勵(lì)編譯器在沒(méi)有等待者的情況下inline。
* @param first (non-null) the first node on condition queue
*/
private void doSignal(Node first) {
do {
//將first的下個(gè)節(jié)點(diǎn)作為新的first
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);//如果轉(zhuǎn)換失敗,繼續(xù)循環(huán),繼續(xù)轉(zhuǎn)換下一個(gè)節(jié)點(diǎn)
}
/**
* Transfers a node from a condition queue onto sync queue.
* Returns true if successful.
* 將節(jié)點(diǎn)從等待隊(duì)列傳輸?shù)酵疥?duì)列。成功則返回true。
* @param node the node
* @return true if successfully transferred (else the node was
* cancelled before signal)
*/
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
* 如果不能改變waitStatus,則該node已經(jīng)被取消了。
* 因?yàn)閍wait的時(shí)候,如果發(fā)生interrupt,則會(huì)將此狀態(tài)設(shè)置為0,表示已經(jīng)取消等待。
*/
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).
* 拼接到隊(duì)列上,并嘗試設(shè)置前置線程的waitStatus,以指示線程(可能)正在等待。
* 如果已取消或嘗試設(shè)置waitStatus失敗,則喚醒以重新同步(在這種情況下,waitStatus可能會(huì)暫時(shí)錯(cuò)誤,且不會(huì)造成傷害)
* 通過(guò)AQS的enq方法將節(jié)點(diǎn)傳輸?shù)紸QS的同步隊(duì)列上
*/
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
//被取消了或者狀態(tài)修改失敗,直接unpark
LockSupport.unpark(node.thread);
return true;
}
/**
* Moves all threads from the wait queue for this condition to
* the wait queue for the owning lock.
* 將此條件的所有線程從等待隊(duì)列移動(dòng)到擁有鎖的等待隊(duì)列。
*/
public final void signalAll() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
/**
* Removes and transfers all nodes.
* @param first (non-null) the first node on condition queue
*/
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
//循環(huán)所有的等待節(jié)點(diǎn),依次transferForSignal
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
}
總結(jié):
- signal 單個(gè)喚醒,則將第一個(gè)節(jié)點(diǎn)firstWaiter狀態(tài)從CONDITION改為0,并加等待隊(duì)列轉(zhuǎn)移到同步隊(duì)列中。
- signalAll 則是從第一個(gè)循環(huán)到最后一個(gè),都處理一遍。
- 這里的signal并不會(huì)直接將等待節(jié)點(diǎn)的線程unpark,而是加到了同步隊(duì)列,等通知者線程unlock了,release邏輯會(huì)將等待線程unpark。