AbstractQueuedSynchronizer,缩写AQS,翻译过来为抽象队列同步器,日常开发当中,发现有很多常用的类都是基于AQS实现的,比如ReentrantLock、Semaphore、CountDownLatch
等等,本文来探究一下AQS是怎么处理锁与同步器的。
AQS的实现主要基于资源与同步队列,当请求的资源能够获取时,通过自旋+CAS的操作将资源占用值加一,当请求的资源不能够获取时,将新来的线程添加到等待队列当中,并设计了一套等待与唤醒的机制,AQS有共享模式与独占模式两种资源共享模式。
AQS拥有一个内部类Node.class,节点的主要结构如下,每个节点都拥有一个双向的指针,最后构造出来的等待队列也是一条双向链表。
waitStatus
:枚举,表示当前节点在队列中的状态
0 该Node 被初始化状态
CANCELLED为 1,该Node线程获取锁取消
CONDITION为-2,该Node在等待队列中,节点等待被唤醒
PROPAGATE为-3,当前线程处在SHARED 情况下
SIGNAL为-1,线程准备好,等待资源释放
thread
:执行线程的引用
prev
:前驱节点
next
:后继节点
static final class Node {static final Node SHARED = new Node();static final Node EXCLUSIVE = null;volatile int waitStatus; volatile Thread thread;volatile Node prev;volatile Node next;}
除了队列信息,还有当前资源的获取情况,以volatile修饰的一个state值
private transient volatile Node head;
private transient volatile Node tail;private volatile int state;
继续往下阅读会发现,很多方法都是空的,在调用的最底层很多方法都会抛出异常,AQS是基于模板方法模式的,大多数的方法还是需要业务去自定义实现,比如ReentrantLock、Semaphore、CountDownLatch对AQS的实现各不相同,这里主要看一下ReentrantLock对AQS的实现
ReentrantLock构造方法默认为非公平锁的实现方式:
public ReentrantLock() {sync = new NonfairSync();}/*** Creates an instance of {@code ReentrantLock} with the* given fairness policy.** @param fair {@code true} if this lock should use a fair ordering policy*/public ReentrantLock(boolean fair) {sync = fair ? new FairSync() : new NonfairSync();}
定义好锁的结构之后,便可以使用可重入锁了,先去看上锁的过程:
static final class NonfairSync extends Sync {private static final long serialVersionUID = 7316153563782823691L;/*** 首先使用cas操作将资源的状态由0设置为1,如果成功则表示上锁成功,并将当前线程设置为独占锁的拥有者*/final void lock() {if (compareAndSetState(0, 1))setExclusiveOwnerThread(Thread.currentThread());else// 如果直接设置失败,去获取锁acquire(1);}}
acquire方法内首先调用tryAcquire
去尝试获取锁,获取失败则调用addWaiter
将当前线程添加到等待队列当中去
public final void acquire(int arg) {if (!tryAcquire(arg) &&acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt();}
这里主要看一下非公平锁的获取方式,非公平锁在请求资源的时候首先会进行尝试抢占,抢占失败才会乖乖排队
final boolean nonfairTryAcquire(int acquires) {// 获取当前的执行线程final Thread current = Thread.currentThread();int c = getState();if (c == 0) {// 如果当前资源未被占用,再尝试加锁,加锁成功返回获取锁成功if (compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);return true;}}// 如果当前资源被占用,判断当前的线程是否为资源拥有者else if (current == getExclusiveOwnerThread()) {// 是资源拥有者的话再将资源值加上acquires值,实现线程可重入锁int nextc = c + acquires;if (nextc < 0) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc);return true;}// 默认获取锁失败return false;}
尝试获取锁失败之后会将这次的请求进行封装,加入到等待队列的末尾中去
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;}}// 使用自旋 + CAS操作不断重试插入到队列末尾enq(node);return node;}
最后不断的重试,将当前线程中断,进入等待就可以了,调用的方法是acquireQueued
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; // help GCfailed = false;return interrupted;}// 会判断当前的节点等待状态// 如果就绪则为true// 如果状态为取消,则将前驱节点设置为第一个就绪的节点// 其它状态时,通过CAS将等待状态设置为就绪if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())interrupted = true;}} finally {if (failed)cancelAcquire(node);}}
解锁最终会调用ReentrantLock内部实现的tryRelease方法
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;}
如果资源解除成功,并且无占用(state为0),则去从尾节点开始向前检查需要唤醒的节点
private void unparkSuccessor(Node node) {// node为当前队列的head节点int ws = node.waitStatus;if (ws < 0)compareAndSetWaitStatus(node, ws, 0);Node s = node.next;if (s == null || s.waitStatus > 0) {s = null;// 从尾节点开始向前检查waitStatus <=0的节点for (Node t = tail; t != null && t != node; t = t.prev)if (t.waitStatus <= 0)s = t;}// 如果不为空则需要进行唤醒,unpart调用的是UNSAFE类的唤醒方法,为native本地方法if (s != null)LockSupport.unpark(s.thread);}