Java多线程系列(六)—AQS源码分析
AbstractQueuedSynchronizer同步器是基于LockSupport和CAS实现的同步器,是实现锁机制和其他同步类的基础;
个人主页:tuzhenyu’s page
原文地址:Java多线程系列(六)—AQS源码分析
1. AbstractQueuedSynchronizer内部数据结构
AQS同步器内部维护着两种链表结构,一种是Sync Queue同步队列用于存放被阻塞后的线程,另外一种是Condition Queue用于存放特定condition等待的线程;
(1)Sync Queue同步队列
同步队列用来存放锁竞争失败后进入阻塞状态的线程,是一个包含头尾指针的双向链表;同步队列是必须的,每个同步器都会维护一个同步队列;
同步队列的的子节点Node:每个线程被阻塞后都会被包装成一个Node,放入同步队列中
每个Node节点都保存着一个阻塞的线程,用thread保存;
每个Node节点都会有pre和next前后指针,指向前后节点;
每个Node节点都用state保存着当前节点的状态,包括等待状态,等待condition状态等;
每个Node节点保存者header和tail指针,分别执行链表的头部和尾部;
static final class Node {
static final Node SHARED = new Node();
static final Node EXCLUSIVE = null;
static final int CANCELLED = 1;
static final int SIGNAL = -1;
static final int CONDITION = -2;
static final int PROPAGATE = -3;
volatile int waitStatus;
volatile Node prev;
volatile Node next;
volatile Thread thread;
Node nextWaiter;
final boolean isShared() {
return nextWaiter == SHARED;
}
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() { // Used to establish initial head or SHARED marker
}
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;
}
}
private transient volatile Node head;
private transient volatile Node tail;
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) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
static final long spinForTimeoutThreshold = 1000L;
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
- 在添加新节点时会通过CAS将新节点添加到尾部,解决并发添加线程安全问题
(2)Condition Queue同步队列
Condition Queue用来存放执行condition等待的线程,每个同步器的Condition Queue数目不定;
Condition Queue是一条单向链表,同步器中每个Condition被包装成一个ConditionObject对象;单向链表中的节点都是阻塞线程包装成的Node节点;
Condition Queue的实体对象ConditionObject中定义了await、signal等函数,用来等待条件、释放条件。
public class ConditionObject implements Condition, java.io.Serializable {
private static final long serialVersionUID = 1173984872572414699L;
private transient Node firstWaiter;
private transient Node lastWaiter;
public ConditionObject() { }
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;
}
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
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);
}
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;
}
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;
}
}
2. AbstractQueuedSynchronizer核心函数
acquire()获取锁
- AbstractQueuedSynchronizer获取锁的入口,调用acquire(1)尝试在独占模式下获取对象状态(state),如果获取失败则阻塞加入同步队列;
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
调用tryAcquire()方法试图在独占模式下获取对象状态(state),即获取锁
如果获取失败则调用addWaiter()方法阻塞当前线程包装成Node放入同步队列中;
新建一个Node节点,节点对应的线程是“当前线程”
判断CLH队列是否为空,如果不为空则通过CAS操作compareAndSetTail()插入新节点并设置为尾节点;
如果CLH队列是否为空或者插入尾节点失败则调用enq()方法创建CLH队列并循环插入;
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
调用enq()循环CAS插入确保节点能成功插入
如果CLH队列为空,第一次循环创建一个空节点赋于head和tail指针
第二次循环将当当前线程包装的节点指向尾部节点;
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
调用acquireQueued()方法判断当前线程是否为可执行线程,如果当前线程获得了锁则将当前节点清空并赋为head指针,否则将当前线程节点进行阻塞休眠直到重新被唤醒;
判断当前线程节点是否为最靠前线程节点,如果是则尝试获取锁,如果不是则直接阻塞休眠,如果获取锁失败则当前线程节点阻塞休眠
获取锁成功后将当前节点清空(thread变为null),并将head指针指向该节点,原来的head节点指向null加快垃圾回收;
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
// interrupted表示在CLH队列的调度中,当前线程”在休眠时,有没有被中断过。
boolean interrupted = false;
for (;;) {
// 获取上一个节点。
// node是“当前线程”对应的节点,这里就意味着“获取前一个线程节点”。
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) { //如果队列中没有等待时间更长的线程,则再次尝试获取锁
setHead(node); //如果获取成功将节点清空并设为head空节点
p.next = null; // 将原来的head空节点指向null,help GC
failed = false;
return interrupted;
}
//如果当前线程节点不是最靠前的节点或者获取锁失败,则将线程进行休眠,直到下次报废唤醒
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
- 通过parkAndCheckInterrupt()方法阻塞线程并进行中断检查
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
release()释放锁
- AbstractQueuedSynchronizer释放锁的入口是调用release()方法,释放当前线程占有的锁,然后唤醒头结点后的线程节点
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
调用tryRelease()方法通过CAS操作释放锁(修改state状态)
调用unparkSuccessor()方法唤醒头结点(虚节点)后的线程;
private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
Node s = node.next;
if (s == null || s.waitStatus > 0) {
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);
}
condition.await()线程等待
- condition的使用
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
condition.await();
condition.singal();
await()方法线程阻塞进入等待状态:线程执行await()方法会从Runnable状态转变为Waiting状态
执行addConditionWaiter()方法创建新节点并添加到Condition队列尾部
执行fullRelease()方法释放锁
挂起线程,直到下次被唤醒
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);
}
- 执行addConditionWaiter()方法创建新节点,放入Condition队列的尾部;
private Node addConditionWaiter() {
Node t = lastWaiter;
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;
}
- 执行fullRelease()方法释放线程持有的锁(state)
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;
}
}
- release()方法调用tryRelease()方法和unparkSuccessor()方法修改state状态和唤醒头结点后的线程节点
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
- 通过isOnSyncQueue()方法判断节点是否在同步队列中,如果不在说明未被singal()方法唤醒则执行park()方法阻塞,如果被唤醒则会被移到同步队列中;
final boolean isOnSyncQueue(Node node) {
if (node.waitStatus == Node.CONDITION || node.prev == null)
return false;
if (node.next != null) // If has successor, it must be on queue
return true;
return findNodeFromTail(node);
}
- 被singal()方法唤醒后线程节点会被转移到同步队列中,调用acquireQueued方法自旋等待尝试再次获取锁
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
- 线程获取锁后会结束await()方法的执行,继续原来的方法执行;
condition.signal()/signalAll()线程唤醒
- 调用signal()方法唤醒condition队列中的线程,singal()方法之后唤醒condition队列最前面的一个线程节点;
public final void signal() {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
Node first = firstWaiter;
if (first != null)
doSignal(first);
}
- 调用doSingal()方法唤醒第一个非cannalled的线程,如果线程节点已经是cannalled则从FIFO队列中剔除;
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
- 调用transferForSignal()方法将Condition队列中第一个非cannalled的节点转移到同步队列中,通过enq()方法加入队列尾部;
final boolean transferForSignal(Node node) {
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
- 调用doSingalAll()方法唤醒所有非cannalled的线程加入到同步队列的尾部
private void doSignalAll(Node first) {
lastWaiter = firstWaiter = null;
do {
Node next = first.nextWaiter;
first.nextWaiter = null;
transferForSignal(first);
first = next;
} while (first != null);
}
总结
AQS底层维护者两种队列,一种是同步队列,一种是Condition队列;
AbstractQueuedSynchronizer同步器是锁机制和同步类的基础,AQS提供四种基本的函数:acquire(),release(),await(),signal()/signalAll();
acquire()用来尝试获取锁,如果获取失败则会线程阻塞并放入同步队列尾部;
release()方法用来释放锁并唤醒同步队列中头结点的下一个节点;
wait()方法是线程获取锁后执行,阻塞创建新节点放入condition尾部,释放锁唤醒同步队列中头结点的下一个节点;
signal()方法是唤醒conditon队列中的第一个节点,将该节点转移到同步队列尾部竞争锁;
signalAll()方法是唤醒condition中所有节点,从condition队列中转移到同步队列竞争锁;