AQS源码

一、前沿

AQS 全称是 AbstractQueuedSynchronizer,即 抽象队列同步器,它底层采用了 CAS 技术保证了操作的原子性,同时利用 FIFO 队列实现线程间的锁竞争。作为基础的功能->同步抽象到了 AQS 中,这也是 JDK 并发包中 ReentrantLock、CountDownLatch、Semaphore、ReentrantReadWriteLock 等同步工具实现同步的底层实现机制,因此 AQS 作为同步基础抽象类非常重要,是 JDK 并发包的核心基础组件,下面学习一下它的源码

二、AQS 结构

AQS 的核心是通过 CAS 操作同步状态FIFO 同步队列实现线程间锁竞争,它主要实现了独占锁和共享锁的获取和释放,这些都是 AQS 对于同步操作实现的一些通用方法,为上层的同步工具屏蔽了大量的细节,大大降低了使用 ReentrantLock、CountDownLatch 这些工具的门槛,java.util.concurrent.locks.AbstractQueuedSynchronizer 结构如下:

几个重要字段和核心方法如下:

public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable {

     /**
     * Head of the wait queue, lazily initialized.  Except for
     * initialization, it is modified only via method setHead.  Note:
     * If head exists, its waitStatus is guaranteed not to be
     * CANCELLED.
     */
    // 队列头(当前执行的节点),延迟初始化,除了初始化只能通过 setHead 方法修改
    private transient volatile Node head;

    /**
     * Tail of the wait queue, lazily initialized.  Modified only via
     * method enq to add new wait node.
     */
    // 队列尾结点,延迟初始化,只能通过 enq 方法添加新节点
    private transient volatile Node tail;

    /**
     * The synchronization state.
     */
    // 同步状态
    private volatile int state;

    /**
     * Atomically sets synchronization state to the given updated
     * value if the current state value equals the expected value.
     * This operation has memory semantics of a {@code volatile} read
     * and write.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that the actual
     *         value was not equal to the expected value.
     */
    // 大名鼎鼎的 CAS 方法
    protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
}

head : 等待队列的头节点,表示当前正在执行的节点

tail: 等待队列的尾节点

state: 同步状态,其中 state > 0 为有锁状态,每次加锁就在原有 state 基础上加 1,即代表当前持有锁的线程加了 state 次锁,反之解锁时每次减 1,当 state = 0 为无锁状态

compareAndSetState: CAS 方法更改 state 同步状态,保证 state 的原子性操作

head 、tail 和 state 字段都使用了 volatile 修饰,保证了多线程间的可见性

head 节点表示当前持有锁的线程的节点,其余线程竞争锁失败后,会加入到队尾,tail 始终指向队列的最后一个节点

三、AQS 源码

说起 AQS 源码不得不说它的核心内部类 Node 节点,它是实现队列的核心部件,下面先看一下它的源码

3.1 Node 核心内部类

Node 总体结构图如下:

Node 代码注释中作者使用简洁图形描述了队列模型,如下图:

从上述图中可知 Node 是双向链表结构,字段说明如下:

SHARED : 共享锁节点

EXCLUSIVE : 独占锁节点

waitStatus : 节点状态,共有四个值,如下所示:

1)、CANCELLED(1):取消状态,如果当前线程的前置节点状态为 CANCELLED,则表示前置节点已经等待超时或者被中断了,此时需要将前置节点从队列中移除

2)、SIGNAL(-1):等待触发状态,如果当前线程的前置节点状态为 SIGNAL,则表示当前线程需要阻塞,因为此时前置节点将要获取到锁了

3)、CONDITION(-2):等待条件状态,表示当前节点在等待 condition,即在 condition 队列中

4)、PROPAGATE(-3):状态向后传播,仅在共享锁中使用,表示释放锁时需要被传播给后续节点

prev : 前置节点

next : 后置节点

thread : 当前线程对象

predecessor : 获取当前节点的前置节点

独占锁和共享锁源码类似,下面我们就以独占锁为例,来分析获取锁和释放锁的源码

独占锁:当一个线程获取到锁之后,则其他线程获取锁失败,然后其他线程进入到等待队列中等待获取锁

3.2  获取锁

获取锁的整个流程图如下:

获取锁的入口是 acquire 方法,源码如下:

    public final void acquire(int arg) {
        // 1、tryAcquire 方法需要自己实现逻辑,功能是获取锁
        // 2、addWaiter 方法将当前线程封装成Node节点,Node.EXCLUSIVE 表示独占锁
        // 3、acquireQueued 方法中试图再次获取锁,因为此时前置节点可能已经释放锁了
        if (!tryAcquire(arg) &&
                acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            // 4、获取锁失败,阻塞当前线程
            selfInterrupt();
    }

acquire 方法代码虽然很少,但是实现了以下一些重要的逻辑,如下:

1)、tryAcquire(arg) 方法尝试获取锁,这个方法需要实现类自己实现逻辑,如果获取锁成功,则直接返回,否则执行 2 步骤

2)、先调用 addWaiter(Node.EXCLUSIVE) 方法将当前线程封装成独占锁类型的 Node 节点并添加到队列尾部(作为尾结点),然后执行 acquireQueued 方法再次获取锁

3)、acquireQueued 获取锁的逻辑是判断当前节点的前置节点是否是头结点,如果是头结点的话则获取锁,获取锁成功之后将当前节点设置为头结点,并返回 false

4)、当前获取获取锁失败后,最终调用 selfInterrupt 方法阻塞自己

接着看  addWaiter(Node.EXCLUSIVE) 方法源码,如下:

    /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        // 构建 Node 节点
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            // 尾结点存在
            node.prev = pred;
            // 使用 CAS 操作将当前节点设置为尾结点,由于使用 CAS 操作则多线程情况下只会有一个线程执行成功,其余线程则会直接去调用 enq 方法添加节点
            if (compareAndSetTail(pred, node)) {
                // 设置成功后,旧尾结点的下一个节点指针指向当前节点
                pred.next = node;
                // 返回当前节点
                return node;
            }
        }
        // 尾结点不存在
        enq(node);
        return node;
    }

addWaiter 方法主要实现了以下逻辑:

1)、当前线程封装成独占锁类型 Node

2)、将当前节点添加到队列尾部,设置为尾结点

接着往下看添加节点 enq 方法,源码如下:

    /**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */
    private Node enq(final Node node) {
        // 自旋,保证当前节点添加到队尾并设置为尾结点
        for (;;) {
            Node t = tail;
            if (t == null) {
                // Must initialize
                // 尾结点不存在,即表示队列为空,此时初始化队列
                // 初始化队列,先创建一个新的Node,设置为头结点,设置成功之后,将尾结点也指向头结点
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                // 队列不为空,直接将当前节点添加到队尾并设置为尾结点
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    // 当前节点添加到队尾成功之后,结束自旋操作,返回旧尾结点
                    return t;
                }
            }
        }
    }

enq 方法主要实现了以下逻辑:

1)、for(;;) 自旋,说白了就是死循环,这是 AQS 中一个很重要的机制,确保当前节点添加到队尾

2)、如果队尾节点为空,则初始化队列,将头节点设置为空节点,头节点即表示当前正在运行的节点

3)、如果队尾节点非空,则采取 CAS 操作,将当前节点加入队尾,不成功则继续自旋,直到成功为止

到这里 addWaiter 方法的整个逻辑就分析完了,这里在总结一下:

1)、如果队尾不为空,则执行 CAS 操作将当前节点加入队尾,加入队尾失败的则继续调用 enq 方法入队

2)、如果队尾不为空或者加入队尾失败的节点调用 enq 方法入队

3)、enq 方法中使用了自旋策略保证当前节点加入队尾

4)、如果队尾节点为空,则初始化队列,将头节点设置为空节点,头节点即表示当前正在运行的节点

5)、如果队尾节点不为空,则采取 CAS 操作,将当前节点加入队尾,不成功则继续自旋,直到成功为止

队列的节点入队逻辑相当重要,这对理解线程获取锁和释放锁的过程至关重要,因此这里又总结了一遍

节点入队之后就是要获取锁操作了,下面接着 acquireQueued 方法源码分析,如下:

   /**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
    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 GC
                    failed = false;
                    return interrupted;
                }
                // 前置节点为非头节点或者再次获取锁失败后,执行线程挂起逻辑
                // shouldParkAfterFailedAcquire 方法实现了判断获取锁失败后是否需要挂起
                // parkAndCheckInterrupt 方法实现了线程挂起逻辑
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                    // 线程挂起成功,返回 true
                    interrupted = true;
            }
        } finally {
            // 线程被挂起了,取消其尝试获取锁
            if (failed)
                cancelAcquire(node);
        }
    }

acquireQueued 方法主要实现了以下逻辑:

1)、采用自旋策略,保证当前节点要么获取到了锁,要么获取锁失败后被挂起

2)、如果当前节点的前置节点是头节点,则再次尝试获取锁

3)、如果前置节点不是头节点或者获取锁失败,则执行线程挂起逻辑

注意: head 节点代表当前持有锁的线程,那么如果当前节点的 pred 节点是 head 节点,很可能此时 head 节点已经释放锁了,所以此时需要再次尝试获取锁

接着看 shouldParkAfterFailedAcquire 方法,即判断获取锁失败后的线程是否应该挂起,源码如下:

    /**
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev.
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        // 前置节点的等待状态
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            // 如果 pred 节点为 SIGNAL 状态,返回true,说明当前节点需要挂起,此时 pred 节点准备获取锁了
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            // 如果 pred 节点为 CANCELLED 状态,则表示 pred 节点需要从队列中移除
            do {
                // 删除所有状态为 CANCELLED 的节点,重新定位当前节点的前置节点
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            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.
             */
            // pred 节点是 PROPAGATE 或者 0,此时将 pred 节点状态统一设置为 SIGNAL,重新循环一次判断,即 acquireQueued 自旋方法
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

shouldParkAfterFailedAcquire 方法主要实现了以下逻辑:

1)、如果 pred 节点状态为 SIGNAL ,返回true,当前线程执行挂起逻辑

2)、如果 pred 节点状态为 CANCELLED ,则移除所有状态为 CANCELLED 的节点

3)、如果 pred 节点状态为 PROPAGATE 或者 0 ,则将pred 节点状态设置为 SIGNAL,则从 acquireQueued 的自旋方法重新执行一次判断

本过程总结如下:

根据 pred 节点状态来判断当前节点是否可以挂起,如果该方法返回 false,那么挂起条件还没准备好,就会重新进入 acquireQueued(final Node node, int arg) 的自旋体,重新进行判断。如果返回 true,那就说明当前线程可以进行挂起操作了,那么就会继续执行挂起

下面看 parkAndCheckInterrupt 方法,即实现了线程挂起逻辑,源码如下:
 

    /**
     * Convenience method to park and then check if interrupted
     *
     * @return {@code true} if interrupted
     */
    private final boolean parkAndCheckInterrupt() {
        // 调用 UNSAFE 的 park 方法阻塞线程
        LockSupport.park(this);
        return Thread.interrupted();
    }

至此获取锁的过程就讲完了,逻辑相对来说不是太很复杂,下面开始分析释放锁

3.3 释放锁

释放锁逻辑入口在 release 方法,源码如下:

    /**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if {@link #tryRelease} returns true.
     * This method can be used to implement method {@link Lock#unlock}.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryRelease} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from {@link #tryRelease}
     */
    public final boolean release(int arg) {
        // 释放锁,需要实现类自己实现逻辑
        if (tryRelease(arg)) {
            // 释放锁成功
            Node h = head;
            if (h != null && h.waitStatus != 0)
                // 如果头节点不为空 && 头节点状态 != 0,则调用 unparkSuccessor 方法唤醒后继节点
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

release 方法主要实现了以下逻辑:

1)、释放锁,这个需要实现类自己实现业务

2)、释放锁成功之后,如果头节点不为空 && 头节点状态 != 0,则调用 unparkSuccessor 方法唤醒后继节点

下面接着看 unparkSuccessor 方法,源码如下:

    /**
     * Wakes up node's successor, if one exists.
     *
     * @param node the node
     */
    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.
         */
        // head 节点等待状态
        int ws = node.waitStatus;
        if (ws < 0)
            // 如果 head 节点等待状态 小于 0 ,则将 head 节点重置为初始状态 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.
         */
        // head 节点的后继节点
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            // 后继节点为空 或者 后继节点等待状态为 CANCELLED
            s = null;
            // 从尾结点开始向前遍历
            for (Node t = tail; t != null && t != node; t = t.prev)
                // 直到找到离头节点最近的等待状态小于等于 0 的节点
                if (t.waitStatus <= 0)
                    // 找到的可以唤醒的节点赋值给 s
                    s = t;
        }
        if (s != null)
            // 后继节点不为空,则直接调用 UNSAFE 的 unpark 方法唤醒后继节点对应的线程
            LockSupport.unpark(s.thread);
    }


unparkSuccessor 方法主要实现了以下逻辑:

1)、如果头节点等待状态 小于 0 ,则将头节点重置为初始状态 0

2)、获取头节点的后继节点,如果后继节点不为空 && 后继节点等待状态 <= 0 ,则直接调用 UNSAFE 的 unpark 方法唤醒后继节点对应的线程

3)、如果后继节点为空 || 后继节点等待状态 > 0,则从尾结点开始向前遍历所有节点,找到离头节点最近的可以唤醒的节点(等待状态 <= 0), 然后执行步骤 2

释放锁过程总结如下:

主要是将头节点的后继节点唤醒,如果后继节点不符合唤醒条件,则从队尾一直往前找,直到找到符合条件的离头节点最近的节点为止

四、总结

本文主要讲述了 AQS 的内部结构和它的同步实现原理,并从源码的角度深度剖析了 AQS 独占锁模式下的获取锁与释放锁的逻辑,并且从源码中我们得出以下结论:
在独占锁模式下,用 state 值表示锁并且 0 表示无锁状态,从 0 到 1 表示从无锁到有锁,仅允许一个线程持有锁,其余的线程会被封装成一个 Node 节点放到队列中进行挂起,队列中的头节点表示当前正在执行的线程,当头节点释放后会唤醒后继节点,从而印证了 AQS 的队列是一个 FIFO 同步队列

参考:http://objcoding.com/2019/05/05/aqs-exclusive-lock/

猜你喜欢

转载自blog.csdn.net/ywlmsm1224811/article/details/103385151