【尚硅谷周阳--JUC并发编程】【第十三章--AbstractQueuedSynchronizer之AQS】
一、AQS入门级别理论知识
1、是什么?
- 字面意思:抽象的队列同步器
- 技术解释
-
是用来实现锁或者其他同步器组件的公共基础部分的抽象实现,是重量级基础框架及整个JUC体系的基石,主要用于解决锁分配给“谁”的问题
-
官网解释
-
整体就是一个抽象的FIFO队列来完成资源获取线程的排队工作,并通过一个int类变量表示持有锁的状态
-
2、AQS为什么是JUC内容中最重要的基石
2.1、和AQS有关的
- ReentrantLock
- CountDownLatch
- ReentrantReadWriteLock
- Semaphore
以上四个他们底层都是继承自AbstractQueuedSynchronizer
2.2、进一步理解锁和同步器的关系
- 锁,面向锁的使用者
定义了程序员和锁交互的使用层API,隐藏了实现细节,调用即可。 - 同步器,面向锁的实现者
Java并发大神DougLee,提出统一规范并简化了锁的实现,将其抽象出来屏蔽了同步状态管理、同步队列的管理和维护、阻塞线程排队和通知、唤醒机制等,是一切锁和同步组件实现的------公共基础部分。
3、能干嘛
- 加锁会导致阻塞
有阻塞就需要排队,实现排队必然需要队列 - 解释说明
- 源码查看
- 源码说明
AQS使用一个Volatile的int类型的成员变量来表示同步状态,通过内置的FIFO队列来完成资源获取的排队工作将每条要去抢占资源的线程封装成一个Node节点来实现锁的分配,通过CAS完成对State值的修改。
4、小总结
- AQS同步队列的基本结构
二、AQS源码分析前置知识储备
1、AQS内部体系架构
1.1、AQS自身
1.1.1、int类型变量state
- AQS的同步状态State成员变量
- 银行办理业务的受理窗口状态
- 零就是没人,自由状态可以办理
- 大于等于1,有人占用窗口,需要等待
1.1.2、AQS的CLH队列
- CLH队列(三个大牛的名字组成),为一个双向队列
- 类似于银行候客区的等待顾客
1.1.3、小总结
- 有阻塞就需要排队,实现排队必然需要队列
- state变量+CLH双端队列
1.2、内部类Node(Node类在AQS类内部)
1.2.1、Node的int变量
- Node的等待状态waitState成员变量
用于标注等候区其他顾客(其他线程)的等待状态,队列中每个排队的个体就是一个Node
1.2.2、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;
// 等待condition唤醒
static final int CONDITION = -2;
// 共享式同步状态获取将会无条件地传播下去
static final int PROPAGATE = -3;
// 初始为0,状态是上面的几种
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() { // 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;
}
}
- 属性说明
三、AQS源码深度讲解和分析
- Lock接口的实现类,基本都是通过【聚合】了一个【队列同步器】的子类完成线程访问控制的
1、ReentrantLock的原理
2、从lock方法看公平锁和非公平锁
3、以非公平锁ReentrantLock()为例
- 对比公平锁和非公平锁的tryAcquire()方法的实现代码,其实差别就在于非公平锁获取锁时比公平锁中少了一个判断!hasQueuedPredecessors()
- hasQueuedPredecessors()中判断了是否需要排队,导致公平锁和非公平锁差异如下
- 公平锁:公平锁讲究先来先到,线程在获取锁时,如果这个锁的等待队列已经有线程在等待,那么当前线程就会进入等待队列中;
- 非公平锁:不管是否有等待队列,如果可以获取锁,则立刻占有锁对象。也就是说队列的第一个排队线程苏醒后,不一定就是排头的这个线程获得锁,它还是需要参加竞争锁(存在线程竞争的情况下),后来的线程可能不讲武德插队夺锁了。
3.1、源码解读
3.1.1、acquire()源码和3大流程走向
/**
* Acquires in exclusive mode, ignoring interrupts. Implemented
* by invoking at least once {@link #tryAcquire},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquire} until success. This method can be used
* to implement method {@link Lock#lock}.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
3.1.2、程序案例
public class AQSDemo {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock();// 非公平锁
// A,B,C三个顾客,去银行办理业务,A先到,此时窗口空无一人,他优先获得办理窗口的机会,办理业务
// A耗时严重,估计长期占有窗口
new Thread(() -> {
reentrantLock.lock();
try {
System.out.println("------come in A");
// 暂停20分钟线程
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} finally {
reentrantLock.unlock();
}
}, "A").start();
// B是第二个顾客,B一看到受理窗口被A占用,只能去候客区等待,进入AQS队列,等待着A办理完成,尝试去抢占受理窗口
new Thread(() -> {
reentrantLock.lock();
try {
System.out.println("------come in B");
} finally {
reentrantLock.unlock();
}
}, "B").start();
// C是第三个顾客,C一看到受理窗口被A占用,只能去候客区等待,进入AQS队列,等待着A办理完成,尝试去抢占受理窗口,前面是B顾客,FIFO
new Thread(() -> {
reentrantLock.lock();
try {
System.out.println("------come in C");
} finally {
reentrantLock.unlock();
}
}, "C").start();
// 后续顾客DEFG......以此类推
new Thread(() -> {
reentrantLock.lock();
try {
System.out.println("------come in D");
} finally {
reentrantLock.unlock();
}
}, "D").start();
}
}
3.1.3、tryAcquire()模板设计模式
- 以非公平锁为例
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// 如果State=0,CAS尝试抢占锁
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
// 判断当前持有锁的是否是当前线程
else if (current == getExclusiveOwnerThread()) {
// 设置重入锁
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
3.1.4、addWaiter(Node.EXCLUSIVE)
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// 拿到当前尾节点
Node pred = tail;
// 如果尾节点为null,表示当前线程为第一个进入队列的线程
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) {
// 如果当前线程是第一次入队,那么循环至少需要走两次,第一次是创建虚节点,第二次才是当前线程入队
for (;;) {
// 尾节点
Node t = tail;
if (t == null) { // Must initialize
// 注意当前线程Node不会作为头结点,而是系统底层new了一个新Node设置为头结点。它是一个哨兵节点(虚节点),只作为占位使用,没有线程占用,waitState=0
if (compareAndSetHead(new Node()))
// 同时将其设置为尾节点
tail = head;
} else {
// 指定当前节点的前置节点
node.prev = t;
// 替换尾节点为当前节点
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
// 设置头结点
private final boolean compareAndSetHead(Node update) {
return unsafe.compareAndSwapObject(this, headOffset, null, update);
}
// 替换尾节点为当前节点
private final boolean compareAndSetTail(Node expect, Node update) {
return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
}
- 双向链表中,第一个节点为虚节点(也叫哨兵节点),其实并不存储任何信息,只是占位。真正的第一个有数据的节点,是从第二个节点开始的。
3.1.5、acquireQueued(addWaiter(Node.EXCLUSIVE), arg)
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
// 如果当前线程是第一次入队,那么循环至少需要走两次,第一次将虚节点的waitState置为-1,第二次返回true
for (;;) {
// 获得当前节点的前置节点
final Node p = node.predecessor();
// 判断前置节点是否虚拟节点并如果是则再次尝试抢夺资源
if (p == head && tryAcquire(arg)) {
// 将当前节点设置为虚拟头节点
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// 设置虚拟头节点
private void setHead(Node node) {
// 将当前节点设置为虚拟头节点
head = node;
// 虚拟头节点就是一个占位,没有线程绑定
node.thread = null;
// 将虚拟头节点前置节点置为空--方便前面的虚拟头节点GC
node.prev = null;
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
// 获得前置节点状态
int ws = pred.waitStatus;
// 如果是SIGNAL 状态,即等待被占用的资源释放,直接返回true
// 准备继续调用parkAndCheckInterrupt方法
if (ws == Node.SIGNAL)
return true;
// ws 大于0说明是CANCELLED状态
if (ws > 0) {
// 循环判断前置节点的前置节点是否也为CANCELLED状态,忽略该状态的节点,重新连接队列
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
// 将当前节点的前置节点设置为SIGNAL 状态 用于后续唤醒操作
// 程序第一次执行到这里返回false,还会进行外层第二次循环,最终在ws == Node.SIGNAL时返回
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
// 等待资源
private final boolean parkAndCheckInterrupt() {
// 挂起线程,程序不会继续向下执行
LockSupport.park(this);
// 根据park方法API描述,程序在下述三种情况会继续向下执行
// 1.被 unpark
// 2.被 中断(interrupt)
// 3.其他不合逻辑的返回才会继续向下执行
// 因上述三种情况程序执行至此,返回当前现成的中断状态,并清空中断状态
// 如果由于被中断,该方法返回true
return Thread.interrupted();
}
4、unlock
public void unlock() {
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
// 虚拟头节点
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
// 将所持有状态置为0
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
// 确认时当前线程,将锁持有者置为null,
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final void setExclusiveOwnerThread(Thread thread) {
// 将锁持有者置为null,
exclusiveOwnerThread = thread;
}
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)
// 将waitStatus设置为默认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);
}
5、cancelAcquire()队列取消流程
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
// 将当前节点Thread置为空
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
// 拿到前面节点中,最近的且不需要取消的流程的节点
// 处理连续几个节点都需要取消流程问题
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
// 修改尾节点
if (node == tail && compareAndSetTail(node, pred)) {
// 将前置节点的next置为null
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
// 设置新的前置节点的next
compareAndSetNext(pred, predNext, next);
} else {
unparkSuccessor(node);
}
node.next = node; // help GC
}
}