一、AQS是什么?
AQS全称AbstractQueuedSynchronizer,抽象队列同步器,简称同步器。它是用来构建锁或者其他同步组件的基础框架。它内部有一个int表示同步状态,通过内置的双向队列获取线程的排队工作,并发包作者doug lea期望它能够成为实现大部分同步需求的基础。
1、volatile int state;0 表示无锁状态 大于0表示锁定状态
- int getState();获取当前同步状态
- void setState();设置当前同步状态。
- boolean compareAndSetState(int expect,int update);使用CAS设置当前状态。
2、同步器可以重写的方法:
- boolean tryAcquire(int arg);独占式获取锁,同步器的魔板方法acquire()方法会调用次方法,需要子类自己实现并返回true or false;
- boolean tryRelease(int arg);释放锁,同步鼓起的魔板方法relase(int arg)会调用此方法,子类只需要实现即可。
- int tryAcquireShared(int arg);共享式获取锁,大于0表示成功。acquireShared()会调用次方法;
- boolean tryReleaseShared(int arg);释放锁。同样模板方法relaseShared()方法会调用此方法。
- boolean isHeldExclusicely();当前线程,是否独占模式被占用;共享永远返回false。
3、同步器模板方法
其实AQS采用了模板方法模式。提供了一下模板方法供子类直接调用,子类不可修改这些方法:
- void acquire(int arg);独占式获取同步状态,如果获取成功,返回。否则将会进入同步队列等待,直到获取到锁。
- boolean release(int arg);释放锁,然后唤醒后面等待的结点。
- void acquireShared(int arg);
- boolean releaseShared(int arg);
- void acquireInterruptibly(int arg);可以响应中断。
在了解完AQS的作用和用法之后,我们来看看源码是怎么实现的。
二、AQS源码解析
CLH 同步队列是一个 FIFO 双向队列,AQS 依赖它来完成同步状态的管理:
- 当前线程如果获取同步状态失败时,AQS则会将当前线程已经等待状态等信息构造成一个节点(Node)并将其加入到CLH同步队列,同时会阻塞当前线程
- 当同步状态释放时,会把首节点唤醒(公平锁),使其再次尝试获取同步状态。
1.Node
Node是一个静态内部类,是队列的结点,也是等待队列的结点。
static final class Node {
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** 因为超时或者中断,节点会被设置为取消状态,被取消的节点时不会参与到竞争中的,他会一直保持取消状态不会转变为其他状态 */
static final int CANCELLED = 1;
/** 后继节点的线程处于等待状态,而当前节点的线程如果释放了同步状态或者被取消,将会通知后继节点,使后继节点的线程得以运行 */
static final int SIGNAL = -1;
/** 节点在等待队列中,节点线程等待在Condition上,当其他线程对Condition调用了signal()后,
该节点将会从等待队列中转移到同步队列中,加入到同步状态的获取中 */
static final int CONDITION = -2;
/**表示下一次共享式同步状态获取,将会无条件地传播下去*/
static final int PROPAGATE = -3;
//结点的同步状态
volatile int waitStatus;
volatile Node prev;
volatile Node next;
/**
* 当前结点的线程
*/
volatile Thread thread;
/**
* Link to next node waiting on condition, or the special
* value SHARED. Because condition queues are accessed only
* when holding in exclusive mode, we just need a simple
* linked queue to hold nodes while they are waiting on
* conditions. They are then transferred to the queue to
* re-acquire. And because conditions can only be exclusive,
* we save a field by using special value to indicate shared
* mode.
* 等待队列
*/
Node nextWaiter;
/**
* 等待队列,是否是共享
*/
final boolean isShared() {
return nextWaiter == SHARED;
}
/**前一结点,获取前一结点的状态,来判断当前结点是否需要park,还是自旋。如果大于0,即取消*/
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;
}
}
2.acquire方法解析
public final void acquire(int arg) {
//1.tryAcquire() 如果获取成功,那就直接执行。
//2.如果没有获取到锁,说明其他线程获取到了锁,这个时候就需要加入到等待队列中, addWaiter
//3.添加成功,然后再acquireQueued
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
private Node addWaiter(Node mode) {
//创建同步队列的结点
Node node = new Node(Thread.currentThread(), mode);
//快速尝试,如果尾结点不为空,说明队列不为空,直接尝试一次添加到队尾,使用CAS,否则的话调用enq 入队
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) {
//因为添加到队尾,存在竞争,这里循环CAS 直到成功
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
//队列为空的话,创建一个初始化结点作为header。 new Node()
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
//从队列中获取
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
//自旋过程中,是否interruptted
boolean interrupted = false;
//自旋 获取锁
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) { //如果上一个结点是头结点,且成功获取到锁
//把当前结点设置为头结点(头结点就是已经获取到锁的结点) 独占 没有竞争 不用CAS 释放锁也是一样的道理
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//如果不是头结点 或者 没有成功获取到锁 1.是否应该park线程? 2.如果是那么就park且检查interrupt 否则什么也不干,继续自旋
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//是否应该park线程
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
//如果前一个节点是signal状态的话,直接park当前结点
return true;
if (ws > 0) {
// 大于0 只有取消状态,那么就移除pred结点
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
//一定是0 或者 -3 那么把pred结点的状态设置为signal 然后返回false 下次再park
//下次再park 也是因为线程的状态切换比较耗时,如果再给他一次机会,如果能获取到,就可以避免状态的切换了。
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//如果当前结点被interrupt 调用一次
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
3.release方法
public final boolean release(int arg) {
//尝试释放,如果成功 正常情况下都会成功
if (tryRelease(arg)) {
Node h = head;
//头结点不为空 并且 头结点的状态不为0 那么说明后续有结点被park
if (h != null && h.waitStatus != 0)
//唤醒后面的结点
unparkSuccessor(h);
return true;
}
return false;
}
private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)//把当前结点的状态设置为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)
//唤醒线程,这里唤醒了,线程继续for(;;)尝试获取锁,如果这个时候又有新的线程来竞争,这个叫做非公平锁
//如果新线程获取到了锁,这个线程又会自旋一次,然后park。非公平锁可能或产生饥饿
//公平锁的实现,就是tryAcquire的时候,判断是否被锁定,或者队列是否>0 是的话 直接返回false
//公平锁性能要比非公平锁慢,应为可能会多一次线程的唤醒。
LockSupport.unpark(s.thread);
}
4.Condition详解
ConditionObject是AQS的内部类,实现了contiditon。可用于条件等待和唤醒。其中最主要的方法就是await()和signal()。
4.1 await()方法:
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//创建一个新的结点 添加到内部类里面的队列 单向队列
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
//才添加 肯定为false 就直接 park 当signal唤醒的时候,跳出循环
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);
}