简介
java.util.concurrent.locks.AbstractQueuedSynchronizer 简称aqs,是J.U.C包中最核心的一个类。也是J.U.C包中其他同步器的基类,J.U.C包在JSR-166中引入,作者是Doug Lea,是著名的并行计算专家。aqs的继承体系如下。
原理
从命名可以看出,他是抽象的基于队列的同步器。aqs维护着一个state属性,代表共享的资源,和一个first-in-first-out (FIFO)等待队列。基于此实现加锁、同步的基础框架。
state资源可以表示锁或同步的状态,如在ReentrantLock中加锁或者重入则state+=1,释放锁state-=1。当state>0时,其他线程会加入到FIFO队列等待释放锁。在Semaphore中则是获取资源state-=1,释放资源state+=1。state为0代表资源已消耗完,阻塞等待。state可以通过以下方法操作
- getState()
- setState()
- compareAndSetState()
FIFO等待队列,一个Node代表一个线程,有两种模式SHARED(共享)、EXCLUSIVE(独占)。head节点表示持有资源的线程,新加入的线程在尾部。公平模式下,只有节点的前一个节点是head才可以去竞争资源。如下图所示
aqs定义了一套基于队列基础同步流程,子类只要按需实现流程中的几个点就可自定义一个同步器。
* tryAcquire 尝试独占方式获取资源
* tryRelease 尝试独占方式释放资源
* tryAcquireShared 尝试共享方式获取资源
* tryReleaseShared 尝试共享方式释放资源
* isHeldExclusively 是否是独占者
如ReentrantLock中就通过tryAcquire 、tryRelease 、isHeldExclusively 实现了可重入独占锁。
源码分析
独占方式
独占方式获取资源的入口方法是 public final void acquire(int arg)
释放资源的方法入口是public final boolean release(int arg)
其中arg代表资源数量,我们先来看看acquireInterruptibly,主要流程如下图。
acquire与acquireInterruptibly的区别在于acquireInterruptibly在线程被中断时会抛出InterruptedException异常,而acquire会忽略中断状态,继续执行循环,跳到判断前一节点是否是头结点处
acquire源码分析:
public final void acquire(int arg) {
/**
* 1 tryAcquire尝试获取独占锁,成功则获取成功,方法完成,不成功则进入步骤2
* 2 addWaiter 创建一个独占模式node,添加到锁竞争线程队列并进入到步骤3
* 3 acquireQueued 竞争线程队列中节点尝试获取锁
*/
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
步骤一由子类实现 尝试获取资源
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
步骤二 获取锁失败,添加一个等待节点加入到等待队列
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
Node pred = tail;
//2.如果等待队列尾节点不为空,则将node加入到队列尾部
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//如果队列尾为空,则将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;
}
}
}
}
步骤三 加入到等待队列中节点尝试获取锁
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {//循环尝试,直至完成或失败
//1.获取当前节点的前一节点
final Node p = node.predecessor();
//2.如果前一节点是头节点,则尝试获取锁(公平锁的获取方式,只有队列的第二 个节点才会尝试获取锁)
if (p == head && tryAcquire(arg)) {
//获取锁则将当前节点设置为头结点
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//3. 获取锁失败后判断是否需要阻塞,如果是进入4
//4 阻塞当前线程,如果阻塞后被唤醒状态是已中断,设置为已中断
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//获取锁失败后判断是否需要阻塞
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;//获取前一节点
if (ws == Node.SIGNAL)//前一节点是Node.SIGNAL状态代表会唤醒下一节点,自己放心休眠
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {//前一节点是cancelled状态,将无效节点去掉
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {//将前一节点设置为Node.SIGNAL状态
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//休眠
return Thread.interrupted();//返回线程是否被中断
}
release源码分析:
release源码要简单很多,很容易理解
public final boolean release(int arg) {
if (tryRelease(arg)) {//尝试释放资源
Node h = head;
//如果头节点不为空,并且状态不为0,唤醒后续节点
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);//唤醒节点
}
共享方式
共享方式获取资源的入口方法是 public final void acquireShared(int arg)
释放资源的方法入口是public final boolean releaseShared(int arg)
其中arg代表资源数量,我们先来看看acquireShared,
acquireShared源码分析:
public final void acquireShared(int arg) {
//步骤一,尝试获取资源
if (tryAcquireShared(arg) < 0)
//步骤二 尝试获取共享锁失败,则进入doAcquireShared方法
doAcquireShared(arg);
}
步骤一 由子类实现
protected boolean tryReleaseShared(int arg) {
throw new UnsupportedOperationException();
}
步骤二
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;
}
}
//如果获取锁失败,前任节点状态为SIGNAL,则当前节点阻塞
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);//设置头节点
//此处传进的propagate必然大于0
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();//唤醒后续节点
}
}
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {//头节点是Node.SIGNAL状态
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);//唤醒后续节点
}
//设置自身为Node.PROPAGATE状态
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
releaseShared源码分析:
public final boolean releaseShared(int arg) {
//尝试释放资源
if (tryReleaseShared(arg)) {
//唤醒后续节点
doReleaseShared();
return true;
}
return false;
}
结束
源码分析到此就结束了,如果看不太懂,可以结合ReentrantLock、Semaphore等实际的同步器进行debug,查看state、队列、节点的状态,就会容易理解多了