源码解析
await
先看一下流程图
// java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#await()
public final void await() throws InterruptedException {
// 当前线程中断直接抛出中断异常
if (Thread.interrupted())
throw new InterruptedException();
// 添加当前线程到等待队列
Node node = addConditionWaiter();
// 释放锁,并保存原锁数
int savedState = fullyRelease(node);
int interruptMode = 0;
// 判断此节点是否在 condition 队列中,此节点为 CONDITION ,一定不在队列中
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);
}
生成CONDITION节点加入condition队列
// java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#addConditionWaiter
private Node addConditionWaiter() {
// 判断是否为持有锁的线程
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
//
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
if (t != null && t.waitStatus != Node.CONDITION) {
// 清理队列中不为CONDITION的node
unlinkCancelledWaiters();
// 重新获取尾节点
t = lastWaiter;
}
Node node = new Node(Node.CONDITION);
if (t == null)
// 队列为空,当前为首节点
firstWaiter = node;
else
// 放入队末
t.nextWaiter = node;
// 当前节点一定为尾节点
lastWaiter = node;
return node;
}
这里判断当前线程是否持有锁
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
遍历队列并清除非CONDITION节点
// java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#unlinkCancelledWaiters
private void unlinkCancelledWaiters() {
// 从头节点开始遍历
Node t = firstWaiter;
Node trail = null;
while (t != null) {
// 获取后继节点
Node next = t.nextWaiter;
// 判断当前节点状态为CONDITION
if (t.waitStatus != Node.CONDITION) {
// 当前节点状态不为CONDITION
// Unlink当前节点
t.nextWaiter = null;
if (trail == null)
// tail为null,表示还未遍历的为CONDITION的节点
// 首节点为next(相当于从头开始,最下面t=next 新的循环开始了===>Node t = firstWaiter;Node trail = null;)
// 把首节点赋值为下一节点(保证了将首节点更新为第一个CONDITION节点)
firstWaiter = next;
else
// tail不为null
// 这里把不为CONDITION的节点串联起来
trail.nextWaiter = next;
if (next == null)
// 遍历结束,将最后一个CONDITION节点保存为尾节点
lastWaiter = trail;
}
else
// 从开始到结尾遍历队列,tail保存最后一个状态为CONDITION的节点
trail = t;
// 遍历下一个节点
t = next;
}
}
释放当前线程占有的锁
// java.util.concurrent.locks.AbstractQueuedSynchronizer#fullyRelease
final int fullyRelease(Node node) {
try {
// 获取计数
int savedState = getState();
// 将当前锁计数全部释放(正常情况一定是true)
if (release(savedState))
return savedState;
throw new IllegalMonitorStateException();
} catch (Throwable t) {
node.waitStatus = Node.CANCELLED;
throw t;
}
}
释放锁并且唤醒AQS中的等待线程
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
// 释放后继节点
unparkSuccessor(h);
return true;
}
return false;
}
唤醒锁
@ReservedStackAccess
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
// 判断占有锁的线程是否为当前线程
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
// 为0表示没有当前线程释放成功(不为0,可能重入)
if (c == 0) {
free = true;
// 将独占线程设为空
setExclusiveOwnerThread(null);
}
// 保存状态
setState(c);
return free;
}
释放后继节点
// java.util.concurrent.locks.AbstractQueuedSynchronizer#unparkSuccessor
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)
compareAndSetWaitStatus(node, 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为头节点(空节点),查找有效的后继节点
Node s = node.next;
// 如果node1为null或者为(CANCELLED),重新查找
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
// 从尾部开始获取第一个不为取消(CANCELLED)的后继节点
if (t.waitStatus <= 0)
// 节点不为取消(CANCELLED)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);// 唤醒后继者
}
判断是否在AQS队列中
final boolean isOnSyncQueue(Node node) {
if (node.waitStatus == Node.CONDITION || node.prev == null)
// 如果节点为CONDITION或者上一个节点为null,说明不在condition 队列
// 这里的node一定是CONDITION,所以返回false
return false;
if (node.next != null) // If has successor, it must be on queue
return true;
/*
* node.prev can be non-null, but not yet on queue because
* the CAS to place it on queue can fail. So we have to
* traverse from tail to make sure it actually made it. It
* will always be near the tail in calls to this method, and
* unless the CAS failed (which is unlikely), it will be
* there, so we hardly ever traverse much.
*/
return findNodeFromTail(node);
}
挂起时线程中断
final boolean transferAfterCancelledWait(Node node) {
// 这里一定会成功
if (node.compareAndSetWaitStatus(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;
}
循环将节点放入队列
// java.util.concurrent.locks.AbstractQueuedSynchronizer#enq
private Node enq(Node node) {
for (;;) {
// 保存现在的尾节点
Node oldTail = tail;
// 尾节点不为null
if (oldTail != null) {
// 这里把当前节点prev指向尾节点
node.setPrevRelaxed(oldTail);
// CAS操作把当前节点设置为尾节点
if (compareAndSetTail(oldTail, node)) {
// 把旧尾节点的next指向当前节点
oldTail.next = node;
return oldTail;
}
} else {
// 队列为空 初始化一个头节点
initializeSyncQueue();
}
}
}
// java.util.concurrent.locks.AbstractQueuedSynchronizer#acquireQueued
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;
}
// 判断当前线程是否挂起(仅当前驱节点为signal)
if (shouldParkAfterFailedAcquire(p, node))
// 挂起当前线程
// |有什么用?挂起当前线程,唤醒后返回中断状态
interrupted |= parkAndCheckInterrupt();
}
} catch (Throwable t) {
cancelAcquire(node);
if (interrupted)
selfInterrupt();
throw t;
}
}
tryAcquire 方法实际调用ReentrantLock的Sync的tryAcquire方法
// java.util.concurrent.locks.ReentrantLock.Sync#nonfairTryAcquire
@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;
}
}
// 我们刚刚被signal或者signalAll,不会进入到这里
else if (current == getExclusiveOwnerThread()) {
// 如果当前线程占有锁,锁计数器加1
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
// 保存state
setState(nextc);
return true;
}
return false;
}
// java.util.concurrent.locks.AbstractQueuedSynchronizer#shouldParkAfterFailedAcquire
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.
*/
// 如果前驱节点为 SIGNAL 状态,表示前驱节点等待释放,则当前节点可以安全挂起
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
// 前驱节点为 cancelled 状态,把当前节点指向前驱节点的前驱节点(找到不为cancelled的前驱节点)
// 这里就是过滤掉 cancelled 状态的节点
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.
*/
// waitStatus为 0 或者 PROPAGATE,暗示此节点不能挂起
// CAS把前驱节点设为 SIGNAL
pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
// 挂起当前线程
LockSupport.park(this);
// 获取线程中断状态
return Thread.interrupted();
}
signal
这个方法简单来说就是把condition队列中的首个不为cancelled的节点,放入AQS的队列中
// java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#signal
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
// 获取首节点
Node first = firstWaiter;
// 队列中为空直接返回
if (first != null)
// 唤醒首节点
doSignal(first);
}
从首节点开始找到一个不为cancelled的节点放入AQS队列中
// java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#doSignal
private void doSignal(Node first) {
do {
// 获取后继节点,把后继节点赋值给首节点并判断null
if ( (firstWaiter = first.nextWaiter) == null)
// 如果为null,把lastWaiter设置为null
lastWaiter = null;
// unlink 首节点
first.nextWaiter = null;
// 如果first为 cancelled,并且队列不为空转换下一个节点
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
把节点waitStatus改为0,并将节点放入AQS队列,如果可以唤醒节点对应的线程
// java.util.concurrent.locks.AbstractQueuedSynchronizer#transferForSignal
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
*/
// CAS将 CONDITION 改为 0
if (!node.compareAndSetWaitStatus(Node.CONDITION, 0))
// 说明此节点为 cancelled
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).
*/
// 拼接到队列上并尝试设置前驱节点的waitStatus来指示线程(可能)正在等待。如果取消或尝试设置waitStatus失败,请唤醒以重新同步(在这种情况下,waitStatus可能会暂时性且无害地错误)。
// 将node加入AQS队列,返回node的前驱节点
Node p = enq(node);
// 获取前驱节点的waitStatus
int ws = p.waitStatus;
if (ws > 0 || !p.compareAndSetWaitStatus(ws, Node.SIGNAL))
// 如果前驱节点为 CANCELLED 或者没有将前驱节点的状态修改为 SIGNAL,唤醒node线程
LockSupport.unpark(node.thread);
return true;
}