AQS源码解析

Posted aquariusm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AQS源码解析相关的知识,希望对你有一定的参考价值。

JAVA的众多锁的机制,包括Semaphore/ReentrantLock/ReentrantReadWriteLock等都是通过 AQS实现的,因为写了上述几个锁实现的源码分析,经常使用到AQS的原理和代码,因此这里做下AQS的源码分析。这样之后再翻看以AQS为基础的各种各样的锁实现就会好理解的多了。

我们结合着源码文件中的注释来看下。

源代码英文注释:

/**
 * Provides a framework for implementing blocking locks and related
 * synchronizers (semaphores, events, etc) that rely on
 * first-in-first-out (FIFO) wait queues.  This class is designed to
 * be a useful basis for most kinds of synchronizers that rely on a
 * single atomic {@code int} value to represent state. Subclasses
 * must define the protected methods that change this state, and which
 * define what that state means in terms of this object being acquired
 * or released.  Given these, the other methods in this class carry
 * out all queuing and blocking mechanics. Subclasses can maintain
 * other state fields, but only the atomically updated {@code int}
 * value manipulated using methods {@link #getState}, {@link
 * #setState} and {@link #compareAndSetState} is tracked with respect
 * to synchronization.
 */

提供一个依赖FIFO等待队列来实现阻塞锁和关联同步机制(信号量、事件等)的框架。该类被作为多数类型的同步机制的一个实用的基础,设计依赖一个atomic类型的int数据来代表一个状态。子类必须实现其protected类型的方法来改变这个状态,这个状态意味着对象被请求或者释放的一个说明。提供了这些,本类的其他方法都用来执行所有的队列和阻塞结构。子类可以维护其他的字段,但只有state状态的原子更新操作通过#getState, #setState, #compareAndSetState 被追踪来实现同步。

AQS的这段类文件中最开始的注释,解释了AQS类的意义和实现手段。

通过一个先进先出的队列和一个内存可见的int类型状态,来提供一个队列的阻塞结构,作为众多同步机制(Semaphore/ReentrantLock等)的基础算法结构。

源代码英文注释:

<p>This class supports either or both a default <em>exclusive</em>
 * mode and a <em>shared</em> mode. When acquired in exclusive mode,
 * attempted acquires by other threads cannot succeed. Shared mode
 * acquires by multiple threads may (but need not) succeed. This class
 * does not &quot;understand&quot; these differences except in the
 * mechanical sense that when a shared mode acquire succeeds, the next
 * waiting thread (if one exists) must also determine whether it can
 * acquire as well. Threads waiting in the different modes share the
 * same FIFO queue. Usually, implementation subclasses support only
 * one of these modes, but both can come into play for example in a
 * {@link ReadWriteLock}. Subclasses that support only exclusive or
 * only shared modes need not define the methods supporting the unused mode.

AQS类支持两种模式,独享模式和分享模式,默认是独享即排它模式。排它模式时,除了当前占用线程外,其他的线程的尝试请求将失败。共享模式下,多个线程的请求将会成功。这个类不能“理解”这种不同,除了这样一种机械的功能,那就是当一个共享模式的请求成功时,另一个等待线程(如果存在的话)必须决定它是否能够请求。不同类型的线程等待使用的是同样的FIFO队列。一般来说,子类只需要实现其中的一种模式,共享or排它。但也可以一起生效比如ReadWriteLock。只支持一种模式的子类不需要定义另一种不支持的模式的方法。

了解了基础的概括,我们来深入代码查看具体实现。

static final class Node {
        /** Marker to indicate a node is waiting in shared mode 标记用来标明一个分享模式的节点 */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode 标记用来标明一个排他模式的节点 */
        static final Node EXCLUSIVE = null;

        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1; // 表明线程被关闭的状态
        /** waitStatus value to indicate successor‘s thread needs unparking */
        static final int SIGNAL    = -1; // 表明线程等待被唤醒的状态
        /** waitStatus value to indicate thread is waiting on condition */
        static final int CONDITION = -2; // 表明线程再等待condition条件的状态
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3; // 表明下一个acquireShared会无条件的传递

        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn‘t need to
         * signal. So, most code doesn‘t need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;

        /**
         * Link to predecessor node that current node/thread relies on
         * for checking waitStatus. Assigned during enqueuing, and nulled
         * out (for sake of GC) only upon dequeuing.  Also, upon
         * cancellation of a predecessor, we short-circuit while
         * finding a non-cancelled one, which will always exist
         * because the head node is never cancelled: A node becomes
         * head only as a result of successful acquire. A
         * cancelled thread never succeeds in acquiring, and a thread only
         * cancels itself, not any other node.
         */
        volatile Node prev;

        /**
         * Link to the successor node that the current node/thread
         * unparks upon release. Assigned during enqueuing, adjusted
         * when bypassing cancelled predecessors, and nulled out (for
         * sake of GC) when dequeued.  The enq operation does not
         * assign next field of a predecessor until after attachment,
         * so seeing a null next field does not necessarily mean that
         * node is at end of queue. However, if a next field appears
         * to be null, we can scan prev‘s from the tail to
         * double-check.  The next field of cancelled nodes is set to
         * point to the node itself instead of null, to make life
         * easier for isOnSyncQueue.
         */
        volatile Node next;

        /**
         * The thread that enqueued this node.  Initialized on
         * construction and nulled out after use.
         */
        volatile Thread thread;

        /**
         * Link to next node waiting on condition, or the special
         * value SHARED.  Because condition queues are accessed only
         * when holding in exclusive mode, we just need a simple
         * linked queue to hold nodes while they are waiting on
         * conditions. They are then transferred to the queue to
         * re-acquire. And because conditions can only be exclusive,
         * we save a field by using special value to indicate shared
         * mode.
         */
        Node nextWaiter;

        /**
         * Returns true if node is waiting in shared mode.
         */
        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        /**
         * Returns previous node, or throws NullPointerException if null.
         * Use when predecessor cannot be null.  The null check could
         * be elided, but is present to help the VM.
         *
         * @return the predecessor of this node
         */
        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源码解析的主要内容,如果未能解决你的问题,请参考以下文章

源码解析之AQS源码解析

AQS源码解析

Java高并发学习——AQS及源码解析

提升--09---AQS源码解析

AQS源码解析-CLH

AQS源码解析-AtomicBoolean源码解析