序
做開發(fā)也有幾年了, 對1.5的concurrent并發(fā)包了解并不是很深入, 近來正好有空做個深入的學習
基礎
在看 AQS 源碼之前, 需要對下面的知識點有個大致的了解, 看源碼會快很多
- Unsafe 相關, 主要是 CAS 原子鎖
- CLH 鎖
- 管程模型
Unsafe CAS原子鎖
CAS原子鎖是基于CPU的原子指令 compareAndSet
實現的命令, 該操作是原子的, 要么成功要么失敗
CLH 鎖
- CLH是一種基于隊列的自旋鎖
- 過來獲取鎖的線程全部排排隊
- 只有排在第一個的線程才有執(zhí)行權
- 其他的線程自旋判斷排在前面一個節(jié)點的狀態(tài)值, 不是允許執(zhí)行狀態(tài)則一直自旋等待
管程模型
- 管程模型是實現線程同步鎖的一種方式, synchronized 的實現模式其實也是這個
- 管程主要的組成部分是: 多線程共享資源, 限制并發(fā)的進入隊列, 不滿足執(zhí)行條件的等待隊列和一些出隊, 入隊的方法
- 進入管程需要先判斷是否有執(zhí)行條件, 沒有則在進入隊列中等待
- 進入管程后, 不滿足執(zhí)行條件后, 進入等待隊列等待
- 執(zhí)行完后離開管程
代碼分析
源碼做了詳細的注釋
/**
* 該處存在兩個隊列 <br>
* 同步隊列 : 爭搶不到鎖的線程進入同步隊列<br>
* 條件隊列 : 不滿足繼續(xù)運行條件的await后進入條件隊列
*
*/
@SuppressWarnings("restriction")
public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable {
private static final long serialVersionUID = 7373984972572414691L;
protected AbstractQueuedSynchronizer() {
}
/**
* 條件隊列和同步隊列的節(jié)點類
*/
static final class Node {
// 標記節(jié)點在共享模式下等待
static final Node SHARED = new Node();
// 標記節(jié)點在排他模式下等待
static final Node EXCLUSIVE = null;
// 狀態(tài)值, 表示線程已經取消了, 線程超時或者被中斷
static final int CANCELLED = 1;
// 節(jié)點還有一個中間狀態(tài)值0, 為0是空白狀態(tài), 后面的節(jié)點也未進入park
// 狀態(tài)值, 表示后續(xù)節(jié)點需要被喚醒
static final int SIGNAL = -1;
// 狀態(tài)值, 表示線程在條件隊列中, 即Condition隊列, 調用Condition.await()后進入該狀態(tài)值
static final int CONDITION = -2;
// 狀態(tài)值, 表示一下個acquireShared應該是無條件傳播
static final int PROPAGATE = -3;
// 節(jié)點的等待狀態(tài)值
volatile int waitStatus;
// Lock.lock()獲取不到鎖的線程進入同步隊列
// 同步隊列中當前節(jié)點的前面的節(jié)點
volatile Node prev;
// 同步隊列中當前節(jié)點的下一個節(jié)點
volatile Node next;
// 當前節(jié)點的線程
volatile Thread thread;
// 維持Condition條件隊列的屬性
// Condition.await() 等待隊列中的下一個等待節(jié)點, 節(jié)點在CONDITION狀態(tài)下
Node nextWaiter;
// 判斷節(jié)點是否在共享模式下
final boolean isShared() {
return nextWaiter == SHARED;
}
// 獲取前置節(jié)點
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() {
}
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
// 同步隊列的頭節(jié)點, 不為空時該節(jié)點的狀態(tài)不能是CANCELLED
private transient volatile Node head;
// 同步隊列的尾部節(jié)點, 只能通過enq添加一個新的同步節(jié)點
private transient volatile Node tail;
// 線程進入同步器的次數
// state>0 說明同步鎖已經被某個線程線程拿了
private volatile int state;
// 獲取重入次數
protected final int getState() {
return state;
}
// 設置重入次數
protected final void setState(int newState) {
state = newState;
}
// 設置重入次數
protected final boolean compareAndSetState(int expect, int update) {
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
// Queuing utilities
// 線程自旋時間
// > spinForTimeoutThreshold線程才會被park
// < spinForTimeoutThreshold的將自旋
static final long spinForTimeoutThreshold = 1000L;
/**
* for循環(huán)強制將節(jié)點插入同步隊列的尾部
*
* @param 待插入的node
* @return 插入前的tail
*/
private Node enq(final Node node) {
// 因為存在并發(fā), 需要循環(huán)執(zhí)行, 直到當前把當前線程作為節(jié)點追加到同步隊列尾部
for (;;) {// 循環(huán)直到將當前節(jié)點放置到等待隊伍尾部
Node t = tail;
if (t == null) { // 尾結點為null, 表示等待隊列沒有節(jié)點, 需要創(chuàng)建一個虛節(jié)點
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;// node.prev=tail
if (compareAndSetTail(t, node)) {// 設置當前節(jié)點為尾節(jié)點
t.next = node;// tail.next = node
return t;
}
}
}
}
/**
* 創(chuàng)建線程節(jié)點, 并且添加到同步隊列尾部
*
* @param mode 同步模式 Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return 新創(chuàng)建的節(jié)點
*/
private Node addWaiter(Node mode) {
// 創(chuàng)建當前線程的等待節(jié)點
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail;
if (pred != null) {
node.prev = pred;
// 該處存在并發(fā), 需要進行原子操作
if (compareAndSetTail(pred, node)) {// 嘗試將當前節(jié)點放置到等待隊伍末尾
pred.next = node;
return node;
}
}
enq(node);// 上面嘗試失敗, 執(zhí)行下面的強制放入
return node;
}
// 設置頭節(jié)點
private void setHead(Node node) {
head = node;
// 用不著的屬性全部設置為null
node.thread = null;// help GC
node.prev = null;
}
/**
* 喚醒同步隊列中的后續(xù)節(jié)點<br>
*
* @param node the node
*/
private void unparkSuccessor(Node node) {
// 設置當前節(jié)點的等待狀態(tài)值為0
int ws = node.waitStatus;
if (ws < 0)// 如果節(jié)點狀態(tài)<0, 將當前等待狀態(tài)設置為0
compareAndSetWaitStatus(node, ws, 0);// waitStatus==0, 表示當前線程即將完成, 需要喚醒后面的節(jié)點
// unpark下一個節(jié)點, 如果下一個節(jié)點cancelled或者不存在則繼續(xù)解鎖下面的節(jié)點
Node s = node.next;
if (s == null || s.waitStatus > 0) {// 找個下一個沒有Canceled的節(jié)點, 然后喚醒
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);// 喚醒
}
/**
* 共享模式下釋放鎖
*/
private void doReleaseShared() {
// 循環(huán)解鎖頭節(jié)點線程, 被解鎖的線程將離開等待隊列, 新的頭節(jié)點將會別代替
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {// 如果節(jié)點狀態(tài)是喚醒
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // 狀態(tài)設置失敗再次設置狀態(tài)值0
unparkSuccessor(h);// 設置成功后喚醒后續(xù)節(jié)點
} else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
/**
* 設置頭節(jié)點然后傳播
*
* @param node
* @param propagate
*/
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
// 傳播
if (propagate > 0 || h == null || h.waitStatus < 0 || (h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();
}
}
// Utilities for various versions of acquire
/**
* 取消正在進行的獲取請求 <br>
* <ol>
* <li>刪除當前節(jié)點</li>
* <li>設置后面節(jié)點的狀態(tài)值SIGNAL或者喚醒后續(xù)節(jié)點</li>
* </ol>
*
* @param node the node
*/
private void cancelAcquire(Node node) {
if (node == null)
return;
// 節(jié)點的線程設置為null
node.thread = null;
// Skip cancelled 所有的前置節(jié)點
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// waitState不為canceled的第一個前置節(jié)點的next節(jié)點
// 可能是當前節(jié)點也可能不是
Node predNext = pred.next;
// 設置當前節(jié)點的等待狀態(tài)為CANCELLED
node.waitStatus = Node.CANCELLED;
// 如果自己是tail, 則移除它
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head && ((ws = pred.waitStatus) == Node.SIGNAL
|| (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) && pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);// 設置前一個節(jié)點的后一個節(jié)點, 將當前節(jié)點排除在等待隊列之外
} else {
// 什么情況下需要喚醒后面的節(jié)點 ?
// 1.如果當前節(jié)點是頭節(jié)點
// 2.不是頭節(jié)點, 但是當前節(jié)點的前面的節(jié)點狀態(tài)值不是SIGNAL, 但是設置SIGNAL失敗時
// 3.前面的節(jié)點為null, 當前節(jié)點已經成為了新的頭節(jié)點
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
/**
* 條件: 節(jié)點的線程進入Prak狀態(tài)時, 需先設置前置節(jié)點的等待狀態(tài)是SIGNAL <br>
* 因為獲取鎖失敗后需要進入Park, 所以需要強制設置前置節(jié)點的waitStatus=SIGNAL <br>
* 所以該方法需在for循環(huán)中使用, 循環(huán)直到前置節(jié)點的waitStatus=SIGNAL <br>
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
// 前節(jié)點狀態(tài)為-1, 說明當前節(jié)點需要被喚醒
return true;
if (ws > 0) {// 狀態(tài)>0是節(jié)點都是CANCELLED
// 前節(jié)點狀態(tài)>0, 找到前狀態(tài)<=0的節(jié)點連在它的后面
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
// 前節(jié)點狀態(tài)<0時, 設置前節(jié)點的等待狀態(tài)為-1
// 下一個循環(huán)就可以將當前線程Park
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
// 打斷當前線程, 目的是重置中斷標識位
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
/**
* Park當前線程, 等待中斷獲取unpark
*
* @return 線程是否被中斷喚醒
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);// 當前線程Park, 等待被unpark獲取被中斷
return Thread.interrupted();// 該方法會重置中斷位, 后續(xù)的操作需要重新設置中斷位
}
/**
* 節(jié)點請求排隊<br>
* 節(jié)點已經進入同步隊列中排隊, 排隊中再次嘗試獲取鎖<br>
* 如果獲取不到則設置前置節(jié)點的waitStatus=SIGNAL后Park等待
*
* @param node 當前節(jié)點
* @param arg 鎖重入次數
* @return 排隊被中斷返回true, 正常喚醒返回false
*/
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
// 第一個是虛節(jié)點, 當節(jié)點是第二個時就可以搶資源了, 如果獲取鎖成功了, 下面就不需要執(zhí)行直接返回
// 其他情況是設置前節(jié)點的等待狀態(tài)為-1, 線程Park后等待喚醒
// for循環(huán), 該處必須要是循環(huán)之內, 線程要是被中斷喚醒后, 沒有搶到鎖繼續(xù)Park
for (;;) {
final Node p = node.predecessor();// 前節(jié)點
if (p == head && tryAcquire(arg)) {// 前面節(jié)點是頭節(jié)點, 而且獲取到了鎖
setHead(node);// 釋放前節(jié)點
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node)// 強制設置前置節(jié)點的waitStatus=SIGNAL
&& parkAndCheckInterrupt())// Park當前線程
interrupted = true;// 不是中斷喚醒不執(zhí)行
}
} finally {
if (failed)// 上面的操作出現異常, 取消當前線程的請求
cancelAcquire(node);
}
}
/**
* 排他模式下, 先獲取鎖, 獲取不到則Park, 如果線程被打斷則拋出InterruptedException
*
* @param arg 重入鎖的次數
* @throws InterruptedException
*/
private void doAcquireInterruptibly(int arg) throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);// 添加排他等待者
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**
* 在時間限定下請求鎖, 每個多少個ns時間周期請求鎖
*
* @param arg the acquire argument
* @param nanosTimeout max wait time
* @return {@code true} if acquired
*/
private boolean doAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.EXCLUSIVE);// 添加到等待隊列
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {// 獲取到鎖則執(zhí)行
setHead(node);
p.next = null; // help GC
failed = false;
return true;
}
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
if (shouldParkAfterFailedAcquire(p, node)// 線程應該park
&& nanosTimeout > spinForTimeoutThreshold// 等待時間>自旋超時時間
)
LockSupport.parkNanos(this, nanosTimeout);// 線程Park
if (Thread.interrupted())// 線程被打斷則拋出異常, 沒有打斷則繼續(xù)請求鎖
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**
* 共享模式下請求鎖
*
* @param arg the acquire argument
*/
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**
* 共享模式下請求鎖, 拋出異常
*
* @param arg the acquire argument
*/
private void doAcquireSharedInterruptibly(int arg) throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
/**
* 共享模式下時間間隔請求鎖
*
* @param arg the acquire argument
* @param nanosTimeout max wait time
* @return {@code true} if acquired
*/
private boolean doAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException {
if (nanosTimeout <= 0L)
return false;
final long deadline = System.nanoTime() + nanosTimeout;
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return true;
}
}
nanosTimeout = deadline - System.nanoTime();
if (nanosTimeout <= 0L)
return false;
if (shouldParkAfterFailedAcquire(p, node) && nanosTimeout > spinForTimeoutThreshold)
LockSupport.parkNanos(this, nanosTimeout);
if (Thread.interrupted())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// Main exported methods
/**
* 請求鎖, 該處實現需要注意并發(fā)情況, 使用CAS原子鎖執(zhí)行操作
*
* @param arg
* @return
*/
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
/**
* 釋放排他鎖 <br>
* 1. 設置同步器state=0 <br>
* 2. 設置同步器排他線程為null
*
* @param arg
* @return
*/
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
/**
* 共享模式下獲取鎖
*
* @param arg
* @return
*/
protected int tryAcquireShared(int arg) {
throw new UnsupportedOperationException();
}
/**
* 共享模式下釋放鎖
*
* @param arg
* @return
*/
protected boolean tryReleaseShared(int arg) {
throw new UnsupportedOperationException();
}
// 判斷當前線程是否持有鎖
protected boolean isHeldExclusively() {
throw new UnsupportedOperationException();
}
/**
* 先請求鎖, 請求不到則到等待隊列
*
* @param arg
*/
public final void acquire(int arg) {
// tryAcquire請求鎖, 請求成功離開
// 請求不成功繼續(xù)執(zhí)行acquireQueued, 請求線程入同步隊列末等待
if (!tryAcquire(arg)// 搶鎖
&& acquireQueued(addWaiter(Node.EXCLUSIVE), arg)// 搶不到排隊, 返回值是精心設計的
)
// 鎖請求失敗, 線程Park被中斷時執(zhí)行下面的方法
selfInterrupt();// 重置中斷
}
/**
* 先請求鎖, 請求不到則到等待隊列
*
* @param arg
* @throws InterruptedException
*/
public final void acquireInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
/**
* 嘗試獲取排他鎖, 獲取不到則間隔獲取
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
* @param nanosTimeout the maximum number of nanoseconds to wait
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquire(arg) || doAcquireNanos(arg, nanosTimeout);
}
/**
* 釋放鎖, 釋放完成后喚醒后續(xù)節(jié)點
*
* @param arg the release argument. This value is conveyed to
* {@link #tryRelease} but is otherwise uninterpreted and can
* represent anything you like.
* @return the value returned from {@link #tryRelease}
*/
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
// 需要判斷當前節(jié)點的waitStatus值
// 后面節(jié)點在進入Park是會將前面的waitStatus設置為-1, 如果是-1時就需要喚醒后面的線程節(jié)點
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);// 喚醒后面的節(jié)點
return true;
}
return false;
}
/**
* Acquires in shared mode, ignoring interrupts. Implemented by first invoking
* at least once {@link #tryAcquireShared}, returning on success. Otherwise the
* thread is queued, possibly repeatedly blocking and unblocking, invoking
* {@link #tryAcquireShared} until success.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquireShared} but is otherwise uninterpreted and can
* represent anything you like.
*/
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
/**
* Acquires in shared mode, aborting if interrupted. Implemented by first
* checking interrupt status, then invoking at least once
* {@link #tryAcquireShared}, returning on success. Otherwise the thread is
* queued, possibly repeatedly blocking and unblocking, invoking
* {@link #tryAcquireShared} until success or the thread is interrupted.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquireShared} but is otherwise uninterpreted and can
* represent anything you like.
* @throws InterruptedException if the current thread is interrupted
*/
public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
/**
* Attempts to acquire in shared mode, aborting if interrupted, and failing if
* the given timeout elapses. Implemented by first checking interrupt status,
* then invoking at least once {@link #tryAcquireShared}, returning on success.
* Otherwise, the thread is queued, possibly repeatedly blocking and unblocking,
* invoking {@link #tryAcquireShared} until success or the thread is interrupted
* or the timeout elapses.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquireShared} but is otherwise uninterpreted
* and can represent anything you like.
* @param nanosTimeout the maximum number of nanoseconds to wait
* @return {@code true} if acquired; {@code false} if timed out
* @throws InterruptedException if the current thread is interrupted
*/
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
return tryAcquireShared(arg) >= 0 || doAcquireSharedNanos(arg, nanosTimeout);
}
/**
* Releases in shared mode. Implemented by unblocking one or more threads if
* {@link #tryReleaseShared} returns true.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryReleaseShared} but is otherwise uninterpreted and can
* represent anything you like.
* @return the value returned from {@link #tryReleaseShared}
*/
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// Queue inspection methods
/**
* 等待隊列中是否還有等待線程
*
* <p>
* In this implementation, this operation returns in constant time.
*
* @return {@code true} if there may be other threads waiting to acquire
*/
public final boolean hasQueuedThreads() {
return head != tail;
}
/**
* 等待隊列中是否還有內容
*
* <p>
* In this implementation, this operation returns in constant time.
*
* @return {@code true} if there has ever been contention
*/
public final boolean hasContended() {
return head != null;
}
/**
* Returns the first (longest-waiting) thread in the queue, or {@code null} if
* no threads are currently queued.
*
* <p>
* In this implementation, this operation normally returns in constant time, but
* may iterate upon contention if other threads are concurrently modifying the
* queue.
*
* @return the first (longest-waiting) thread in the queue, or {@code null} if
* no threads are currently queued
*/
public final Thread getFirstQueuedThread() {
// handle only fast path, else relay
return (head == tail) ? null : fullGetFirstQueuedThread();
}
/**
* Version of getFirstQueuedThread called when fastpath fails
*/
private Thread fullGetFirstQueuedThread() {
/*
* The first node is normally head.next. Try to get its thread field, ensuring
* consistent reads: If thread field is nulled out or s.prev is no longer head,
* then some other thread(s) concurrently performed setHead in between some of
* our reads. We try this twice before resorting to traversal.
*/
Node h, s;
Thread st;
if (((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null)
|| ((h = head) != null && (s = h.next) != null && s.prev == head && (st = s.thread) != null))
return st;
/*
* Head's next field might not have been set yet, or may have been unset after
* setHead. So we must check to see if tail is actually first node. If not, we
* continue on, safely traversing from tail back to head to find first,
* guaranteeing termination.
*/
Node t = tail;
Thread firstThread = null;
while (t != null && t != head) {
Thread tt = t.thread;
if (tt != null)
firstThread = tt;
t = t.prev;
}
return firstThread;
}
/**
* 判斷線程是否已經進入等待隊列
*
* <p>
* 遍歷等待隊列檢查線程是否存在
*
* @param thread the thread
* @return {@code true} if the given thread is on the queue
* @throws NullPointerException if the thread is null
*/
public final boolean isQueued(Thread thread) {
if (thread == null)
throw new NullPointerException();
for (Node p = tail; p != null; p = p.prev)
if (p.thread == thread)
return true;
return false;
}
/**
* 判斷排隊個第一個是否是排他模式節(jié)點
*/
final boolean apparentlyFirstQueuedIsExclusive() {
Node h, s;
return (h = head) != null && (s = h.next) != null && !s.isShared() && s.thread != null;
}
/**
* 檢查我前面是否還有別的線程在等待
*
* @return
*/
public final boolean hasQueuedPredecessors() {
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t && ((s = h.next) == null || s.thread != Thread.currentThread());
}
// Instrumentation and monitoring methods
/**
* 獲取節(jié)點的排隊的隊伍長度
*
* @return the estimated number of threads waiting to acquire
*/
public final int getQueueLength() {
int n = 0;
for (Node p = tail; p != null; p = p.prev) {
if (p.thread != null)
++n;
}
return n;
}
/**
* 獲取所有的排隊線程
*
* @return the collection of threads
*/
public final Collection<Thread> getQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
return list;
}
/**
* 獲取所有的排他模式的排隊線程
*
* @return the collection of threads
*/
public final Collection<Thread> getExclusiveQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
if (!p.isShared()) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
}
return list;
}
/**
* 獲取所有的共享模式下的排隊線程
*
* @return the collection of threads
*/
public final Collection<Thread> getSharedQueuedThreads() {
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node p = tail; p != null; p = p.prev) {
if (p.isShared()) {
Thread t = p.thread;
if (t != null)
list.add(t);
}
}
return list;
}
/**
* AQS toString
*
* @return a string identifying this synchronizer, as well as its state
*/
public String toString() {
int s = getState();
String q = hasQueuedThreads() ? "non" : "";
return super.toString() + "[State = " + s + ", " + q + "empty queue]";
}
// Internal support methods for Conditions
/**
* 當前節(jié)點是否在同步隊列中
*
* @param node the node
* @return true if is reacquiring
*/
final boolean isOnSyncQueue(Node node) {
// 節(jié)點狀態(tài)是CONDITION, 或者節(jié)點沒有前置節(jié)點, 說明節(jié)點不在隊列里面
if (node.waitStatus == Node.CONDITION// 節(jié)點狀態(tài)是await, 那肯定是不在同步隊列中, 應該在等待隊列里面
|| node.prev == null// 前一個節(jié)點是null, 則是頭節(jié)點, 那肯定不需要進行同步
)
return false;
// 節(jié)點有后置節(jié)點, 說明節(jié)點肯定在
if (node.next != null) // If has successor, it must be on queue
return true;
return findNodeFromTail(node);
}
/**
* 從等待隊列的最后往前遍歷, 檢測節(jié)點是的在排隊
*
* @return true if present
*/
private boolean findNodeFromTail(Node node) {
Node t = tail;
for (;;) {
if (t == node)
return true;
if (t == null)
return false;
t = t.prev;
}
}
/**
* 將節(jié)點從條件隊列轉換到同步隊列
*
* @param node the node
* @return true if successfully transferred (else the node was cancelled before
* signal)
*/
final boolean transferForSignal(Node node) {
// 節(jié)點狀態(tài)轉換為0
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
// 節(jié)點狀態(tài)轉換失敗
return false;
// 節(jié)點加入到同步隊列尾
Node p = enq(node);// 前置節(jié)點
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
// 前面的節(jié)點取消了, 或者前面節(jié)點設置SIGNAL失敗, 當前節(jié)點unpark
LockSupport.unpark(node.thread);
return true;
}
/**
* Transfers node, if necessary, to sync queue after a cancelled wait. Returns
* true if thread was cancelled before being signalled.
*
* @param node the node
* @return true if cancelled before the node was signalled
*/
final boolean transferAfterCancelledWait(Node node) {
if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
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.
*/
while (!isOnSyncQueue(node))
Thread.yield();
return false;
}
/**
* 釋放所有的可重入的鎖
*
* @param node
* @return
*/
final int fullyRelease(Node node) {
boolean failed = true;
try {
int savedState = getState();// 鎖的重入數量
if (release(savedState)) {// 釋放全部
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
// Instrumentation methods for conditions
/**
* Queries whether the given ConditionObject uses this synchronizer as its lock.
*
* @param condition the condition
* @return {@code true} if owned
* @throws NullPointerException if the condition is null
*/
public final boolean owns(ConditionObject condition) {
return condition.isOwnedBy(this);
}
/**
* Queries whether any threads are waiting on the given condition associated
* with this synchronizer. Note that because timeouts and interrupts may occur
* at any time, a {@code true} return does not guarantee that a future
* {@code signal} will awaken any threads. This method is designed primarily for
* use in monitoring of the system state.
*
* @param condition the condition
* @return {@code true} if there are any waiting threads
* @throws IllegalMonitorStateException if exclusive synchronization is not held
* @throws IllegalArgumentException if the given condition is not associated
* with this synchronizer
* @throws NullPointerException if the condition is null
*/
public final boolean hasWaiters(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.hasWaiters();
}
/**
* Returns an estimate of the number of threads waiting on the given condition
* associated with this synchronizer. Note that because timeouts and interrupts
* may occur at any time, the estimate serves only as an upper bound on the
* actual number of waiters. This method is designed for use in monitoring of
* the system state, not for synchronization control.
*
* @param condition the condition
* @return the estimated number of waiting threads
* @throws IllegalMonitorStateException if exclusive synchronization is not held
* @throws IllegalArgumentException if the given condition is not associated
* with this synchronizer
* @throws NullPointerException if the condition is null
*/
public final int getWaitQueueLength(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.getWaitQueueLength();
}
/**
* Returns a collection containing those threads that may be waiting on the
* given condition associated with this synchronizer. Because the actual set of
* threads may change dynamically while constructing this result, the returned
* collection is only a best-effort estimate. The elements of the returned
* collection are in no particular order.
*
* @param condition the condition
* @return the collection of threads
* @throws IllegalMonitorStateException if exclusive synchronization is not held
* @throws IllegalArgumentException if the given condition is not associated
* with this synchronizer
* @throws NullPointerException if the condition is null
*/
public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
if (!owns(condition))
throw new IllegalArgumentException("Not owner");
return condition.getWaitingThreads();
}
/**
* 條件對象, 獲取到鎖的線程的進入await的隊列
*/
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
// 條件隊列的第一個元素
private transient Node firstWaiter;
// 條件隊列的最后一個元素
private transient Node lastWaiter;
public ConditionObject() {
}
// Internal methods
/**
* 將當前線程添加到條件隊列中
*
* @return 當前線程的隊列節(jié)點
*/
private Node addConditionWaiter() {
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
if (t != null && t.waitStatus != Node.CONDITION) {
unlinkCancelledWaiters();
t = lastWaiter;
}
Node node = new Node(Thread.currentThread(), Node.CONDITION);
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
/**
* 移除canceled節(jié)點, 將條件隊列轉換為同步隊列
*
* @param first (non-null) the first node on condition queue
*/
private void doSignal(Node first) {
do {
if ((firstWaiter = first.nextWaiter) == null)// 下一個waiter設置為firstWaiter
lastWaiter = null;// 下一個waiter為null, 設置lastWaiter=null
first.nextWaiter = null;// 清除nextWaiter
} while (!transferForSignal(first) && (first = firstWaiter) != null);
}
/**
* 將所有的條件隊列轉換為同步隊列
*
* @param first (non-null) the first node on condition queue
*/
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
/**
* 刪除條件隊列中所有waitStatus!=CONDITION的節(jié)點
*/
private void unlinkCancelledWaiters() {
Node t = firstWaiter;
Node trail = null;// 追蹤遍歷過程中節(jié)點狀態(tài)是CONDITION的最新的節(jié)點
while (t != null) {
Node next = t.nextWaiter;// 下一個節(jié)點
if (t.waitStatus != Node.CONDITION) {// 當前節(jié)點的狀態(tài)不是 CONDITION
t.nextWaiter = null;// 清除
if (trail == null)//
firstWaiter = next;
else
trail.nextWaiter = next;
if (next == null)// await隊列尾
lastWaiter = trail;
} else
trail = t;
t = next;
}
}
// public methods
/**
* 喚醒等待隊列的第一個線程
*/
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
/**
* 喚醒所有條件隊列的等待節(jié)點
*
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} returns
* {@code false}
*/
public final void signalAll() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignalAll(first);
}
/**
* Implements uninterruptible condition wait.
* <ol>
* <li>Save lock state returned by {@link #getState}.
* <li>Invoke {@link #release} with saved state as argument, throwing
* IllegalMonitorStateException if it fails.
* <li>Block until signalled.
* <li>Reacquire by invoking specialized version of {@link #acquire} with saved
* state as argument.
* </ol>
*/
public final void awaitUninterruptibly() {
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean interrupted = false;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if (Thread.interrupted())
interrupted = true;
}
if (acquireQueued(node, savedState) || interrupted)
selfInterrupt();
}
// 出隊列后重新打斷
private static final int REINTERRUPT = 1;
// 出隊列后throw InterruptedException
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.
*/
private int checkInterruptWhileWaiting(Node node) {
return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0;
}
/**
* Throws InterruptedException, reinterrupts current thread, or does nothing,
* depending on mode.
*/
private void reportInterruptAfterWait(int interruptMode) throws InterruptedException {
if (interruptMode == THROW_IE)
throw new InterruptedException();
else if (interruptMode == REINTERRUPT)
selfInterrupt();
}
/**
* Implements interruptible condition wait.
* <ol>
* <li>如果當前線程被打斷則拋出異常
* <li>Save lock state returned by {@link #getState}.
* <li>請求Invoke {@link #release} 釋放上面獲取lock狀態(tài), 失敗則拋出IllegalMonitorStateException
* <li>阻塞等待喚醒或者打斷
* <li>重新爭搶鎖, 搶到則繼續(xù)運行
* <li>If interrupted while blocked in step 4, throw InterruptedException.
* </ol>
*/
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();// 將線程添加到await隊列
int savedState = fullyRelease(node);// 釋放所有的重入鎖
int interruptMode = 0;//
while (!isOnSyncQueue(node)) {// 檢查線程是否在同步隊列中
// 不在同同步隊列中就應該阻塞
LockSupport.park(this);// park
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);
}
/**
* Implements timed condition wait.
* <ol>
* <li>If current thread is interrupted, throw InterruptedException.
* <li>Save lock state returned by {@link #getState}.
* <li>Invoke {@link #release} with saved state as argument, throwing
* IllegalMonitorStateException if it fails.
* <li>Block until signalled, interrupted, or timed out.
* <li>Reacquire by invoking specialized version of {@link #acquire} with saved
* state as argument.
* <li>If interrupted while blocked in step 4, throw InterruptedException.
* </ol>
*/
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();
}
/**
* Implements absolute timed condition wait.
* <ol>
* <li>If current thread is interrupted, throw InterruptedException.
* <li>Save lock state returned by {@link #getState}.
* <li>Invoke {@link #release} with saved state as argument, throwing
* IllegalMonitorStateException if it fails.
* <li>Block until signalled, interrupted, or timed out.
* <li>Reacquire by invoking specialized version of {@link #acquire} with saved
* state as argument.
* <li>If interrupted while blocked in step 4, throw InterruptedException.
* <li>If timed out while blocked in step 4, return false, else true.
* </ol>
*/
public final boolean awaitUntil(Date deadline) throws InterruptedException {
long abstime = deadline.getTime();
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (System.currentTimeMillis() > abstime) {
timedout = transferAfterCancelledWait(node);
break;
}
LockSupport.parkUntil(this, abstime);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null)
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
return !timedout;
}
/**
* Implements timed condition wait.
* <ol>
* <li>If current thread is interrupted, throw InterruptedException.
* <li>Save lock state returned by {@link #getState}.
* <li>Invoke {@link #release} with saved state as argument, throwing
* IllegalMonitorStateException if it fails.
* <li>Block until signalled, interrupted, or timed out.
* <li>Reacquire by invoking specialized version of {@link #acquire} with saved
* state as argument.
* <li>If interrupted while blocked in step 4, throw InterruptedException.
* <li>If timed out while blocked in step 4, return false, else true.
* </ol>
*/
public final boolean await(long time, TimeUnit unit) throws InterruptedException {
long nanosTimeout = unit.toNanos(time);
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
final long deadline = System.nanoTime() + nanosTimeout;
boolean timedout = false;
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
if (nanosTimeout <= 0L) {
timedout = 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 !timedout;
}
// support for instrumentation
/**
* Returns true if this condition was created by the given synchronization
* object.
*
* @return {@code true} if owned
*/
final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
return sync == AbstractQueuedSynchronizer.this;
}
/**
* Queries whether any threads are waiting on this condition. Implements
* {@link AbstractQueuedSynchronizer#hasWaiters(ConditionObject)}.
*
* @return {@code true} if there are any waiting threads
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} returns
* {@code false}
*/
protected final boolean hasWaiters() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION)
return true;
}
return false;
}
/**
* Returns an estimate of the number of threads waiting on this condition.
* Implements
* {@link AbstractQueuedSynchronizer#getWaitQueueLength(ConditionObject)}.
*
* @return the estimated number of waiting threads
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} returns
* {@code false}
*/
protected final int getWaitQueueLength() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
int n = 0;
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION)
++n;
}
return n;
}
/**
* Returns a collection containing those threads that may be waiting on this
* Condition. Implements
* {@link AbstractQueuedSynchronizer#getWaitingThreads(ConditionObject)}.
*
* @return the collection of threads
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} returns
* {@code false}
*/
protected final Collection<Thread> getWaitingThreads() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
ArrayList<Thread> list = new ArrayList<Thread>();
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
if (w.waitStatus == Node.CONDITION) {
Thread t = w.thread;
if (t != null)
list.add(t);
}
}
return list;
}
}
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.getDeclaredField("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);
}
}
// 設置頭節(jié)點
private final boolean compareAndSetHead(Node update) {
return unsafe.compareAndSwapObject(this, headOffset, null, update);
}
// 設置等待隊列的尾節(jié)點
private final boolean compareAndSetTail(Node expect, Node update) {
return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
}
// 設置節(jié)點的等待狀態(tài)值
private static final boolean compareAndSetWaitStatus(Node node, int expect, int update) {
return unsafe.compareAndSwapInt(node, waitStatusOffset, expect, update);
}
// 設置當前節(jié)點的下一個節(jié)點值
private static final boolean compareAndSetNext(Node node, Node expect, Node update) {
return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
}
}