前言
之前我已经分析了 AQS 的部分源码,那么在学习 Condition 原理之前,建议先去了解一下 AQS 的工作原理,可以参考:
JUC AQS源码分析(上) – AQS原理分析
JUC AQS源码分析(中) – ReentrantLock上锁源码解析
一、Condition 概括
Java并发编程实战(进阶篇)中分析 ArrayBlockingQueue 的阻塞入队和出队方法时使用到了 Condition 的await
(等待)和signal
(唤醒)方法来阻塞生产者或消费者线程,这也是 Condition 的简单使用。
Condition 究竟是如何将这些线程进行等待或者唤醒的呢?
同步队列和等待队列
我们在学习 AQS 时,会将 CAS 获取锁失败的线程加入到同步队列(CLH)当中;同样地,在 Condition 中,会将调用await
方法的线程加入到等待队列中。
那么同步队列和等待队列有什么异同?
- 异:同步队列的实现是采用双向链表,并且后一个结点的线程状态由前一个结点保存;等待队列的实现是采用单链表,结点保存各自的线程状态(waitStatus)
- 同:Condition 只是一个接口,主要实现类 ConditionObject 在 AQS 类中,所以同步队列和等待队列封装线程状态都是用Node结点
接下来主要从 Condition 最常用的两个方法await
和signal
来逐步分析源码。
二、ConditionObject#await()
调用Condition的await()方法会使当前线程进入等待状态,同时会加入到Condition等待队列同时释放锁。
public final void await() throws InterruptedException {
// 当前线程被中断直接抛出异常
if (Thread.interrupted())
throw new InterruptedException();
// 1.将当前线程加入到等待队列
Node node = addConditionWaiter();
// 2.释放当前线程持有的锁
int savedState = fullyRelease(node);
int interruptMode = 0;
// 3.直到当前线程在同步队列(被唤醒了),否则一直循环
// 在循环中也就是处于等待状态
while (!isOnSyncQueue(node)) {
// 4.将线程挂起
LockSupport.park(this);
// 等待状态响应中断,直接break
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
// 5.当前线程被唤醒之后,竞争同步状态
// acquireQueued在AQS源码中已经分析,这里就不在赘述
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
// 6.清除等待队列中不在等待状态的结点
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
// 7.中断状态不为0的情况,响应中断(要么抛出异常,要么自我中断)
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
1.addConditionWaiter
将线程添加到等待队列,并返回该线程结点。
/**
* Adds a new waiter to wait queue.
* @return its new wait node
*/
private Node addConditionWaiter() {
// 获取队尾结点
Node t = lastWaiter;
// If lastWaiter is cancelled, clean out.
// 队尾结点不为空 且 队尾结点线程状态不为等待状态
if (t != null && t.waitStatus != Node.CONDITION) {
// 清除不为等待状态的结点
unlinkCancelledWaiters();
// 获取新的队尾结点
t = lastWaiter;
}
// 将当前线程等待状态封装为Node结点
Node node = new Node(Thread.currentThread(), Node.CONDITION);
// 等待队列为空,node为队首结点
if (t == null)
firstWaiter = node;
else
t.nextWaiter = node;
lastWaiter = node;
return node;
}
2.unlinkCancelledWaiters
清除等待队列中不为等待状态(CONDITION)的结点。
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;
}
}
3.fullyRelease
释放结点持有的锁。
需要注意:这里结点持有的锁表示创建 Condition 的 lock 所持有的锁。
final int fullyRelease(Node node) {
boolean failed = true;
try {
// 获取AQS的状态变量state 0 表示未加锁 >=1 表示加锁
// state > 1表示锁重入的次数
int savedState = getState();
// 调用AQS解锁方法release,解锁成功返回state的值
if (release(savedState)) {
failed = false;
return savedState;
} else {
throw new IllegalMonitorStateException();
}
} finally {
// 解锁失败或出现异常,当前结点取消等待,会被从等待队列中清除
if (failed)
node.waitStatus = Node.CANCELLED;
}
}
4.isOnSyncQueue
判断当前结点线程是否在同步队列中,不在就会阻塞该线程。
final boolean isOnSyncQueue(Node node) {
// 处于等待状态 或 没有前置结点(如果在同步队列中肯定存在前置结点)
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
// 能够到达该判断说明
// node.waitStatus != Node.CONDITION && node.prev != null
// 如果node的后继存在结点,那他肯定在同步队列中
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.
*/
// 正如注释所说,在AQS添加该结点到同步队列中,可能设置了前置结点,
// 但将该结点CAS置为同步队列尾结点失败,所以需要从尾部遍历,确保
// 真的成功(具体添加结点到同步队列代码可以参考AQS addWaiter方法)
return findNodeFromTail(node);
}
三、ConditionObject#signal()
调用Condition的signal()方法,将会唤醒在等待队列中等待最长时间的节点(等待队列里的首节点),在唤醒节点前,会将节点移到CLH同步队列中。
public final void signal() {
// 当前线程是否独占
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
// 1.获取等待队列队头结点
Node first = firstWaiter;
// 2.如果队头结点不为空,就唤醒队头结点
if (first != null)
doSignal(first);
}
1.doSignal
唤醒首节点。
private void doSignal(Node first) {
do {
// 队头结点移除之后队列为空
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
// GC
first.nextWaiter = null;
// 循环直到队头结点移到同步队列 或 队列为空
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
2.transferForSignal
将结点转移到同步队列中。
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
* 如果无法CAS改变ws,说明该结点被取消等待
* 原因:该结点等待超时或被中断
*/
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;
// 如果p的状态为CANCELLED 或 修改状态失败,说明当前线程取消等待
// 不会去竞争,直接唤醒退出
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
最后提一句,在 Condition 源码分析中用到了很多 AQS 相关的原理知识,还是希望能去好好了解一下 AQS 的工作原理。