AQS(AbstractQueuedSynchronizer)コメント

AQSはじめに

AQSは抽象クラス、継承を使用する主な方法である、AQS自体は単に、取得及び同期コンポーネントのカスタム使用する同期状態を解除するためのメソッドを定義する任意の同期インターフェースを実装していない、AQS抽象クラスには、次のものが含ま方法1:AQSは、同期キューのみ共有モード(共有、複数のスレッドは、セマフォ/たCountDownLatchように、同時に実行されてもよい)は、2つのリソース共有:.排他的(排他的、唯一つのスレッドは、ReentrantLockののように、実行することができる)と共有定義時々排他モードでのみ同期キューが、条件が関与する場合、そこ条件キュー。公平かつ不公平な区別tryAcquire語クラス、tryAcquireShared

別のカスタム・シンクロナイザはまた、唯一の共有リソースへのアクセスを実現するための方法および状態の解除を実装する際にすることができます。さまざまな共有リソースでカスタムシンクロナイザを争うが、特定のスレッドには、そのようなチームの故障などのリソースへのキュー(アクセスを維持するために待機します/チームなどを覚ます)、AQSは最上階に良い達成しています。

 * <pre>
     *      +------+  prev +-----+       +-----+
     * head |      | <---- |     | <---- |     |  tail
     *      +------+       +-----+       +-----+
     * </pre>
复制代码

AQSの全体は、次のセクションに分かれています。

  • ノードnode、取得されたスレッドを格納するノードが存在する同期キュー、状態キューにおける前記値のノードとの間の主な違いwaitStatus
  • コホート全体の条件キューが排他モードにあったCondition.awaitXXノードが最後尾に追加された場合にのみ使用され、条件を使用しての前提は、すでにロックを取得し、
  • 同期キューは、排他、共有モード(主機能は、キューにある常にダミーノードであるノードCLHキューを格納するために使用する、後続のノードは、ロック状態がロックの解除時前者続きノード、先行ノードによって決定される取得しますウェイク以降のノード)でスリープします
  • ConditionObjectの、排他モードでは、メインスレッドがロックを解放する、条件キューを追加し、対応する操作信号を行ないます
  • ReentrantLockの次のような排他ロック(獲得、解放を)、取得
  • たとえばReentrantReadWriteLock、セマフォ、たCountDownLatchのための株式取得ロック(acquireShared、releaseShared)、

インナークラスノード

ノードノードは、ロック・スレッドのための代表的な内部状態キュー、同期キューに存在しているが、それは主にnextWaiter(マークが共有または排他)、waitStatusマークノードのステータス

 static final class Node {
        /** 标示节点是否是共享节点(这样的节点只存在于Sync Queue里面) */
        static final Node SHARED = new Node();
        
        /** 独占模式 */
        static final Node EXCLUSIVE = null;

        /** CANCELLED说明节点已经取消获取lock类(一般是由于interrupt或timeout导致的) 
        * 很多时候是在cancelAcquire里面进行设置这个标识
        */
        static final int CANCELLED =  1;
        
        /** SIGNAL标识当前节点的后继节点需要唤醒(PS: 这个通常是在 独占模式下使用, 在共享模式下有时用 PROPAGATE) */
        static final int SIGNAL    = -1;
        
        /** 当前节点在Condition Queue里面 */
        static final int CONDITION = -2;
        
        /**
         * 当前节点获取到 lock 或进行 release lock 时, 共享模式的最终状态是 PROPAGATE(PS:  *有可能共享模式的节点变成 PROPAGATE 之前就被其后继节点抢占 head 节点, 而从Sync *Queue中被踢出掉)
         
        /**
        *当前节点获取到 lock 或进行 release lock 时, 共享模式的最终状态是 PROPAGATE(PS: *有可能共享模式的节点变成 PROPAGATE 之前就被其后继节点抢占 head 节点, 而从Sync *Queue中被踢出掉)
        */
        static final int PROPAGATE = -3;

        /**
         * 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;
        }
    }
复制代码
* <h3>Usage Examples</h3>
 *
 * <p>Here is a non-reentrant mutual exclusion lock class that uses
 * the value zero to represent the unlocked state, and one to
 * represent the locked state. While a non-reentrant lock
 * does not strictly require recording of the current owner
 * thread, this class does so anyway to make usage easier to monitor.
 * It also supports conditions and exposes
 * one of the instrumentation methods:
 *
 *  <pre> {@code
 * class Mutex implements Lock, java.io.Serializable {
 *
 *   // Our internal helper class
 *   private static class Sync extends AbstractQueuedSynchronizer {
 *     // Reports whether in locked state
 *     protected boolean isHeldExclusively() {
 *       return getState() == 1;
 *     }
 *
 *     // Acquires the lock if state is zero
 *     public boolean tryAcquire(int acquires) {
 *       assert acquires == 1; // Otherwise unused
 *       if (compareAndSetState(0, 1)) {
 *         setExclusiveOwnerThread(Thread.currentThread());
 *         return true;
 *       }
 *       return false;
 *     }
 *
 *     // Releases the lock by setting state to zero
 *     protected boolean tryRelease(int releases) {
 *       assert releases == 1; // Otherwise unused
 *       if (getState() == 0) throw new IllegalMonitorStateException();
 *       setExclusiveOwnerThread(null);
 *       setState(0);
 *       return true;
 *     }
 *
 *     // Provides a Condition
 *     Condition newCondition() { return new ConditionObject(); }
 *
 *     // Deserializes properly
 *     private void readObject(ObjectInputStream s)
 *         throws IOException, ClassNotFoundException {
 *       s.defaultReadObject();
 *       setState(0); // reset to unlocked state
 *     }
 *   }
 *
 *   // The sync object does all the hard work. We just forward to it.
 *   private final Sync sync = new Sync();
 *
 *   public void lock()                { sync.acquire(1); }
 *   public boolean tryLock()          { return sync.tryAcquire(1); }
 *   public void unlock()              { sync.release(1); }
 *   public Condition newCondition()   { return sync.newCondition(); }
 *   public boolean isLocked()         { return sync.isHeldExclusively(); }
 *   public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
 *   public void lockInterruptibly() throws InterruptedException {
 *     sync.acquireInterruptibly(1);
 *   }
 *   public boolean tryLock(long timeout, TimeUnit unit)
 *       throws InterruptedException {
 *     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
 *   }
 * }}</pre>
 *
复制代码

おすすめ

転載: juejin.im/post/5d7203a7e51d4561ee1bdfe4