一、简介
AQS全名AbstractQueuedSynchronizer,是构建锁和同步容器的框架。内部维护了两个队列,一个是等待队列(CHL),还有一个是条件队列(condition用的,调用await(),线程会进入条件队列,等待被唤醒,唤醒后以自旋方式获取资源或处理中断异常;调用signal(),线程会插入到等待队列,唤醒被阻塞的线程)。实现的主要逻辑依靠state锁状态和内部类Node:
state:锁资源状态,为0当前锁资源未被占用,>0被占用。
内部类Node:双向链表结构,内含变量、方法及含义如下(JDK1.8)
static final class Node {
/** 指示节点正在共享模式下等待的标记 */
static final Node SHARED = new Node();
/** 指示节点正在以独占模式等待的标记 */
static final Node EXCLUSIVE = null;
/** waitStatus值,指示线程已取消 等待GC回收 */
static final int CANCELLED = 1;
/** waitStatus值,指示Next节点线程需要唤醒 */
static final int SIGNAL = -1;
/** waitStatus值,因为等待某个条件而被阻塞 表示这个结点在条件队列中 ConditonObject中用到 */
static final int CONDITION = -2;
/**
* waitStatus值,使用在共享模式头结点有可能处于这种状态,表示锁的下一次获取可以无条件传播
*/
static final int PROPAGATE = -3;
/**
对于普通同步节点,该字段初始化为0,对于条件节点,该字段初始化为 CONDITION。使用CAS修改
*/
volatile int waitStatus;
/** 前节点 */
volatile Node prev;
/** 后节点 */
volatile Node next;
/** 节点内存储线程 */
volatile Thread thread;
/**等待条件的下一个节点,ConditonObject中用到 */
Node nextWaiter;
/**
* 如果节点在共享模式下等待,则返回true。
*/
final boolean isShared() {
return nextWaiter == SHARED;
}
/**
返回前节点 没有NPE
*/
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() {
}
Node(Thread thread, Node mode) { //初始化节点 用于addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { //初始化节点 用于Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
核心实现依赖CAS、volatile:
volatile修饰:静态内部类Node的waitStatus等待状态、prev前节点、next下节点、thread节点内线程、AbstractQueuedSynchronizer的成员变量head头结点、tail尾结点、state锁状态。
CAS使用:
1.compareAndSetState()更新锁资源状态。
2.compareAndSetHead()更新头结点。
3.compareAndSetTail()更新尾结点。
4.compareAndSetWaitStatus()更新等待状态。
5.compareAndSetNext()。更新下节点
二、ReentrantLock的获取锁
debugger模式阅读:
1.调用lock方法:
2.进入到ReentrantLock类,sync为继承AbstractQueuedSynchronizer类的静态内部类的对象:
3.进入sync.lock方法
final void lock() {
//首先更新锁状态,成功将锁的持有者更新为当前线程 否则进入acquire方法 参数为1
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
4…进入acquire方法
public final void acquire(int arg) {
//尝试获取锁失败 并且 将节点添加的同步队列中
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//Thread.currentThread().interrupt(); 标记线程中断
selfInterrupt();
}
5…进入tryAcquire方法
protected final boolean tryAcquire(int acquires) {
//调用nonfairTryAcquire方法 因为初始化ReentrantLock为 非公平锁
return nonfairTryAcquire(acquires);
}
6…进入nonfairTryAcquire方法
final boolean nonfairTryAcquire(int acquires) {
//当前线程
final Thread current = Thread.currentThread();
//获取锁状态
int c = getState();
//锁未被占用
if (c == 0) {
//更新锁状态 成功将锁的持有者更新为当前线程 返回true
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//锁被占用 判断占用锁资源线程是否为当前线程
else if (current == getExclusiveOwnerThread()) {
//是 重入次数加acquires 就入参1
int nextc = c + acquires;
//state 长度为2的32次方 <0 重入越界 抛出错误
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
//否则 更新state 为nextc
setState(nextc);
return true;
}
//锁被占用 并且不是当前线程占用 返回false
return false;
}
7…进入addWaiter方法,参数Node.EXCLUSIVE为排它锁
private Node addWaiter(Node mode) {
//构建当前线程的排他锁类型的Node节点
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);
return node;
}
8…进入enq方法,参数为当前节点
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;
}
}
}
}
9.进入acquireQueued方法,参数为当前节点 和 1
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);
//之前的节点 置空 方便GC回收
p.next = null;
//未失败
failed = false;
return interrupted;
}
//如果前节点不为头结点 则寻找一个合适位置 并将自己挂起 等待被唤醒
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
//如果失败
if (failed)
//取消正在获取的尝试
cancelAcquire(node);
}
}
10.shouldParkAfterFailedAcquire 寻找合适节点位置
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 {
//如果前节点状态不为已取消 设置为SIGNAL 等待被其唤醒
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
11.parkAndCheckInterrupt寻找合适节点位置后 挂起 更待唤醒
private final boolean parkAndCheckInterrupt() {
//阻塞该线程,至此该线程进入等待状态 等着unpark和interrupt叫醒他
LockSupport.park(this);
//叫醒之后返回该线程是否在中断状态, 并会清除中断记号。
return Thread.interrupted();
}
12.cancelAcquire 取消正在获取锁资源的尝试
private void cancelAcquire(Node node) {
// 如果当前节点为空 退出
if (node == null)
return;
//将节点内线程置空
node.thread = null;
// 循环向前找到一个不为取消状态的前节点
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
//前节点的下一节点
Node predNext = pred.next;
// 当前节点状态设置为无效
node.waitStatus = Node.CANCELLED;
// 如果当前节点为尾结点 将当前节点的前节点设置为 尾结点
if (node == tail && compareAndSetTail(node, pred)) {
//将前节点的下一节点置空
compareAndSetNext(pred, predNext, null);
} else {
// 如果前节点不为head 并且 (前节点的状态为SIGNAL 或者 前节点状态<0 不为SIGNAL 但是设置为SIGNAL 成功 )并且 前节点的线程 不为空
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)
//将当前节点的前节点 的 下一节点 设置为 当前节点的下一节点 (跳过 当前节点)
compareAndSetNext(pred, predNext, next);
} else {//节点不为末尾,status<=0的前节点是头节点 或status<=0的前节点线程为null 不唤醒后面节点可能就停止工作。如果你是尾节点,那无所谓,反正你后面也没线程需要unpark
//唤醒节点的下一有效节点
unparkSuccessor(node);
}
//当前节点只指向自己 可达性分析法 该对象是不可达 等待gc 回收
node.next = node;
}
13.unparkSuccessor 唤醒当前节点的下一有效节点
private void unparkSuccessor(Node node) {
//当前节点状态
int ws = node.waitStatus;
if (ws < 0)
//小于0 更新为0 不参与 整体获取锁的 状态判断
compareAndSetWaitStatus(node, ws, 0);
//当前节点 下一节点
Node s = node.next;
//如果 下一节点 为null 或者 状态为取消
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);
}
流程图:
总结:acquire()尝试获取资源,如果获取失败,将线程插入等待队列。插入后,并没有放弃获取资源,而是根据前置节点状态状态判断是否应该继续获取资源。如果前置节点是头结点,继续尝试获取资源;如果前置节点是SIGNAL状态,就中断当前线程,否则继续尝试获取资源。直到当前线程被阻塞或者获取到资源,结束。
三、ReentrantLock的释放锁
debugger模式阅读:
1.调用lock.unlock();
2.调用sync.release(1);
3.release方法 参数1
public final boolean release(int arg) {
//尝试释放锁资源1次
if (tryRelease(arg)) {
//头节点
Node h = head;
//头结点不为空 状态 不为0
if (h != null && h.waitStatus != 0)
//释放锁资源 唤醒下一有效节点 去 竞争锁
unparkSuccessor(h);
return true;
}
return false;
}
4.tryRelease方法 参数1
protected final boolean tryRelease(int releases) {
//状态值 减去 释放锁 数量
int c = getState() - releases;
//当前持有锁资源线程 不为 本线程 抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//状态为0
if (c == 0) {
free = true;
//更新只有锁资源线程为空
setExclusiveOwnerThread(null);
}
//更新状态值
setState(c);
return free;
}
5.unparkSuccessor方法 参数头结点 就是当前节点
private void unparkSuccessor(Node node) {
//当前节点状态
int ws = node.waitStatus;
if (ws < 0)
//小于0 更新为0 不参与 整体获取锁的 状态判断
compareAndSetWaitStatus(node, ws, 0);
//当前节点 下一节点
Node s = node.next;
//如果 下一节点 为null 或者 状态为取消
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);
}
流程图:
总结:释放资源,更新锁资源状态后,唤醒后继节点,判断后继节点为空且不是作废状态,则唤醒这个后继节点;否则从尾部往前面找距离自己最近的有效节点唤醒。