1、AQS是什么
AQS同步器是Java并发编程的基础,从资源共享的角度分成独占和共享两种模式,像ReentrantLock、ThreadPoolExecutor、CountDownLatch等都是基于AQS来实现的,如图:
2、AQS同步队列的基本结构
AQS维护了一个头节点(head)和一个尾节点(tail)结构的双向链表,当一个线程获取锁失败时,会将该线程打包成一个Node节点,挂到同步队列尾节点
private transient volatile Node head;//同步队列头结点
private transient volatile Node tail;//同步队列尾结点
private volatile int state;//同步状态
2.1、同步队列内部结构
2.2、获取同步状态失败,将当前线程和节点模式打包成一个节点,放入同步队列尾部
2.3、前驱节点是头节点并且获取同步状态成功,设置当前节点为头节点,并将前驱节点指针清空,方便GC回收
2.1、Node节点类(双向链表挂在同步器中)
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() {
}
//当前线程和节点模式
Node(Thread thread, Node mode) {
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) {
this.waitStatus = waitStatus;
this.thread = thread;
}
}
2.2、state同步状态(AQS的重要成员变量)
//同步状态
private volatile int state;
//获取同步状态
protected final int getState() {
return state;
}
//设置同步状态
protected final void setState(int newState) {
state = newState;
}
//CAS设置同步状态
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
3、子类需重写的方法
AQS使用了模板方法设计模式,核心框架JDK已经写好,子类(自定义同步器)只需重写如下几个方法,即可实现不同的同步器:
//用于判断当前方法是否被线程独占,独占锁需重写
protected boolean isHeldExclusively() {
throw new UnsupportedOperationException();
}
//独占式获取锁
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
//独占式释放锁
protected boolean tryRelease(int arg) {
throw new UnsupportedOperationException();
}
//共享式获取锁
protected int tryAcquireShared(int arg) {
throw new UnsupportedOperationException();
}
//共享式释放锁
protected int tryReleaseShared(int arg) {
throw new UnsupportedOperationException();
}
4、独占模式分析
4.1、acquire独占锁获取(ReentrantLock的lock方法就是调用该方法)
1、tryAcquire(子类实现的方法,此时派上用场)
尝试获取同步状态,获取成功则直接使用
2、addWaiter
将当前线程打包成一个独占模式节点,放入同步队列的尾部
3、acquireQueued
进入等待状态,直到其他线程唤醒自己
//获取独占锁入口方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
//放入队列
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// 快速尝试将其放入尾部节点
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);//循环CAS方式将节点放入队列尾部
return node;
}
//入队
private Node enq(final Node node) {
for (; ; ) {//循环CAS添加尾部节点
Node t = tail;
if (t == null) { //队列为空,初始化一个空节点
if (compareAndSetHead(new Node()))//CAS防止产生多个队列
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {//CAS设置尾节点
t.next = node;
return t;
}
}
}
}
//阻塞等待
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; //便于GC回收以前的头节点
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&//设置前驱节点状态
parkAndCheckInterrupt())//阻塞线程
interrupted = true;//被中断一次就设置为true
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//设置前驱节点
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;//前驱节点的状态
if (ws == Node.SIGNAL)
return true;
if (ws > 0) {//目的是为了剔除取消的节点
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);//找到一个没有被取消的节点
pred.next = node;
} else {
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);//将前驱节点设置为SIGNAL
}
return false;
}
//阻塞线程
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//阻塞线程,直到被唤醒(发生中断或被其他线程调用unpark)
return Thread.interrupted();//线程是否中断
}
4.2、release独占锁释放(ReentrantLock的unlock方法就是调用该方法)
1、tryRelease(子类实现的方法,自定义释放的逻辑)
尝试获取同步状态,成功则继续
2、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;
}
//唤醒后继线程
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);
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);//唤醒后继线程
}
5、共享模式分析
5.1、acquireSharedInterruptibly共享锁获取(Semaphore的acquire方法就是调用该方法)
1、线程是否中断,是则抛出异常
2、tryAcquireShared(子类实现的方法)
尝试获取资源,成功直接返回,失败进入下面流程
3、doAcquireSharedInterruptibly(和独占锁类似)
将当前线程打包成共享节点,放入同步队列并阻塞,直到被唤醒并成功获取到资源才返回
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)//子类实现的方法,一般用来判断是否还有资源
doAcquireSharedInterruptibly(arg);//放入同步队列等待
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);//将当前线程打包成一个共享节点,放入同步队列尾部
boolean failed = true;
try {
for (;;) {//自旋
final Node p = node.predecessor();//获取前驱节点
if (p == head) {//前驱节点是头节点
int r = tryAcquireShared(arg);//尝试获取资源
if (r >= 0) {//大于0代表有资源可用
setHeadAndPropagate(node, r);//设置自己为head,还有剩余资源则唤醒后继线程
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&//设置前驱节点状态
parkAndCheckInterrupt())//阻塞线程,等待其他线程唤醒或线程被中断
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
5.2、releaseShared共享锁释放(Semaphore的release方法就是调用该方法)
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
private void doReleaseShared() {
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;
}
}
待续...