文章目录
AQS实现的三个功能
- 对同步状态的管理
- 对阻塞线程进行排队
- 等待通知等底层功能的实现
同步队列
AQS通过头尾指针管理同步队列的,获取锁失败的线程入队,释放锁对同步队列中的线程进行通知
当共享资源被某个线程占有,其他请求该资源的线程将会阻塞,从而进入同步队列。
Node={
static final Node shared = new Node(); //当前节点处于共享模式
static final Node exclusive = null; //当前节点处于独占模式
static final int canclled = 1; //当前节点从同步队列中取消
static final int signal = -1; //当前节点处于阻塞状态
static final int condition = -2; //当前节点进入等待队列中
static final int propagate = -3; //下一次共享同步状态 会无条件传播下去
volatile int waitStatus; //节点等待状态
volatile Node pre; //当前节点的前驱节点
volatile Node next; //当前节点的后继节点
volatile Thread thread; //同步队列的线程
volatile Node nextWaiter; // 等待队列的下一个节点
}
独占锁
独占锁的获取 acquire方法
调用lock方法获取独占锁,获取成功则线程执行,获取失败则当前线程入队。而lock方法实际会调用AQS的acquire方法
- 获取同步状态成功,则返回
- 获取同步状态失败,则先调用addWaiter方法再调用acquireQueued()方法 ——先将失败进程入队,然后再尝试获取独占锁
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
获取独占锁失败包装成Node插入同步队列
- 若当前同步队列尾节点为null,调用enq插入
- 若当前同步队列为节点不为null,采用尾插入(compareAndSetTail方法)
通常来说如果CAS操作失败会继续自旋(死循环)进行重试
private Node addWaiter(Node mode) {
// 1. 将当前线程封装成成Node类型
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
// 2. 当前尾节点是否为null?
Node pred = tail;
if (pred != null) {
// 2.2 将当前节点尾插入的方式插入同步队列中
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
// 2.1. 当前同步队列尾节点为null,说明当前线程是第一个加入同步队列进行等待的线程
enq(node);
return node;
}
- 若当前线程是第一个加入同步队列时,调用compareAndSetHead(new Node())构造头节点
- 自旋不断尝试CAS尾插入节点直到成功
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
//1. 构造头结点
if (compareAndSetHead(new Node()))
tail = head;
} else {
// 2. 尾插入,CAS操作失败自旋尝试 for(;;)
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
同步队列保证有机会获取到独占锁
- 如果前驱节点是头节点,并且成功获取到同步状态时,当前节点获取锁成功退出
- 获取锁失败的话,将节点状态设置为signal,然后调用LockSupport.park方法阻塞该线程
节点状态为siginal:标识当前线程处于阻塞状态
// 排队获取锁的过程
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) { //表示这是一个自旋的过程
// 1. 获得当前节点的先驱节点
final Node p = node.predecessor();
// 2. 当前节点能否获取独占式锁
// 2.1 如果当前节点的先驱节点是头结点并且成功获取同步状态,即可以获得独占式锁
if (p == head && tryAcquire(arg)) {
//队列头指针用指向当前节点
setHead(node);
//释放前驱节点
p.next = null; // help GC
failed = false;
return interrupted;
}
// 2.2 获取锁失败,线程进入等待状态等待获取独占式锁
if (shouldParkAfterFailedAcquire(p, node) && //使用CAS将节点状态由initial设置成signal
parkAndCheckInterrupt()) //阻塞该线程
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
独占锁的释放 release方法
若同步状态释放成功,再判断头节点是否不为空以及该节点状态值是否不为0,若成立执行unparkSuccessor方法
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
首先获取头节点的后继节点,调用lockSupport.unpark方法唤醒后继节点
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)
//后继节点不为null时唤醒该线程
LockSupport.unpark(s.thread);
}
独占锁的获取与释放总结
- 如果线程获取锁失败,线程被封装成Node进行入队操作,核心方法在于addWaiter()和enq(),enq()完成对同步队列头节点的初始化工作以及CAS队列操作失败的重试
- 队列中线程获取锁是一个自旋的过程,若当前节点的前驱节点是头节点而且成功获取同步状态时,将当前节点设置为头节点,否则调用LockSupport.park方法使当前线程阻塞
- 释放锁的时候,会通过LockSupport.unpark方法唤醒头节点的后继节点
总的来说:
在获取同步状态时,AQS维护一个同步队列,获取同步状态失败的线程会加入到队列并且进行自旋,也就是不断尝试获取锁;如果前驱节点是头节点并且成功获得了同步状态就会停止自旋,否则调用LockSupport.park方法使当前线程阻塞。
在释放同步状态时,会通过lockSupport.unpark方法唤醒头节点的后继节点
同步队列通过头指针与尾指针管理队列,头指针指向的节点是已经获取到同步状态的线程。
能响应中断以及超时等待
lock.lockInterruptibly方法,而该方法底层调用AQS的acquireInterrruptibly方法
lock.tryLock(timeout,TimeUnit),底层调用AQS的tryAcquireNanos方法
唯一不同:获取锁失败后,对超时时间,对中断的处理
共享锁
共享锁的获取 acquireShared方法
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0) //当返回值>=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);
}
}
自旋过程退出条件:前驱节点是头节点,并且成功获取到同步状态
共享锁的释放 releaseShared方法
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
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;
}
}
在共享锁释放过程中,对于能够支持多个线程同时访问的并发组件,必须保证多个线程安全释放同步状态。
这里采用CAS保证,当CAS操作失败,continue下一次循环重试