回到顶部 暗色模式

AQS源码解读

        AQS提供了一个实现阻塞锁和相关的基于FIFO队列的同步器的框架。该类作为大部分依赖于一个状态字段的同步器的基础。子类必须定义 $protected$ 方法来改变状态,其他方法用于管理队列和实现阻塞机制。子类也可以包含其他状态字段,但必须通过原子性操作维护状态。

1. 成员变量

// 等待队列的头节点,懒加载,只能通过setHead方法修改
private transient volatile Node head;
// 等待队列的尾部,懒加载,只能通过enq方法添加新节点
private transient volatile Node tail;
// 同步状态
private volatile int state;
// 如果超时时间大于该值,中断,单位为纳秒
static final long spinForTimeoutThreshold = 1000L;

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;
    // 等待状态
    volatile int waitStatus;
    // 前驱节点
    volatile Node prev;
    // 后继节点
    volatile Node next;
    // 节点对应的线程
    volatile Thread thread;
    // 下一个在condition上等待的节点,或者表示共享模式
    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() {} // 用于创建头节点或者共享标记

    Node(Thread thread, Node mode) {
        this.nextWaiter = mode;
        this.thread = thread;
    }

    Node(Thread thread, int waitStatus) {
        this.waitStatus = waitStatus;
        this.thread = thread;
    }
}

3. 获取锁

3.1 独占模式

// 独占模式获取资源,忽略中断,未获取成功则阻塞
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

// 尝试以独占模式获取锁,需要在子类中重写
protected boolean tryAcquire(int arg) {
    throw new UnsupportedOperationException();
}

// 根据给定模式创建队列节点
private Node addWaiter(Node mode) {
    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;
}

// 节点入队
private Node enq(final Node node) {
    for(;;) {
        Node t = tail;
        if (t == null) {
            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 (;;) {
            final Node p = node.predecessor(); // 获取前驱节点
            if (p == head && tryAcquire(arg)) { // 如果没有前驱节点在等待,尝试获取锁
                setHead(node);
                p.next = null; // 帮助GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) && // 根据状态判断是否阻塞
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

// 检查和更新获取锁失败的节点状态,true表示需要阻塞
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
    int ws = pred.waitStatus; // 获取前驱节点状态
    if (ws == Node.SIGNAL) // 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;
}

// 挂起当前线程
private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
}

// 产生一个中断
static void selfInterrupt() {
    Thread.currentThread().interrupt();
}

        总结一下 $acquire$ 方法的执行步骤:

  1. 尝试以独占方式获取锁,成功则直接返回
  2. 尝试以自旋等待方式获取锁,将节点加入队列
  3. 在自旋的过程中通过 $shouldParkAfterFailedAcquire$ 方法判断是否需要挂起,如果之间发生了中断,设置中断标志位;
  4. 自旋获取锁成功,如果发生了中断,通过 $selfInterrupt$ 方法产生一个中断。

3.2 共享模式

// 共享模式获取锁,忽略中断
public final void acquireShared(int arg) {
    if (tryAcquireShared(arg) < 0)
        doAcquireShared(arg);
}

// 共享模式获取锁,失败时返回负数,0表示获取成功但没有剩余资源,正数表示获取节点成功并且还有剩余资源
protected int tryAcquireShared(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;
                    if (interrupted)
                        selfInterrupt();
                    failed = false;
                    return;
                }
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

// 设置队列头节点并传播
private void setHeadAndPropagate(Node node, int propagate) {
    Node h = head;
    setHead(node); // 设置头节点
    // 存在剩余资源、头节点为空、处于负状态
    if (propagate > 0 || h == null || h.waitStatus < 0 ||
        (h = head) == null || h.waitStatus < 0) {
        Node s = node.next; // 获取下一个节点
        if (s == null || s.isShared()) // 下一个节点为空或者处于共享模式
            doReleaseShared(); // 唤醒后继并确保传播
    }
}

3.3 其他

// 是否存在等待中的前驱
public final boolean hasQueuedPredecessors() {
    Node t = tail;
    Node h = head;
    Node s;
    return h != t && // 队列非空
        ((s = h.next) == null || s.thread != Thread.currentThread()); // 当前等待节点非当前线程所在节点
}

// 在规定时间内以独占模式获取锁
private boolean doAcquireNanos(int arg, long nanosTimeout)
        throws InterruptedException {
    if (nanosTimeout <= 0L)
        return false;
    final long deadLine = System.nanoTime() + nanosTimeout; // 到期时间
    final Node node = addWaiter(Node.EXCLUSIVE); // 创建节点并加入队列
    boolean failed = true;
    try {
        for (;;) {
            final Node p = node.predecessor(); // 获取前驱
            if (p == head && tryAcquire(arg)) { // 前驱为头节点,尝试获取锁
                setHead(node);
                p.next = null;
                failed = false;
                return true;
            }
            nanosTimeout = deadLine - System.nanoTime(); // 计算剩余时间
            if (nanosTimeout <= 0L)
                return false;
            if (shouldParkAfterFailedAcquire(p, node) && // 判断是否应该阻塞
                nanosTimeout > spinForTimeoutThreshold) // 超时时间大于阈值(1000),中断
                LockSupport.parkNanos(this, nanosTimeout);
            if (Thread.interrupted())
                throw new InterruptedException();
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

// 以独占模式获取锁,可以响应中断
private void doAcquireInterruptibly(int arg)
    throws InterruptedException {
    final Node node = addWaiter(Node.EXCLUSIVE); // 添加节点
    boolean failed = true;
    try {
        for (;;) {
            final Node p = node.predecessor(); // 获取前驱
            if (p == head && tryAcquire(arg)) { // 前驱为头节点,尝试获取锁
                setHead(node);
                p.next = null;
                failed = false;
                return;
            }
            if (shouldParkAfterFailedAcquire(p, node) && // 判断是否中断
                parkAndCheckInterrupt())
                throw new InterruptedException(); // 不再设置中断状态,而是直接抛出线程
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

4. 释放锁

4.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 boolean tryRelease(int arg) {
    throw new UnsupportedOperationException();
}

// 唤醒后继节点
private void unparkSuccessor(Node node) {
    int ws = node.waitStatus; // 获取当前节点状态
    if (ws < 0) // 负数则设置为正常状态
        compareAndSetWaitStatus(node, ws, 0);
    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); // 唤醒节点
}

4.2 共享模式

// 释放共享模式的锁
private void releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

protected boolean tryReleaseShared(int arg) {
    throw new UnsupportedOperationException();
}

// 释放共享模式的锁,唤醒后继并且设置为传播状态
private void doReleaseShared() {
    for (;;) {
        Node h = head;
        if (h != null && h != tail) {
            int ws = h.waitStatus;
            if (ws == Node.SIGNAL) {
                if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) // 设置正常状态
                    continue;
                unparkSuccessor(h); // 唤醒后继
            } else if (ws == 0 && // 已经是正常状态
                       !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) // 设置传播
                continue;
        }
        if (h == head) // 设置完成后如果发现头节点改变,重新设置
            break;
    }
}

5. 内部类ConditionObject

5.1 成员变量

// 队首节点
private transient Node firstWaiter;
// 队尾节点
private transient Node lastWaiter;
// 发生中断,设置该状态位,后续不抛出异常而是产生中断
private static final int REINTERRUPT = 1;
// 发生中断,设置该状态位,后续抛出异常
private static final int THROW_IE = -1;

5.2 阻塞

public final void await() throws InterruptedException {
    if (Thread.interrupted()) // 线程中断
        throw new InterruptedException();
    Node node = addConditionWaiter(); // 添加节点
    int savedState = fullyRelease(node); // 释放当前节点所有资源
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) { // 节点不在等待队列,则在condition的条件队列中
        LockSupport.park(this); // 阻塞节点
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) // 中断状态变化
            break;
    }
    // 唤醒后重新添加到等待队列中
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    // 删除非CONDITION节点
    if (node.nextWaiter != null)
        unlinkCancelledWaiters();
    // 如果发生中断,处理中断
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
}

// 向等待队列中添加节点
private Node addConditionWaiter() {
    Node t = lastWaiter;
    if (t != null && t.waitStatus != Node.CONDITION) {
        unlinkCancelledWaiters(); // 删除非CONDITION节点
        t = lastWaiter;
    }
    Node node = new Node(Thread.currentThread, Node.CONDITION);
    if (t == null)
        firstWaiter = node;
    else
        t.nextWaiter = node;
    lastWaiter = node;
    return node;
}

// 删除非CONDITION节点
private void unlinkCancelledWaiters() {
    Node t = firstWaiter;
    Node trail = null;
    while (t != null) {
        Node next = t.nextWaiter;
        if (t.waitStatus != Node.CONDITION) {
            t.nextWaiter = null;
            if (trail == null)
                firstWaiter = next;
            else
                trail.nextWaiter = next;
            if (next == null)
                lastWaiter = trail;
        } else trail = t;
        t = next;
    }
}

// 释放节点持有的资源
final int fullyRelease(Node node) {
    boolean failed = true;
    try {
        int savedState = getState(); // 获取当前状态
        if (release(savedState)) { // 完全释放锁
            failed = false;
            return savedState;
        } else {
            throw new IllegalMonitorStateException();
        }
    } finally {
        if (failed) // 释放失败,取消线程
            node.waitStatus = Node.CANCELLED;
    }
}

// 节点是否处于等待队列中
final boolean isOnSyncQueue(Node node) {
    if (node.waitStatus == Node.CONDITION || node.prev == null) // 如果为CONDITION节点或者首节点
        return false;
    if (node.next != null) // 如果存在后继,则位于等待队列中
        return true;
    return findNodeFromTail(node); // 从尾节点查找结点
}

// 检查阻塞过程中的中断情况
private int checkInterruptWhileWaiting(Node node) {
    return Thread.interrupted() ?
        (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
        0;
}

// 传输节点到等待队列
final boolean transferAfterCancelledWait(Node node) {
    if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) { // 取消CONDITION状态
        enq(node); // 加入等待队列
        return true;
    }
    while (!isOnSyncQueue(node)) // 不在等待队列,阻塞
        Thread.yield();
    return false;
}

// 处理中断
private void reportInterruptAfterWait(int interruptMode)
    throws InterruptedException {
    if (interruptMode = THROW_IE)
        throw new InterruptedException();
    else if (interruptMode == REINTERRUPT)
        selfInterrupt();
}

5.3 唤醒

// 唤醒最长等待的线程
public final void signal() {
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    Node first = firstWaiter;
    if (first != null)
        doSignal(first);
}

// 唤醒所有线程
private final void signalAll() {
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    Node first = firstWaiter;
    if (first != null)
        doSignalAll(first);
}

// 是否被独占
protected boolean isHeldExclusively() {
    throw new UnsupportedOperationException();
}

private void doSignal(Node first) {
    do {
        if ((firstWaiter = first.nextWaiter) == null)
            lastWaiter = null;
        first.nextWaiter = null;
    } while (!transferForSignal(first) &&
             (first = firstWaiter) != null);
}

private void doSignalAll(Node first) {
    lastWaiter = firstWaiter = null;
    // 唤醒并移除所有节点
    do {
        Node next = first.nextWaiter;
        first.nextWaiter = null;
        transferForSignal(first);
        first = next;
    } while (first != null);
}

// 传输节点到等待队列
final boolean transferForSignal(Node node) {
    if (!compareAndSetWaitStatus(node, Node.CONDITION, 0)) // 取消CONDITION状态
        return false;
    Node p = enq(node); // 加入队列
    int ws = p.waitStatus;
    if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL)) // 节点被取消或者更改状态失败
        LockSupport.unpark(node.thread); // 阻塞节点线程
    return true;
}

5.4 其他

public final long awaitNanos(long nanosTimeout)
    throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter(); // 添加节点
    int savedState = fullyRelease(node); // 释放节点
    final long deadline = System.nanoTime() + nanosTimeout; // 计算截止时间
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) { // 检查节点是否处于等待队列
        if (nanosTimeout <= 0L) { // 超时
            transferAfterCancelledWait(node); // 传输到等待队列
            break;
        }
        if (nanosTimeout >= spinForTimeoutThreshold) // 剩余时间大于阈值,阻塞
            LockSupport.parkNanos(this, nanosTimeout);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0) // 检查是否出现中断
            break;
        nanosTimeout = deadline - System.nanoTime();
    }
    if (acquireQueued(node, savedState)  && interruptMode != THROW_IE) // 插入等待队列
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null) // 移除非CONDITION节点
        unlinkCancelledWaiters();
    if (interruptMode != 0) // 处理中断
        reportInterruptAfterWait(interruptMode);
    return deadline - System.nanoTime();
}

AQS源码解读