一 概述
AQS(AbstractQueuedSynchronizer) ,类如其名,抽象的队列同步器,定义了一套多线程访问共享资源的同步框架,许多类实现都依赖于它,如Semaphore,ReentrangLock底层都是使用了这个框架。使用AQS能够简单高效的构造出大量的同步器。AQS具备一下特性,阻塞等待队列,共享/独占,公平/非公平,可重入,允许中断。
1.1 设计思想
AQS维护了一个volatile int state表示共享变量,和一个FIFO线程等待队列(多线程争用资源被阻塞时会进入队列)。
/**
* The synchronization state.
*/
private volatile long state;
state 的访问一共有三种方式
- getState() //返回同步变量state的值
- setState() //获取同步变量state的值
- compareAndSetState() //cas方式改变state的值
AQS定义了两种资源共享方式:
- Exclusive(独占,同一时刻只有一个线程能够执行,如ReentrantLock)
- Share(共享,多个线程可同时执行,如Semaphore)。 其中线程阻塞维护了一个线程等待队列。
AQS定义了两种队列
- 同步等待队列
- 条件队列
其中同步队列是是Craig、Landin、Hagersten三人发明的一种基于双向链表数据结构的队列,是FIFO先入先出线程等待队列,Java中的CLH队列是原CLH队列的一个变种,线程由原自旋机制改为阻塞机制。
条件队列Condition是一个多线程间协调通信的工具类,使得某个,或者某些线程一起等待某个条(Condition),只有当该条件具备时 ,这些等待线程才会被唤醒,从而重新争夺锁。
不同的自定义同步器争用共享资源的方式也不同。自定义同步器在实现时只需要实现共享资源state的获取与释放就好,至于具体线程等待队列的维护(如获取资源失败/唤醒出队等),AQS在顶层已经实现好了。自定义同步器实现的主要实现下面方法
- tryAcquire(int) :独占方法。尝试获取资源,成功则返回true,失败则返回false.
- tryRelease(int):独占方法。产生释放资源,成功则返回true,失败就返回false.
- tryAcquireShared(int):共享方法。产生获取资源,负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
- tryAcquireShare(int):共享方式。尝试释放资源,如果释放后允许唤醒后续等待结点返回true,否则返回false。
- isHeldExclusively():该线程是否正在独占资源。只有用到condition才需要去实现它。
二 源码详解
2.1 主要属性介绍
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;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/
static final int PROPAGATE = -3;
//节点状态.可选值(0 , SIGNAl(-1), CANCELLED(1), CONDITION, PROPAGATE)
//waitStatus ==0 默认状态 waitStatus >0 取消状态
//waitStatus==-1 表示当前node如果是head节点的时候,释放锁之后,需要唤醒他的后继节点
volatile int waitStatus;
// 节点中用在阻塞队列中指向前继节点
volatile Node prev;
//next指向后继节点
volatile Node next;
/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
*/
//node 中线程
volatile Thread thread;
//条件队列中,指向后继节点
Node nextWaiter
}
//当前锁的持有者
private transient Thread exclusiveOwnerThread;
//头节点 (当有锁竞争的时候才会延迟初始化) 任何时刻 头节点对应的线程都是当前持锁线程
private transient volatile Node head;
// 阻塞队列的尾节点
private transient volatile Node tail;
/**
* The synchronization state.
*/
//表示资源
//在独占模式中:0 是未加锁状态 >0表示加锁状态
private volatile int state;
2.2 加锁方法,以公平锁 不可中断
//ReentrantLock.lock()
public void lock() {
sync.lock();
}
// 内部类 static final class FairSync extends Sync
//公平锁入口..
//不响应中断的加锁..响应中断的 方法为:lockinterrupted。。
final void lock() {
acquire(1);
}
//调用AQS acquire方法
public final void acquire(int arg) {
//条件 1:尝试获取锁 获取成功返回true 获取失败返回false
//条件2 : 当获取锁失败的时候 ,addWaiter将当前线程入队列,
acquireQueued挂起当前线程,以及被唤醒后相关的逻辑
acquireQueued返回true表示当前被挂起的线程被中断唤醒过..false表示没有被中断过
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//再次设置中断标记位,true
selfInterrupt();
}
- 公平锁获取资源流程图
protected final boolean tryAcquire(int acquires) {
//current 当前线程
final Thread current = Thread.currentThread();
// AQS state值
int c = getState();
// c==0 表示当前AQS处于无锁状态
if (c == 0) {
// 条件一:
//因为fairSync是公平锁,任何时候到需要检查以下 队列中是否在当前线程之前有等待者
方法返回true表示当前线程前面有等待者,当前线程需要入队等待
放回返回false表示当前线程前没有等待者,直接尝试获取锁就好
//条件二:compareAndSetState(0, acquires)
成功:说明当前线程抢占锁成功
失败:说明存在竞争。且当前线程竞争失败
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
/获取锁成功.设置当前线程为独占者线程
setExclusiveOwnerThread(current);
return true;
}
}
// 执行到这里 ,有几中情况?
// c!=0 大于0的情况,这种情况就需要检查一下,当前线程是不是独占锁线程,可以重入锁设计
//条件成立:说明当前线程就是独占锁线程...
else if (current == getExclusiveOwnerThread()) {
//锁重入的逻辑 这里没有并发
//nextc更新值
int nextc = c + acquires;
//越界判断,当重入的深度很深时,回导致nextc<0。
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
//更新state的值
setState(nextc);
return true;
}
//执行到这里?
// 1. CAS失败,c==0时,等待队列中有线程在等待或者cas修改state时,没有抢其他线程
// 2 c>0 且ownerThread != currentThread.
return false;
}
//判断阻塞队列中是否有线程在等待
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
// 条件一: h !=t 成立
不成立: h==t 也就是h==null的时候
h == t == head 第一个获取锁失败的线程,会为当前持有锁的线程 补充创建一个 head 节点。
//条件二:前置条件:条件一成立 ((s = h.next) == null || s.thread != Thread.currentThread())
//排除几种情况
//条件2.1:(s = h.next) == null
//极端情况:第一个获取锁失败的线程,会为 持锁线程 补充创建 head ,然后再自旋入队, 1. cas tail() 成功了,2. pred【head】.next = node;
//其实想表达的就是:已经有head.next节点了,其它线程再来这时 需要返回 true。
//条件2.2:前置条件,h.next 不是空。 s.thread != Thread.currentThread()
//条件成立:说明当前线程,就不是h.next节点对应的线程...返回true。
//条件不成立:说明当前线程,就是h.next节点对应的线程,需要返回false,回头线程会去竞争锁了。
(s=h.next)
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
- 线程入阻塞队列代码
private Node addWaiter() {
Node newNode = new Node(Thread.currentThread());
//如何入队呢?
//1.找到newNode的前置节点 pred
//2.更新newNode.prev = pred
//3.CAS 更新tail 为 newNode
//4.更新 pred.next = newNode
//快速入队
//前置条件:队列已经有等待者node了,当前node 不是第一个入队的node
Node pred = tail;
if(pred != null) {
newNode.prev = pred;
//条件成立:说明当前线程成功入队!
if(compareAndSetTail(pred, newNode)) {
pred.next = newNode;
return newNode;
}
}
//执行到这里的有几种情况?
//1.tail == null 队列是空队列
//2.cas 设置当前newNode 为 tail 时 失败了...被其它线程抢先一步了...
enq(newNode);
return newNode;
}
//自旋入队,只有成功后才返回,
1 tail ==null 队列是空队列
2 cas设置当前newNode为tail时失败了
private Node enq(final Node node) {
for (;;) {
//当前节点的前置节点
Node t = tail;
// 第一种情况,队列是空队列,初始化队列。
//当前持有锁的线程,没有设置过任何node,直接获取到锁了,给当前持有锁的线程设置一个node节点,用来唤醒后面阻塞的线程节点
if (t == null) { // Must initialize
//多线程的时候只有一个线程能初始化链表,然后自旋入队列
if (compareAndSetHead(new Node()))
tail = head;
//注意没有返回,还会继续自旋
} else {
//将当前节点的prev指向队列尾节点
node.prev = t;
//cas改变尾节点
if (compareAndSetTail(t, node)) {
//成功
返回当前节点
t.next = node;
return t;
}
}
}
}
- acquireQueued 挂起线程。以及线程唤醒后的逻辑
// 参数一:就是当前线程包装出来的node,且当前时刻,已成功入队
// 参数二:当前线程抢占到锁成功后,设置state值时会用到,
final boolean acquireQueued(final Node node, int arg) {
//true 表示当前下次你抢占锁成功,普通情况下[Lock]当前线程早晚会拿到锁
//false 表示失败,需要执行出队的逻辑
boolean failed = true;
try {
//当前线程是否被中断
boolean interrupted = false;
for (;;) {
//什么时候会执行到这里?
1 进入for循环时,线程尚为park时候会执行
2 线程park后。被唤醒后,也会执行这里
//获取当前节点的前置节点
final Node p = node.predecessor();
// 条件一 : 成立 p==head ,说明当前节点为head.next节点 可以竞争锁
//条件二: 成立 :说明head对应的线程,已经释放锁了, 当前线程获取到锁了
不成立:说明head对应的线程,还没释放锁呢, head.next仍然需要被park
if (p == head && tryAcquire(arg)) {
//设置自己为头节点
setHead(node);
//帮助老的head的节点出队
p.next = null; // help GC
//当前线程获取锁的过程中没有异常,
failed = false;
//返回当前线程的中断标记..
return interrupted;
}
//shouldParkAfterFailedAcquire 当前线程获取资源失败后,是否需要挂起呢
//返回值,true 当前线程需要挂起, false 不需要挂起
//parkAndCheckInterrupt() 这个方法什么作用? 挂起当前线程,并且唤醒之后 返回 当前线程的 中断标记
(1,正常唤醒,其他线程unpark 2 其他线程给当前线程一个中断信号)
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
//interrupted == true 表示当前node对应的线程是被 中断信号唤醒的...
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//设置头节点
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
//ws 前置节点的信号
//waitStatus:0 默认状态 new Node() ; -1 Signal状态,表示当前节点释放锁之后会唤醒它的第一个后继节点; >0 表示当前节点是CANCELED状态
int ws = pred.waitStatus;
//条件成立:当前前置节点是个可以唤醒当前节点的节点,所以返回true ==> parkAndCheckInterrupt() park当前线程了..
//第一次来当这个函数,ws不会是-1
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
//条件成立:>0 ,表示前置节点的状态是CANCELED状态,
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
//找前置 节点<=0的节点 当前head节点状态必定为sinal
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
// 隐含着一种操作,CANCELED状态的节点会被出队。
pred.next = node;
} else {
/*
* 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.
*/
//当前node前置节点的状态就是 0 的这一种情况。
//将当前线程node的前置node,状态强制设置为 SIGNAl,表示前置节点释放锁之后需要 喊醒我..
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//park当前线程 将当前线程 挂起,唤醒后返回当前线程 是否为 中断信号 唤醒。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
- 其中中断线程,也仅仅只是设置中断位
非中断 获取锁流程图
2.3 可中断锁
可响应中断锁当中断线程的时候会抛出中断异常,并取消线程参与竞争锁,不响应中断锁,不抛出异常,但是中断线程时候,会将线程重置线程中断标志位。
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public final void acquireInterruptibly(int arg)
throws InterruptedException {
//条件一: 如果线程被中断了,直接抛出异常
if (Thread.interrupted())
throw new InterruptedException();
//条件二,试图获取资源 和上面逻辑一样
if (!tryAcquire(arg))
doAcquireInterruptibly(arg);
}
//参数 arg获取锁成功,设置state使用
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
//添加线程到阻塞队列,和上面逻辑一样
final Node node = addWaiter(Node.EXCLUSIVE);
// true 出现了异常
//false 没有出现异常
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
//抛出异常
throw new InterruptedException();
}
} finally {
// 当代码抛出中断异常的时候,会执行cancelAcquire方法
if (failed)
cancelAcquire(node);
}
}
- 当线程被中断时候,取消指定node参与竞争
这个代码有点迷
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
//取消指定node参与竞争
if (node == null)
return;
//因为已经取消排队了..所以node内部关联的当前线程,置为Null就好了。。
node.thread = null;
// 获取当前 排队node的前驱
Node pred = node.prev;
//将node前面取消的线程状态出队列
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
//拿到前驱的后继节点。
//1.当前node
//2.可能也是 ws > 0 的节点。
Node predNext = pred.next;
//将当前node状态设置为 取消状态
node.waitStatus = Node.CANCELLED;
// 如果当前node 是尾节点,直接讲当前当前节点出队列即可
if (node == tail && compareAndSetTail(node, pred)) {
//可能是线程入阻塞队列了,所以存在竞争
compareAndSetNext(pred, predNext, null);
} else {
int ws;
//条件一 成立:说明node不是 head.next节点
//条件二三成立,说明前面的节点可以讲后置节点唤醒
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
//这里node没有真正的出队列,只有当node.next节点被唤醒后,调用 shouldParkAfterFailedAcquire 会让node.next 节点越过取消状态的节点完成真正出队。
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
//node是head.next节点
//唤醒node的后继节点 调用shouldParkAfterFailedAcquire将取消任务的节点出队列,
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
2.5 释放锁
public void unlock() {
sync.release(1);
}
//AQS#release方法
//ReentrantLock.unlock() -> sync.release()【AQS提供的release】
public final boolean release(int arg) {
//尝试释放锁,tryRelease 返回true 表示当前线程已经完全释放锁
//返回false,说明当前线程尚未完全释放锁..
if (tryRelease(arg)) {
//head什么情况下会被创建出来?
//当持锁线程未释放线程时,且持锁期间 有其它线程想要获取锁时,其它线程发现获取不了锁,而且队列是空队列,此时后续线程会为当前持锁中的
//线程 构建出来一个head节点,然后后续线程 会追加到 head 节点后面。
Node h = head;
//条件一 :成立,说明队列中的head节点已经初始化过了,ReentrantLock 在使用期间 发生过 多线程竞争了...
//条件二:条件成立,说明当前head后面一定插入过node节点。
**为什么这里要两个条件**
if (h != null && h.waitStatus != 0)
//唤醒后继节点中的线程
unparkSuccessor(h);
return true;
}
return false;
}
//Sync#tryRelease()
protected final boolean tryRelease(int releases) {
//减去释放的值..
int c = getState() - releases;
//条件成立:说明当前线程并未持锁..直接异常.,.
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
//当前线程持有锁.
//是否已经完全释放锁..默认false
boolean free = false;
//条件成立:说明当前线程已经达到完全释放锁的条件。 c == 0
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
//更新AQS.state值
setState(c);
return free;
}
//唤醒后继节点
private void unparkSuccessor(Node node) {
//获取当前节点的状态
int ws = node.waitStatus;
if (ws < 0) //-1 Signal 改成零的原因:因为当前节点已经完成喊后继节点的任务了..
compareAndSetWaitStatus(node, ws, 0);
//s是当前节点的第一后继节点
Node s = node.next;
//条件一: s什么时候为空,
1. 1.当前节点就是tail节点时 s == null。
2.当新节点入队未完成时(1.设置新节点的prev 指向pred 2.cas设置新节点为tail 3.(未完成)pred.next -> 新节点 )
//需要找到可以被唤醒的节点..
//条件二:s.waitStatus > 0 前提:s != null
//成立:说明 当前node节点的后继节点是 取消状态... 需要找一个合适的可以被唤醒的节点..
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;
//上面循环,会找到一个离当前node最近的一个可以被唤醒的node。 node 可能找不到 node 有可能是null、、
从后面向前寻找
}
if (s != null)
//如果找到合适的可以被唤醒的node,则唤醒.. 找不到 啥也不做。
//唤醒的线程,执行获取锁的逻辑,获取成功,设置头节点啥的,以及设置独占线程
LockSupport.unpark(s.thread);
}