AQS介绍
AQS(AbstractQueuedSynchronizer),是JDK并发包下的锁模板,包含共享模式和排他模式,是并发包下大部分的基础,如ReentrantLock、Semaphore和CountDownLatch等等。State属性和CLH队列是AQS的关键元素,子类通过State属性判断线程是否需要阻塞,CLH队列为线程阻塞队列,提供了线程阻塞和唤醒的实现。
AQS原理概述
AQS采用“模板方法”的设计模式,自身为抽象类,提供线程入队和出队的功能实现,子类只需要根据场景决定何时入队和出队即可(利用state属性)。因此,AQS的核心就是等待线程的入队和出队。
等待队列节点Node
waitStatus
- 0:初始化值;
- SIGNAL:当前节点的后续节点线程需要被唤醒;
- CONDITION:当前节点的线程正在等待某种条件;
- PROPAGATE:当前节点的后续节点的acquireShared方法需要被触发;
- CANCELLED:等待线程节点被取消;
AQS重要属性
/**
*等待队列尾节点
*/
private transient volatile Node head;
/**
* 等待队列尾节点
*/
private transient volatile Node tail;
/**
* 等待队列状态
*/
private volatile int state;
排它模式
只有一个线程持有锁,其它线程阻塞等待。Head节点表示对应的线程正在持有锁,其它Node节点表示其线程正阻塞等待,Head节点释放锁后只会唤醒后续的节点,如下图所示:
锁的获取acquire
大致过程:首先尝试获取排它锁,如果失败则创建排它节点,将当前线程阻塞加入等待队列。
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
新增节点
大致过程:首先尝试使用CAS操作插入队尾,如果失败则使用“自旋锁”(死循环)的方式入队。
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;
}
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;
}
}
}
}
获取锁
大致过程:如果锁获取成功,则将自身节点设为Head节点,然后返回;否则,利用LockSupport.park()将线程挂起,等待被唤醒。
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
锁的释放release
大致过程:将自身节点的waitStatus置为0,并唤醒后续节点的线程。
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
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 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);
}
共享模式
多个线程可以同时持有锁,某个Node节点被唤醒后,除了将自身节点设为Head节点外,还要唤醒后续的节点,如下图所示:
锁的获取acquireShared
大致过程:首先尝试获取共享锁,如果成功则将自身节点设为Head节点,并向后传播(继续唤醒其它线程);否则创建共享节点,将当前线程挂起,加入阻塞等待队列,等待被唤醒。
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
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);
}
}
向后传播setHeadAndPropagate
大致过程:调用方法releaseShared释放锁,并唤醒其它线程。
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
/*
* Try to signal next queued node if:
* Propagation was indicated by caller,
* or was recorded (as h.waitStatus either before
* or after setHead) by a previous operation
* (note: this uses sign-check of waitStatus because
* PROPAGATE status may transition to SIGNAL.)
* and
* The next node is waiting in shared mode,
* or we don't know, because it appears null
*
* The conservatism in both of these checks may cause
* unnecessary wake-ups, but only when there are multiple
* racing acquires/releases, so most need signals now or soon
* anyway.
*/
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();
}
}
锁的释放releaseShared
大致过程:唤醒后续节点的线程,并将自身节点的waitStatus设置为PROPAGATE。
private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
参考: