rt/emul/compact/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 11:01:40 +0100
changeset 1894 75ee4eca04e3
parent 1890 212417b74b72
permissions -rw-r--r--
Can compile java.util.concurrent.locks
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3  *
     4  * This code is free software; you can redistribute it and/or modify it
     5  * under the terms of the GNU General Public License version 2 only, as
     6  * published by the Free Software Foundation.  Oracle designates this
     7  * particular file as subject to the "Classpath" exception as provided
     8  * by Oracle in the LICENSE file that accompanied this code.
     9  *
    10  * This code is distributed in the hope that it will be useful, but WITHOUT
    11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    13  * version 2 for more details (a copy is included in the LICENSE file that
    14  * accompanied this code).
    15  *
    16  * You should have received a copy of the GNU General Public License version
    17  * 2 along with this work; if not, write to the Free Software Foundation,
    18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    19  *
    20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    21  * or visit www.oracle.com if you need additional information or have any
    22  * questions.
    23  */
    24 
    25 /*
    26  * This file is available under and governed by the GNU General Public
    27  * License version 2 only, as published by the Free Software Foundation.
    28  * However, the following notice accompanied the original version of this
    29  * file:
    30  *
    31  * Written by Doug Lea with assistance from members of JCP JSR-166
    32  * Expert Group and released to the public domain, as explained at
    33  * http://creativecommons.org/publicdomain/zero/1.0/
    34  */
    35 
    36 package java.util.concurrent.locks;
    37 import java.util.*;
    38 import java.util.concurrent.*;
    39 
    40 /**
    41  * Provides a framework for implementing blocking locks and related
    42  * synchronizers (semaphores, events, etc) that rely on
    43  * first-in-first-out (FIFO) wait queues.  This class is designed to
    44  * be a useful basis for most kinds of synchronizers that rely on a
    45  * single atomic <tt>int</tt> value to represent state. Subclasses
    46  * must define the protected methods that change this state, and which
    47  * define what that state means in terms of this object being acquired
    48  * or released.  Given these, the other methods in this class carry
    49  * out all queuing and blocking mechanics. Subclasses can maintain
    50  * other state fields, but only the atomically updated <tt>int</tt>
    51  * value manipulated using methods {@link #getState}, {@link
    52  * #setState} and {@link #compareAndSetState} is tracked with respect
    53  * to synchronization.
    54  *
    55  * <p>Subclasses should be defined as non-public internal helper
    56  * classes that are used to implement the synchronization properties
    57  * of their enclosing class.  Class
    58  * <tt>AbstractQueuedSynchronizer</tt> does not implement any
    59  * synchronization interface.  Instead it defines methods such as
    60  * {@link #acquireInterruptibly} that can be invoked as
    61  * appropriate by concrete locks and related synchronizers to
    62  * implement their public methods.
    63  *
    64  * <p>This class supports either or both a default <em>exclusive</em>
    65  * mode and a <em>shared</em> mode. When acquired in exclusive mode,
    66  * attempted acquires by other threads cannot succeed. Shared mode
    67  * acquires by multiple threads may (but need not) succeed. This class
    68  * does not &quot;understand&quot; these differences except in the
    69  * mechanical sense that when a shared mode acquire succeeds, the next
    70  * waiting thread (if one exists) must also determine whether it can
    71  * acquire as well. Threads waiting in the different modes share the
    72  * same FIFO queue. Usually, implementation subclasses support only
    73  * one of these modes, but both can come into play for example in a
    74  * {@link ReadWriteLock}. Subclasses that support only exclusive or
    75  * only shared modes need not define the methods supporting the unused mode.
    76  *
    77  * <p>This class defines a nested {@link ConditionObject} class that
    78  * can be used as a {@link Condition} implementation by subclasses
    79  * supporting exclusive mode for which method {@link
    80  * #isHeldExclusively} reports whether synchronization is exclusively
    81  * held with respect to the current thread, method {@link #release}
    82  * invoked with the current {@link #getState} value fully releases
    83  * this object, and {@link #acquire}, given this saved state value,
    84  * eventually restores this object to its previous acquired state.  No
    85  * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
    86  * condition, so if this constraint cannot be met, do not use it.  The
    87  * behavior of {@link ConditionObject} depends of course on the
    88  * semantics of its synchronizer implementation.
    89  *
    90  * <p>This class provides inspection, instrumentation, and monitoring
    91  * methods for the internal queue, as well as similar methods for
    92  * condition objects. These can be exported as desired into classes
    93  * using an <tt>AbstractQueuedSynchronizer</tt> for their
    94  * synchronization mechanics.
    95  *
    96  * <p>Serialization of this class stores only the underlying atomic
    97  * integer maintaining state, so deserialized objects have empty
    98  * thread queues. Typical subclasses requiring serializability will
    99  * define a <tt>readObject</tt> method that restores this to a known
   100  * initial state upon deserialization.
   101  *
   102  * <h3>Usage</h3>
   103  *
   104  * <p>To use this class as the basis of a synchronizer, redefine the
   105  * following methods, as applicable, by inspecting and/or modifying
   106  * the synchronization state using {@link #getState}, {@link
   107  * #setState} and/or {@link #compareAndSetState}:
   108  *
   109  * <ul>
   110  * <li> {@link #tryAcquire}
   111  * <li> {@link #tryRelease}
   112  * <li> {@link #tryAcquireShared}
   113  * <li> {@link #tryReleaseShared}
   114  * <li> {@link #isHeldExclusively}
   115  *</ul>
   116  *
   117  * Each of these methods by default throws {@link
   118  * UnsupportedOperationException}.  Implementations of these methods
   119  * must be internally thread-safe, and should in general be short and
   120  * not block. Defining these methods is the <em>only</em> supported
   121  * means of using this class. All other methods are declared
   122  * <tt>final</tt> because they cannot be independently varied.
   123  *
   124  * <p>You may also find the inherited methods from {@link
   125  * AbstractOwnableSynchronizer} useful to keep track of the thread
   126  * owning an exclusive synchronizer.  You are encouraged to use them
   127  * -- this enables monitoring and diagnostic tools to assist users in
   128  * determining which threads hold locks.
   129  *
   130  * <p>Even though this class is based on an internal FIFO queue, it
   131  * does not automatically enforce FIFO acquisition policies.  The core
   132  * of exclusive synchronization takes the form:
   133  *
   134  * <pre>
   135  * Acquire:
   136  *     while (!tryAcquire(arg)) {
   137  *        <em>enqueue thread if it is not already queued</em>;
   138  *        <em>possibly block current thread</em>;
   139  *     }
   140  *
   141  * Release:
   142  *     if (tryRelease(arg))
   143  *        <em>unblock the first queued thread</em>;
   144  * </pre>
   145  *
   146  * (Shared mode is similar but may involve cascading signals.)
   147  *
   148  * <p><a name="barging">Because checks in acquire are invoked before
   149  * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
   150  * others that are blocked and queued.  However, you can, if desired,
   151  * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to
   152  * disable barging by internally invoking one or more of the inspection
   153  * methods, thereby providing a <em>fair</em> FIFO acquisition order.
   154  * In particular, most fair synchronizers can define <tt>tryAcquire</tt>
   155  * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method
   156  * specifically designed to be used by fair synchronizers) returns
   157  * <tt>true</tt>.  Other variations are possible.
   158  *
   159  * <p>Throughput and scalability are generally highest for the
   160  * default barging (also known as <em>greedy</em>,
   161  * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
   162  * While this is not guaranteed to be fair or starvation-free, earlier
   163  * queued threads are allowed to recontend before later queued
   164  * threads, and each recontention has an unbiased chance to succeed
   165  * against incoming threads.  Also, while acquires do not
   166  * &quot;spin&quot; in the usual sense, they may perform multiple
   167  * invocations of <tt>tryAcquire</tt> interspersed with other
   168  * computations before blocking.  This gives most of the benefits of
   169  * spins when exclusive synchronization is only briefly held, without
   170  * most of the liabilities when it isn't. If so desired, you can
   171  * augment this by preceding calls to acquire methods with
   172  * "fast-path" checks, possibly prechecking {@link #hasContended}
   173  * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
   174  * is likely not to be contended.
   175  *
   176  * <p>This class provides an efficient and scalable basis for
   177  * synchronization in part by specializing its range of use to
   178  * synchronizers that can rely on <tt>int</tt> state, acquire, and
   179  * release parameters, and an internal FIFO wait queue. When this does
   180  * not suffice, you can build synchronizers from a lower level using
   181  * {@link java.util.concurrent.atomic atomic} classes, your own custom
   182  * {@link java.util.Queue} classes, and {@link LockSupport} blocking
   183  * support.
   184  *
   185  * <h3>Usage Examples</h3>
   186  *
   187  * <p>Here is a non-reentrant mutual exclusion lock class that uses
   188  * the value zero to represent the unlocked state, and one to
   189  * represent the locked state. While a non-reentrant lock
   190  * does not strictly require recording of the current owner
   191  * thread, this class does so anyway to make usage easier to monitor.
   192  * It also supports conditions and exposes
   193  * one of the instrumentation methods:
   194  *
   195  * <pre>
   196  * class Mutex implements Lock, java.io.Serializable {
   197  *
   198  *   // Our internal helper class
   199  *   private static class Sync extends AbstractQueuedSynchronizer {
   200  *     // Report whether in locked state
   201  *     protected boolean isHeldExclusively() {
   202  *       return getState() == 1;
   203  *     }
   204  *
   205  *     // Acquire the lock if state is zero
   206  *     public boolean tryAcquire(int acquires) {
   207  *       assert acquires == 1; // Otherwise unused
   208  *       if (compareAndSetState(0, 1)) {
   209  *         setExclusiveOwnerThread(Thread.currentThread());
   210  *         return true;
   211  *       }
   212  *       return false;
   213  *     }
   214  *
   215  *     // Release the lock by setting state to zero
   216  *     protected boolean tryRelease(int releases) {
   217  *       assert releases == 1; // Otherwise unused
   218  *       if (getState() == 0) throw new IllegalMonitorStateException();
   219  *       setExclusiveOwnerThread(null);
   220  *       setState(0);
   221  *       return true;
   222  *     }
   223  *
   224  *     // Provide a Condition
   225  *     Condition newCondition() { return new ConditionObject(); }
   226  *
   227  *     // Deserialize properly
   228  *     private void readObject(ObjectInputStream s)
   229  *         throws IOException, ClassNotFoundException {
   230  *       s.defaultReadObject();
   231  *       setState(0); // reset to unlocked state
   232  *     }
   233  *   }
   234  *
   235  *   // The sync object does all the hard work. We just forward to it.
   236  *   private final Sync sync = new Sync();
   237  *
   238  *   public void lock()                { sync.acquire(1); }
   239  *   public boolean tryLock()          { return sync.tryAcquire(1); }
   240  *   public void unlock()              { sync.release(1); }
   241  *   public Condition newCondition()   { return sync.newCondition(); }
   242  *   public boolean isLocked()         { return sync.isHeldExclusively(); }
   243  *   public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
   244  *   public void lockInterruptibly() throws InterruptedException {
   245  *     sync.acquireInterruptibly(1);
   246  *   }
   247  *   public boolean tryLock(long timeout, TimeUnit unit)
   248  *       throws InterruptedException {
   249  *     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
   250  *   }
   251  * }
   252  * </pre>
   253  *
   254  * <p>Here is a latch class that is like a {@link CountDownLatch}
   255  * except that it only requires a single <tt>signal</tt> to
   256  * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
   257  * acquire and release methods.
   258  *
   259  * <pre>
   260  * class BooleanLatch {
   261  *
   262  *   private static class Sync extends AbstractQueuedSynchronizer {
   263  *     boolean isSignalled() { return getState() != 0; }
   264  *
   265  *     protected int tryAcquireShared(int ignore) {
   266  *       return isSignalled() ? 1 : -1;
   267  *     }
   268  *
   269  *     protected boolean tryReleaseShared(int ignore) {
   270  *       setState(1);
   271  *       return true;
   272  *     }
   273  *   }
   274  *
   275  *   private final Sync sync = new Sync();
   276  *   public boolean isSignalled() { return sync.isSignalled(); }
   277  *   public void signal()         { sync.releaseShared(1); }
   278  *   public void await() throws InterruptedException {
   279  *     sync.acquireSharedInterruptibly(1);
   280  *   }
   281  * }
   282  * </pre>
   283  *
   284  * @since 1.5
   285  * @author Doug Lea
   286  */
   287 public abstract class AbstractQueuedSynchronizer
   288     extends AbstractOwnableSynchronizer
   289     implements java.io.Serializable {
   290 
   291     private static final long serialVersionUID = 7373984972572414691L;
   292 
   293     /**
   294      * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
   295      * with initial synchronization state of zero.
   296      */
   297     protected AbstractQueuedSynchronizer() { }
   298 
   299     /**
   300      * Wait queue node class.
   301      *
   302      * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
   303      * Hagersten) lock queue. CLH locks are normally used for
   304      * spinlocks.  We instead use them for blocking synchronizers, but
   305      * use the same basic tactic of holding some of the control
   306      * information about a thread in the predecessor of its node.  A
   307      * "status" field in each node keeps track of whether a thread
   308      * should block.  A node is signalled when its predecessor
   309      * releases.  Each node of the queue otherwise serves as a
   310      * specific-notification-style monitor holding a single waiting
   311      * thread. The status field does NOT control whether threads are
   312      * granted locks etc though.  A thread may try to acquire if it is
   313      * first in the queue. But being first does not guarantee success;
   314      * it only gives the right to contend.  So the currently released
   315      * contender thread may need to rewait.
   316      *
   317      * <p>To enqueue into a CLH lock, you atomically splice it in as new
   318      * tail. To dequeue, you just set the head field.
   319      * <pre>
   320      *      +------+  prev +-----+       +-----+
   321      * head |      | <---- |     | <---- |     |  tail
   322      *      +------+       +-----+       +-----+
   323      * </pre>
   324      *
   325      * <p>Insertion into a CLH queue requires only a single atomic
   326      * operation on "tail", so there is a simple atomic point of
   327      * demarcation from unqueued to queued. Similarly, dequeing
   328      * involves only updating the "head". However, it takes a bit
   329      * more work for nodes to determine who their successors are,
   330      * in part to deal with possible cancellation due to timeouts
   331      * and interrupts.
   332      *
   333      * <p>The "prev" links (not used in original CLH locks), are mainly
   334      * needed to handle cancellation. If a node is cancelled, its
   335      * successor is (normally) relinked to a non-cancelled
   336      * predecessor. For explanation of similar mechanics in the case
   337      * of spin locks, see the papers by Scott and Scherer at
   338      * http://www.cs.rochester.edu/u/scott/synchronization/
   339      *
   340      * <p>We also use "next" links to implement blocking mechanics.
   341      * The thread id for each node is kept in its own node, so a
   342      * predecessor signals the next node to wake up by traversing
   343      * next link to determine which thread it is.  Determination of
   344      * successor must avoid races with newly queued nodes to set
   345      * the "next" fields of their predecessors.  This is solved
   346      * when necessary by checking backwards from the atomically
   347      * updated "tail" when a node's successor appears to be null.
   348      * (Or, said differently, the next-links are an optimization
   349      * so that we don't usually need a backward scan.)
   350      *
   351      * <p>Cancellation introduces some conservatism to the basic
   352      * algorithms.  Since we must poll for cancellation of other
   353      * nodes, we can miss noticing whether a cancelled node is
   354      * ahead or behind us. This is dealt with by always unparking
   355      * successors upon cancellation, allowing them to stabilize on
   356      * a new predecessor, unless we can identify an uncancelled
   357      * predecessor who will carry this responsibility.
   358      *
   359      * <p>CLH queues need a dummy header node to get started. But
   360      * we don't create them on construction, because it would be wasted
   361      * effort if there is never contention. Instead, the node
   362      * is constructed and head and tail pointers are set upon first
   363      * contention.
   364      *
   365      * <p>Threads waiting on Conditions use the same nodes, but
   366      * use an additional link. Conditions only need to link nodes
   367      * in simple (non-concurrent) linked queues because they are
   368      * only accessed when exclusively held.  Upon await, a node is
   369      * inserted into a condition queue.  Upon signal, the node is
   370      * transferred to the main queue.  A special value of status
   371      * field is used to mark which queue a node is on.
   372      *
   373      * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
   374      * Scherer and Michael Scott, along with members of JSR-166
   375      * expert group, for helpful ideas, discussions, and critiques
   376      * on the design of this class.
   377      */
   378     static final class Node {
   379         /** Marker to indicate a node is waiting in shared mode */
   380         static final Node SHARED = new Node();
   381         /** Marker to indicate a node is waiting in exclusive mode */
   382         static final Node EXCLUSIVE = null;
   383 
   384         /** waitStatus value to indicate thread has cancelled */
   385         static final int CANCELLED =  1;
   386         /** waitStatus value to indicate successor's thread needs unparking */
   387         static final int SIGNAL    = -1;
   388         /** waitStatus value to indicate thread is waiting on condition */
   389         static final int CONDITION = -2;
   390         /**
   391          * waitStatus value to indicate the next acquireShared should
   392          * unconditionally propagate
   393          */
   394         static final int PROPAGATE = -3;
   395 
   396         /**
   397          * Status field, taking on only the values:
   398          *   SIGNAL:     The successor of this node is (or will soon be)
   399          *               blocked (via park), so the current node must
   400          *               unpark its successor when it releases or
   401          *               cancels. To avoid races, acquire methods must
   402          *               first indicate they need a signal,
   403          *               then retry the atomic acquire, and then,
   404          *               on failure, block.
   405          *   CANCELLED:  This node is cancelled due to timeout or interrupt.
   406          *               Nodes never leave this state. In particular,
   407          *               a thread with cancelled node never again blocks.
   408          *   CONDITION:  This node is currently on a condition queue.
   409          *               It will not be used as a sync queue node
   410          *               until transferred, at which time the status
   411          *               will be set to 0. (Use of this value here has
   412          *               nothing to do with the other uses of the
   413          *               field, but simplifies mechanics.)
   414          *   PROPAGATE:  A releaseShared should be propagated to other
   415          *               nodes. This is set (for head node only) in
   416          *               doReleaseShared to ensure propagation
   417          *               continues, even if other operations have
   418          *               since intervened.
   419          *   0:          None of the above
   420          *
   421          * The values are arranged numerically to simplify use.
   422          * Non-negative values mean that a node doesn't need to
   423          * signal. So, most code doesn't need to check for particular
   424          * values, just for sign.
   425          *
   426          * The field is initialized to 0 for normal sync nodes, and
   427          * CONDITION for condition nodes.  It is modified using CAS
   428          * (or when possible, unconditional volatile writes).
   429          */
   430         volatile int waitStatus;
   431 
   432         /**
   433          * Link to predecessor node that current node/thread relies on
   434          * for checking waitStatus. Assigned during enqueing, and nulled
   435          * out (for sake of GC) only upon dequeuing.  Also, upon
   436          * cancellation of a predecessor, we short-circuit while
   437          * finding a non-cancelled one, which will always exist
   438          * because the head node is never cancelled: A node becomes
   439          * head only as a result of successful acquire. A
   440          * cancelled thread never succeeds in acquiring, and a thread only
   441          * cancels itself, not any other node.
   442          */
   443         volatile Node prev;
   444 
   445         /**
   446          * Link to the successor node that the current node/thread
   447          * unparks upon release. Assigned during enqueuing, adjusted
   448          * when bypassing cancelled predecessors, and nulled out (for
   449          * sake of GC) when dequeued.  The enq operation does not
   450          * assign next field of a predecessor until after attachment,
   451          * so seeing a null next field does not necessarily mean that
   452          * node is at end of queue. However, if a next field appears
   453          * to be null, we can scan prev's from the tail to
   454          * double-check.  The next field of cancelled nodes is set to
   455          * point to the node itself instead of null, to make life
   456          * easier for isOnSyncQueue.
   457          */
   458         volatile Node next;
   459 
   460         /**
   461          * The thread that enqueued this node.  Initialized on
   462          * construction and nulled out after use.
   463          */
   464         volatile Thread thread;
   465 
   466         /**
   467          * Link to next node waiting on condition, or the special
   468          * value SHARED.  Because condition queues are accessed only
   469          * when holding in exclusive mode, we just need a simple
   470          * linked queue to hold nodes while they are waiting on
   471          * conditions. They are then transferred to the queue to
   472          * re-acquire. And because conditions can only be exclusive,
   473          * we save a field by using special value to indicate shared
   474          * mode.
   475          */
   476         Node nextWaiter;
   477 
   478         /**
   479          * Returns true if node is waiting in shared mode
   480          */
   481         final boolean isShared() {
   482             return nextWaiter == SHARED;
   483         }
   484 
   485         /**
   486          * Returns previous node, or throws NullPointerException if null.
   487          * Use when predecessor cannot be null.  The null check could
   488          * be elided, but is present to help the VM.
   489          *
   490          * @return the predecessor of this node
   491          */
   492         final Node predecessor() throws NullPointerException {
   493             Node p = prev;
   494             if (p == null)
   495                 throw new NullPointerException();
   496             else
   497                 return p;
   498         }
   499 
   500         Node() {    // Used to establish initial head or SHARED marker
   501         }
   502 
   503         Node(Thread thread, Node mode) {     // Used by addWaiter
   504             this.nextWaiter = mode;
   505             this.thread = thread;
   506         }
   507 
   508         Node(Thread thread, int waitStatus) { // Used by Condition
   509             this.waitStatus = waitStatus;
   510             this.thread = thread;
   511         }
   512     }
   513 
   514     /**
   515      * Head of the wait queue, lazily initialized.  Except for
   516      * initialization, it is modified only via method setHead.  Note:
   517      * If head exists, its waitStatus is guaranteed not to be
   518      * CANCELLED.
   519      */
   520     private transient volatile Node head;
   521 
   522     /**
   523      * Tail of the wait queue, lazily initialized.  Modified only via
   524      * method enq to add new wait node.
   525      */
   526     private transient volatile Node tail;
   527 
   528     /**
   529      * The synchronization state.
   530      */
   531     private volatile int state;
   532 
   533     /**
   534      * Returns the current value of synchronization state.
   535      * This operation has memory semantics of a <tt>volatile</tt> read.
   536      * @return current state value
   537      */
   538     protected final int getState() {
   539         return state;
   540     }
   541 
   542     /**
   543      * Sets the value of synchronization state.
   544      * This operation has memory semantics of a <tt>volatile</tt> write.
   545      * @param newState the new state value
   546      */
   547     protected final void setState(int newState) {
   548         state = newState;
   549     }
   550 
   551     /**
   552      * Atomically sets synchronization state to the given updated
   553      * value if the current state value equals the expected value.
   554      * This operation has memory semantics of a <tt>volatile</tt> read
   555      * and write.
   556      *
   557      * @param expect the expected value
   558      * @param update the new value
   559      * @return true if successful. False return indicates that the actual
   560      *         value was not equal to the expected value.
   561      */
   562     protected final boolean compareAndSetState(int expect, int update) {
   563         // See below for intrinsics setup to support this
   564         if (this.state == expect) {
   565             this.state = update;
   566             return true;
   567         }
   568         return false;
   569     }
   570 
   571     // Queuing utilities
   572 
   573     /**
   574      * The number of nanoseconds for which it is faster to spin
   575      * rather than to use timed park. A rough estimate suffices
   576      * to improve responsiveness with very short timeouts.
   577      */
   578     static final long spinForTimeoutThreshold = 1000L;
   579 
   580     /**
   581      * Inserts node into queue, initializing if necessary. See picture above.
   582      * @param node the node to insert
   583      * @return node's predecessor
   584      */
   585     private Node enq(final Node node) {
   586         for (;;) {
   587             Node t = tail;
   588             if (t == null) { // Must initialize
   589                 if (compareAndSetHead(new Node()))
   590                     tail = head;
   591             } else {
   592                 node.prev = t;
   593                 if (compareAndSetTail(t, node)) {
   594                     t.next = node;
   595                     return t;
   596                 }
   597             }
   598         }
   599     }
   600 
   601     /**
   602      * Creates and enqueues node for current thread and given mode.
   603      *
   604      * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
   605      * @return the new node
   606      */
   607     private Node addWaiter(Node mode) {
   608         Node node = new Node(Thread.currentThread(), mode);
   609         // Try the fast path of enq; backup to full enq on failure
   610         Node pred = tail;
   611         if (pred != null) {
   612             node.prev = pred;
   613             if (compareAndSetTail(pred, node)) {
   614                 pred.next = node;
   615                 return node;
   616             }
   617         }
   618         enq(node);
   619         return node;
   620     }
   621 
   622     /**
   623      * Sets head of queue to be node, thus dequeuing. Called only by
   624      * acquire methods.  Also nulls out unused fields for sake of GC
   625      * and to suppress unnecessary signals and traversals.
   626      *
   627      * @param node the node
   628      */
   629     private void setHead(Node node) {
   630         head = node;
   631         node.thread = null;
   632         node.prev = null;
   633     }
   634 
   635     /**
   636      * Wakes up node's successor, if one exists.
   637      *
   638      * @param node the node
   639      */
   640     private void unparkSuccessor(Node node) {
   641         /*
   642          * If status is negative (i.e., possibly needing signal) try
   643          * to clear in anticipation of signalling.  It is OK if this
   644          * fails or if status is changed by waiting thread.
   645          */
   646         int ws = node.waitStatus;
   647         if (ws < 0)
   648             compareAndSetWaitStatus(node, ws, 0);
   649 
   650         /*
   651          * Thread to unpark is held in successor, which is normally
   652          * just the next node.  But if cancelled or apparently null,
   653          * traverse backwards from tail to find the actual
   654          * non-cancelled successor.
   655          */
   656         Node s = node.next;
   657         if (s == null || s.waitStatus > 0) {
   658             s = null;
   659             for (Node t = tail; t != null && t != node; t = t.prev)
   660                 if (t.waitStatus <= 0)
   661                     s = t;
   662         }
   663         if (s != null)
   664             LockSupport.unpark(s.thread);
   665     }
   666 
   667     /**
   668      * Release action for shared mode -- signal successor and ensure
   669      * propagation. (Note: For exclusive mode, release just amounts
   670      * to calling unparkSuccessor of head if it needs signal.)
   671      */
   672     private void doReleaseShared() {
   673         /*
   674          * Ensure that a release propagates, even if there are other
   675          * in-progress acquires/releases.  This proceeds in the usual
   676          * way of trying to unparkSuccessor of head if it needs
   677          * signal. But if it does not, status is set to PROPAGATE to
   678          * ensure that upon release, propagation continues.
   679          * Additionally, we must loop in case a new node is added
   680          * while we are doing this. Also, unlike other uses of
   681          * unparkSuccessor, we need to know if CAS to reset status
   682          * fails, if so rechecking.
   683          */
   684         for (;;) {
   685             Node h = head;
   686             if (h != null && h != tail) {
   687                 int ws = h.waitStatus;
   688                 if (ws == Node.SIGNAL) {
   689                     if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
   690                         continue;            // loop to recheck cases
   691                     unparkSuccessor(h);
   692                 }
   693                 else if (ws == 0 &&
   694                          !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
   695                     continue;                // loop on failed CAS
   696             }
   697             if (h == head)                   // loop if head changed
   698                 break;
   699         }
   700     }
   701 
   702     /**
   703      * Sets head of queue, and checks if successor may be waiting
   704      * in shared mode, if so propagating if either propagate > 0 or
   705      * PROPAGATE status was set.
   706      *
   707      * @param node the node
   708      * @param propagate the return value from a tryAcquireShared
   709      */
   710     private void setHeadAndPropagate(Node node, int propagate) {
   711         Node h = head; // Record old head for check below
   712         setHead(node);
   713         /*
   714          * Try to signal next queued node if:
   715          *   Propagation was indicated by caller,
   716          *     or was recorded (as h.waitStatus) by a previous operation
   717          *     (note: this uses sign-check of waitStatus because
   718          *      PROPAGATE status may transition to SIGNAL.)
   719          * and
   720          *   The next node is waiting in shared mode,
   721          *     or we don't know, because it appears null
   722          *
   723          * The conservatism in both of these checks may cause
   724          * unnecessary wake-ups, but only when there are multiple
   725          * racing acquires/releases, so most need signals now or soon
   726          * anyway.
   727          */
   728         if (propagate > 0 || h == null || h.waitStatus < 0) {
   729             Node s = node.next;
   730             if (s == null || s.isShared())
   731                 doReleaseShared();
   732         }
   733     }
   734 
   735     // Utilities for various versions of acquire
   736 
   737     /**
   738      * Cancels an ongoing attempt to acquire.
   739      *
   740      * @param node the node
   741      */
   742     private void cancelAcquire(Node node) {
   743         // Ignore if node doesn't exist
   744         if (node == null)
   745             return;
   746 
   747         node.thread = null;
   748 
   749         // Skip cancelled predecessors
   750         Node pred = node.prev;
   751         while (pred.waitStatus > 0)
   752             node.prev = pred = pred.prev;
   753 
   754         // predNext is the apparent node to unsplice. CASes below will
   755         // fail if not, in which case, we lost race vs another cancel
   756         // or signal, so no further action is necessary.
   757         Node predNext = pred.next;
   758 
   759         // Can use unconditional write instead of CAS here.
   760         // After this atomic step, other Nodes can skip past us.
   761         // Before, we are free of interference from other threads.
   762         node.waitStatus = Node.CANCELLED;
   763 
   764         // If we are the tail, remove ourselves.
   765         if (node == tail && compareAndSetTail(node, pred)) {
   766             compareAndSetNext(pred, predNext, null);
   767         } else {
   768             // If successor needs signal, try to set pred's next-link
   769             // so it will get one. Otherwise wake it up to propagate.
   770             int ws;
   771             if (pred != head &&
   772                 ((ws = pred.waitStatus) == Node.SIGNAL ||
   773                  (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
   774                 pred.thread != null) {
   775                 Node next = node.next;
   776                 if (next != null && next.waitStatus <= 0)
   777                     compareAndSetNext(pred, predNext, next);
   778             } else {
   779                 unparkSuccessor(node);
   780             }
   781 
   782             node.next = node; // help GC
   783         }
   784     }
   785 
   786     /**
   787      * Checks and updates status for a node that failed to acquire.
   788      * Returns true if thread should block. This is the main signal
   789      * control in all acquire loops.  Requires that pred == node.prev
   790      *
   791      * @param pred node's predecessor holding status
   792      * @param node the node
   793      * @return {@code true} if thread should block
   794      */
   795     private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
   796         int ws = pred.waitStatus;
   797         if (ws == Node.SIGNAL)
   798             /*
   799              * This node has already set status asking a release
   800              * to signal it, so it can safely park.
   801              */
   802             return true;
   803         if (ws > 0) {
   804             /*
   805              * Predecessor was cancelled. Skip over predecessors and
   806              * indicate retry.
   807              */
   808             do {
   809                 node.prev = pred = pred.prev;
   810             } while (pred.waitStatus > 0);
   811             pred.next = node;
   812         } else {
   813             /*
   814              * waitStatus must be 0 or PROPAGATE.  Indicate that we
   815              * need a signal, but don't park yet.  Caller will need to
   816              * retry to make sure it cannot acquire before parking.
   817              */
   818             compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
   819         }
   820         return false;
   821     }
   822 
   823     /**
   824      * Convenience method to interrupt current thread.
   825      */
   826     private static void selfInterrupt() {
   827         Thread.currentThread().interrupt();
   828     }
   829 
   830     /**
   831      * Convenience method to park and then check if interrupted
   832      *
   833      * @return {@code true} if interrupted
   834      */
   835     private final boolean parkAndCheckInterrupt() {
   836         LockSupport.park(this);
   837         return Thread.interrupted();
   838     }
   839 
   840     /*
   841      * Various flavors of acquire, varying in exclusive/shared and
   842      * control modes.  Each is mostly the same, but annoyingly
   843      * different.  Only a little bit of factoring is possible due to
   844      * interactions of exception mechanics (including ensuring that we
   845      * cancel if tryAcquire throws exception) and other control, at
   846      * least not without hurting performance too much.
   847      */
   848 
   849     /**
   850      * Acquires in exclusive uninterruptible mode for thread already in
   851      * queue. Used by condition wait methods as well as acquire.
   852      *
   853      * @param node the node
   854      * @param arg the acquire argument
   855      * @return {@code true} if interrupted while waiting
   856      */
   857     final boolean acquireQueued(final Node node, int arg) {
   858         boolean failed = true;
   859         try {
   860             boolean interrupted = false;
   861             for (;;) {
   862                 final Node p = node.predecessor();
   863                 if (p == head && tryAcquire(arg)) {
   864                     setHead(node);
   865                     p.next = null; // help GC
   866                     failed = false;
   867                     return interrupted;
   868                 }
   869                 if (shouldParkAfterFailedAcquire(p, node) &&
   870                     parkAndCheckInterrupt())
   871                     interrupted = true;
   872             }
   873         } finally {
   874             if (failed)
   875                 cancelAcquire(node);
   876         }
   877     }
   878 
   879     /**
   880      * Acquires in exclusive interruptible mode.
   881      * @param arg the acquire argument
   882      */
   883     private void doAcquireInterruptibly(int arg)
   884         throws InterruptedException {
   885         final Node node = addWaiter(Node.EXCLUSIVE);
   886         boolean failed = true;
   887         try {
   888             for (;;) {
   889                 final Node p = node.predecessor();
   890                 if (p == head && tryAcquire(arg)) {
   891                     setHead(node);
   892                     p.next = null; // help GC
   893                     failed = false;
   894                     return;
   895                 }
   896                 if (shouldParkAfterFailedAcquire(p, node) &&
   897                     parkAndCheckInterrupt())
   898                     throw new InterruptedException();
   899             }
   900         } finally {
   901             if (failed)
   902                 cancelAcquire(node);
   903         }
   904     }
   905 
   906     /**
   907      * Acquires in exclusive timed mode.
   908      *
   909      * @param arg the acquire argument
   910      * @param nanosTimeout max wait time
   911      * @return {@code true} if acquired
   912      */
   913     private boolean doAcquireNanos(int arg, long nanosTimeout)
   914         throws InterruptedException {
   915         long lastTime = System.nanoTime();
   916         final Node node = addWaiter(Node.EXCLUSIVE);
   917         boolean failed = true;
   918         try {
   919             for (;;) {
   920                 final Node p = node.predecessor();
   921                 if (p == head && tryAcquire(arg)) {
   922                     setHead(node);
   923                     p.next = null; // help GC
   924                     failed = false;
   925                     return true;
   926                 }
   927                 if (nanosTimeout <= 0)
   928                     return false;
   929                 if (shouldParkAfterFailedAcquire(p, node) &&
   930                     nanosTimeout > spinForTimeoutThreshold)
   931                     LockSupport.parkNanos(this, nanosTimeout);
   932                 long now = System.nanoTime();
   933                 nanosTimeout -= now - lastTime;
   934                 lastTime = now;
   935                 if (Thread.interrupted())
   936                     throw new InterruptedException();
   937             }
   938         } finally {
   939             if (failed)
   940                 cancelAcquire(node);
   941         }
   942     }
   943 
   944     /**
   945      * Acquires in shared uninterruptible mode.
   946      * @param arg the acquire argument
   947      */
   948     private void doAcquireShared(int arg) {
   949         final Node node = addWaiter(Node.SHARED);
   950         boolean failed = true;
   951         try {
   952             boolean interrupted = false;
   953             for (;;) {
   954                 final Node p = node.predecessor();
   955                 if (p == head) {
   956                     int r = tryAcquireShared(arg);
   957                     if (r >= 0) {
   958                         setHeadAndPropagate(node, r);
   959                         p.next = null; // help GC
   960                         if (interrupted)
   961                             selfInterrupt();
   962                         failed = false;
   963                         return;
   964                     }
   965                 }
   966                 if (shouldParkAfterFailedAcquire(p, node) &&
   967                     parkAndCheckInterrupt())
   968                     interrupted = true;
   969             }
   970         } finally {
   971             if (failed)
   972                 cancelAcquire(node);
   973         }
   974     }
   975 
   976     /**
   977      * Acquires in shared interruptible mode.
   978      * @param arg the acquire argument
   979      */
   980     private void doAcquireSharedInterruptibly(int arg)
   981         throws InterruptedException {
   982         final Node node = addWaiter(Node.SHARED);
   983         boolean failed = true;
   984         try {
   985             for (;;) {
   986                 final Node p = node.predecessor();
   987                 if (p == head) {
   988                     int r = tryAcquireShared(arg);
   989                     if (r >= 0) {
   990                         setHeadAndPropagate(node, r);
   991                         p.next = null; // help GC
   992                         failed = false;
   993                         return;
   994                     }
   995                 }
   996                 if (shouldParkAfterFailedAcquire(p, node) &&
   997                     parkAndCheckInterrupt())
   998                     throw new InterruptedException();
   999             }
  1000         } finally {
  1001             if (failed)
  1002                 cancelAcquire(node);
  1003         }
  1004     }
  1005 
  1006     /**
  1007      * Acquires in shared timed mode.
  1008      *
  1009      * @param arg the acquire argument
  1010      * @param nanosTimeout max wait time
  1011      * @return {@code true} if acquired
  1012      */
  1013     private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
  1014         throws InterruptedException {
  1015 
  1016         long lastTime = System.nanoTime();
  1017         final Node node = addWaiter(Node.SHARED);
  1018         boolean failed = true;
  1019         try {
  1020             for (;;) {
  1021                 final Node p = node.predecessor();
  1022                 if (p == head) {
  1023                     int r = tryAcquireShared(arg);
  1024                     if (r >= 0) {
  1025                         setHeadAndPropagate(node, r);
  1026                         p.next = null; // help GC
  1027                         failed = false;
  1028                         return true;
  1029                     }
  1030                 }
  1031                 if (nanosTimeout <= 0)
  1032                     return false;
  1033                 if (shouldParkAfterFailedAcquire(p, node) &&
  1034                     nanosTimeout > spinForTimeoutThreshold)
  1035                     LockSupport.parkNanos(this, nanosTimeout);
  1036                 long now = System.nanoTime();
  1037                 nanosTimeout -= now - lastTime;
  1038                 lastTime = now;
  1039                 if (Thread.interrupted())
  1040                     throw new InterruptedException();
  1041             }
  1042         } finally {
  1043             if (failed)
  1044                 cancelAcquire(node);
  1045         }
  1046     }
  1047 
  1048     // Main exported methods
  1049 
  1050     /**
  1051      * Attempts to acquire in exclusive mode. This method should query
  1052      * if the state of the object permits it to be acquired in the
  1053      * exclusive mode, and if so to acquire it.
  1054      *
  1055      * <p>This method is always invoked by the thread performing
  1056      * acquire.  If this method reports failure, the acquire method
  1057      * may queue the thread, if it is not already queued, until it is
  1058      * signalled by a release from some other thread. This can be used
  1059      * to implement method {@link Lock#tryLock()}.
  1060      *
  1061      * <p>The default
  1062      * implementation throws {@link UnsupportedOperationException}.
  1063      *
  1064      * @param arg the acquire argument. This value is always the one
  1065      *        passed to an acquire method, or is the value saved on entry
  1066      *        to a condition wait.  The value is otherwise uninterpreted
  1067      *        and can represent anything you like.
  1068      * @return {@code true} if successful. Upon success, this object has
  1069      *         been acquired.
  1070      * @throws IllegalMonitorStateException if acquiring would place this
  1071      *         synchronizer in an illegal state. This exception must be
  1072      *         thrown in a consistent fashion for synchronization to work
  1073      *         correctly.
  1074      * @throws UnsupportedOperationException if exclusive mode is not supported
  1075      */
  1076     protected boolean tryAcquire(int arg) {
  1077         throw new UnsupportedOperationException();
  1078     }
  1079 
  1080     /**
  1081      * Attempts to set the state to reflect a release in exclusive
  1082      * mode.
  1083      *
  1084      * <p>This method is always invoked by the thread performing release.
  1085      *
  1086      * <p>The default implementation throws
  1087      * {@link UnsupportedOperationException}.
  1088      *
  1089      * @param arg the release argument. This value is always the one
  1090      *        passed to a release method, or the current state value upon
  1091      *        entry to a condition wait.  The value is otherwise
  1092      *        uninterpreted and can represent anything you like.
  1093      * @return {@code true} if this object is now in a fully released
  1094      *         state, so that any waiting threads may attempt to acquire;
  1095      *         and {@code false} otherwise.
  1096      * @throws IllegalMonitorStateException if releasing would place this
  1097      *         synchronizer in an illegal state. This exception must be
  1098      *         thrown in a consistent fashion for synchronization to work
  1099      *         correctly.
  1100      * @throws UnsupportedOperationException if exclusive mode is not supported
  1101      */
  1102     protected boolean tryRelease(int arg) {
  1103         throw new UnsupportedOperationException();
  1104     }
  1105 
  1106     /**
  1107      * Attempts to acquire in shared mode. This method should query if
  1108      * the state of the object permits it to be acquired in the shared
  1109      * mode, and if so to acquire it.
  1110      *
  1111      * <p>This method is always invoked by the thread performing
  1112      * acquire.  If this method reports failure, the acquire method
  1113      * may queue the thread, if it is not already queued, until it is
  1114      * signalled by a release from some other thread.
  1115      *
  1116      * <p>The default implementation throws {@link
  1117      * UnsupportedOperationException}.
  1118      *
  1119      * @param arg the acquire argument. This value is always the one
  1120      *        passed to an acquire method, or is the value saved on entry
  1121      *        to a condition wait.  The value is otherwise uninterpreted
  1122      *        and can represent anything you like.
  1123      * @return a negative value on failure; zero if acquisition in shared
  1124      *         mode succeeded but no subsequent shared-mode acquire can
  1125      *         succeed; and a positive value if acquisition in shared
  1126      *         mode succeeded and subsequent shared-mode acquires might
  1127      *         also succeed, in which case a subsequent waiting thread
  1128      *         must check availability. (Support for three different
  1129      *         return values enables this method to be used in contexts
  1130      *         where acquires only sometimes act exclusively.)  Upon
  1131      *         success, this object has been acquired.
  1132      * @throws IllegalMonitorStateException if acquiring would place this
  1133      *         synchronizer in an illegal state. This exception must be
  1134      *         thrown in a consistent fashion for synchronization to work
  1135      *         correctly.
  1136      * @throws UnsupportedOperationException if shared mode is not supported
  1137      */
  1138     protected int tryAcquireShared(int arg) {
  1139         throw new UnsupportedOperationException();
  1140     }
  1141 
  1142     /**
  1143      * Attempts to set the state to reflect a release in shared mode.
  1144      *
  1145      * <p>This method is always invoked by the thread performing release.
  1146      *
  1147      * <p>The default implementation throws
  1148      * {@link UnsupportedOperationException}.
  1149      *
  1150      * @param arg the release argument. This value is always the one
  1151      *        passed to a release method, or the current state value upon
  1152      *        entry to a condition wait.  The value is otherwise
  1153      *        uninterpreted and can represent anything you like.
  1154      * @return {@code true} if this release of shared mode may permit a
  1155      *         waiting acquire (shared or exclusive) to succeed; and
  1156      *         {@code false} otherwise
  1157      * @throws IllegalMonitorStateException if releasing would place this
  1158      *         synchronizer in an illegal state. This exception must be
  1159      *         thrown in a consistent fashion for synchronization to work
  1160      *         correctly.
  1161      * @throws UnsupportedOperationException if shared mode is not supported
  1162      */
  1163     protected boolean tryReleaseShared(int arg) {
  1164         throw new UnsupportedOperationException();
  1165     }
  1166 
  1167     /**
  1168      * Returns {@code true} if synchronization is held exclusively with
  1169      * respect to the current (calling) thread.  This method is invoked
  1170      * upon each call to a non-waiting {@link ConditionObject} method.
  1171      * (Waiting methods instead invoke {@link #release}.)
  1172      *
  1173      * <p>The default implementation throws {@link
  1174      * UnsupportedOperationException}. This method is invoked
  1175      * internally only within {@link ConditionObject} methods, so need
  1176      * not be defined if conditions are not used.
  1177      *
  1178      * @return {@code true} if synchronization is held exclusively;
  1179      *         {@code false} otherwise
  1180      * @throws UnsupportedOperationException if conditions are not supported
  1181      */
  1182     protected boolean isHeldExclusively() {
  1183         throw new UnsupportedOperationException();
  1184     }
  1185 
  1186     /**
  1187      * Acquires in exclusive mode, ignoring interrupts.  Implemented
  1188      * by invoking at least once {@link #tryAcquire},
  1189      * returning on success.  Otherwise the thread is queued, possibly
  1190      * repeatedly blocking and unblocking, invoking {@link
  1191      * #tryAcquire} until success.  This method can be used
  1192      * to implement method {@link Lock#lock}.
  1193      *
  1194      * @param arg the acquire argument.  This value is conveyed to
  1195      *        {@link #tryAcquire} but is otherwise uninterpreted and
  1196      *        can represent anything you like.
  1197      */
  1198     public final void acquire(int arg) {
  1199         if (!tryAcquire(arg) &&
  1200             acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
  1201             selfInterrupt();
  1202     }
  1203 
  1204     /**
  1205      * Acquires in exclusive mode, aborting if interrupted.
  1206      * Implemented by first checking interrupt status, then invoking
  1207      * at least once {@link #tryAcquire}, returning on
  1208      * success.  Otherwise the thread is queued, possibly repeatedly
  1209      * blocking and unblocking, invoking {@link #tryAcquire}
  1210      * until success or the thread is interrupted.  This method can be
  1211      * used to implement method {@link Lock#lockInterruptibly}.
  1212      *
  1213      * @param arg the acquire argument.  This value is conveyed to
  1214      *        {@link #tryAcquire} but is otherwise uninterpreted and
  1215      *        can represent anything you like.
  1216      * @throws InterruptedException if the current thread is interrupted
  1217      */
  1218     public final void acquireInterruptibly(int arg)
  1219             throws InterruptedException {
  1220         if (Thread.interrupted())
  1221             throw new InterruptedException();
  1222         if (!tryAcquire(arg))
  1223             doAcquireInterruptibly(arg);
  1224     }
  1225 
  1226     /**
  1227      * Attempts to acquire in exclusive mode, aborting if interrupted,
  1228      * and failing if the given timeout elapses.  Implemented by first
  1229      * checking interrupt status, then invoking at least once {@link
  1230      * #tryAcquire}, returning on success.  Otherwise, the thread is
  1231      * queued, possibly repeatedly blocking and unblocking, invoking
  1232      * {@link #tryAcquire} until success or the thread is interrupted
  1233      * or the timeout elapses.  This method can be used to implement
  1234      * method {@link Lock#tryLock(long, TimeUnit)}.
  1235      *
  1236      * @param arg the acquire argument.  This value is conveyed to
  1237      *        {@link #tryAcquire} but is otherwise uninterpreted and
  1238      *        can represent anything you like.
  1239      * @param nanosTimeout the maximum number of nanoseconds to wait
  1240      * @return {@code true} if acquired; {@code false} if timed out
  1241      * @throws InterruptedException if the current thread is interrupted
  1242      */
  1243     public final boolean tryAcquireNanos(int arg, long nanosTimeout)
  1244             throws InterruptedException {
  1245         if (Thread.interrupted())
  1246             throw new InterruptedException();
  1247         return tryAcquire(arg) ||
  1248             doAcquireNanos(arg, nanosTimeout);
  1249     }
  1250 
  1251     /**
  1252      * Releases in exclusive mode.  Implemented by unblocking one or
  1253      * more threads if {@link #tryRelease} returns true.
  1254      * This method can be used to implement method {@link Lock#unlock}.
  1255      *
  1256      * @param arg the release argument.  This value is conveyed to
  1257      *        {@link #tryRelease} but is otherwise uninterpreted and
  1258      *        can represent anything you like.
  1259      * @return the value returned from {@link #tryRelease}
  1260      */
  1261     public final boolean release(int arg) {
  1262         if (tryRelease(arg)) {
  1263             Node h = head;
  1264             if (h != null && h.waitStatus != 0)
  1265                 unparkSuccessor(h);
  1266             return true;
  1267         }
  1268         return false;
  1269     }
  1270 
  1271     /**
  1272      * Acquires in shared mode, ignoring interrupts.  Implemented by
  1273      * first invoking at least once {@link #tryAcquireShared},
  1274      * returning on success.  Otherwise the thread is queued, possibly
  1275      * repeatedly blocking and unblocking, invoking {@link
  1276      * #tryAcquireShared} until success.
  1277      *
  1278      * @param arg the acquire argument.  This value is conveyed to
  1279      *        {@link #tryAcquireShared} but is otherwise uninterpreted
  1280      *        and can represent anything you like.
  1281      */
  1282     public final void acquireShared(int arg) {
  1283         if (tryAcquireShared(arg) < 0)
  1284             doAcquireShared(arg);
  1285     }
  1286 
  1287     /**
  1288      * Acquires in shared mode, aborting if interrupted.  Implemented
  1289      * by first checking interrupt status, then invoking at least once
  1290      * {@link #tryAcquireShared}, returning on success.  Otherwise the
  1291      * thread is queued, possibly repeatedly blocking and unblocking,
  1292      * invoking {@link #tryAcquireShared} until success or the thread
  1293      * is interrupted.
  1294      * @param arg the acquire argument
  1295      * This value is conveyed to {@link #tryAcquireShared} but is
  1296      * otherwise uninterpreted and can represent anything
  1297      * you like.
  1298      * @throws InterruptedException if the current thread is interrupted
  1299      */
  1300     public final void acquireSharedInterruptibly(int arg)
  1301             throws InterruptedException {
  1302         if (Thread.interrupted())
  1303             throw new InterruptedException();
  1304         if (tryAcquireShared(arg) < 0)
  1305             doAcquireSharedInterruptibly(arg);
  1306     }
  1307 
  1308     /**
  1309      * Attempts to acquire in shared mode, aborting if interrupted, and
  1310      * failing if the given timeout elapses.  Implemented by first
  1311      * checking interrupt status, then invoking at least once {@link
  1312      * #tryAcquireShared}, returning on success.  Otherwise, the
  1313      * thread is queued, possibly repeatedly blocking and unblocking,
  1314      * invoking {@link #tryAcquireShared} until success or the thread
  1315      * is interrupted or the timeout elapses.
  1316      *
  1317      * @param arg the acquire argument.  This value is conveyed to
  1318      *        {@link #tryAcquireShared} but is otherwise uninterpreted
  1319      *        and can represent anything you like.
  1320      * @param nanosTimeout the maximum number of nanoseconds to wait
  1321      * @return {@code true} if acquired; {@code false} if timed out
  1322      * @throws InterruptedException if the current thread is interrupted
  1323      */
  1324     public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
  1325             throws InterruptedException {
  1326         if (Thread.interrupted())
  1327             throw new InterruptedException();
  1328         return tryAcquireShared(arg) >= 0 ||
  1329             doAcquireSharedNanos(arg, nanosTimeout);
  1330     }
  1331 
  1332     /**
  1333      * Releases in shared mode.  Implemented by unblocking one or more
  1334      * threads if {@link #tryReleaseShared} returns true.
  1335      *
  1336      * @param arg the release argument.  This value is conveyed to
  1337      *        {@link #tryReleaseShared} but is otherwise uninterpreted
  1338      *        and can represent anything you like.
  1339      * @return the value returned from {@link #tryReleaseShared}
  1340      */
  1341     public final boolean releaseShared(int arg) {
  1342         if (tryReleaseShared(arg)) {
  1343             doReleaseShared();
  1344             return true;
  1345         }
  1346         return false;
  1347     }
  1348 
  1349     // Queue inspection methods
  1350 
  1351     /**
  1352      * Queries whether any threads are waiting to acquire. Note that
  1353      * because cancellations due to interrupts and timeouts may occur
  1354      * at any time, a {@code true} return does not guarantee that any
  1355      * other thread will ever acquire.
  1356      *
  1357      * <p>In this implementation, this operation returns in
  1358      * constant time.
  1359      *
  1360      * @return {@code true} if there may be other threads waiting to acquire
  1361      */
  1362     public final boolean hasQueuedThreads() {
  1363         return head != tail;
  1364     }
  1365 
  1366     /**
  1367      * Queries whether any threads have ever contended to acquire this
  1368      * synchronizer; that is if an acquire method has ever blocked.
  1369      *
  1370      * <p>In this implementation, this operation returns in
  1371      * constant time.
  1372      *
  1373      * @return {@code true} if there has ever been contention
  1374      */
  1375     public final boolean hasContended() {
  1376         return head != null;
  1377     }
  1378 
  1379     /**
  1380      * Returns the first (longest-waiting) thread in the queue, or
  1381      * {@code null} if no threads are currently queued.
  1382      *
  1383      * <p>In this implementation, this operation normally returns in
  1384      * constant time, but may iterate upon contention if other threads are
  1385      * concurrently modifying the queue.
  1386      *
  1387      * @return the first (longest-waiting) thread in the queue, or
  1388      *         {@code null} if no threads are currently queued
  1389      */
  1390     public final Thread getFirstQueuedThread() {
  1391         // handle only fast path, else relay
  1392         return (head == tail) ? null : fullGetFirstQueuedThread();
  1393     }
  1394 
  1395     /**
  1396      * Version of getFirstQueuedThread called when fastpath fails
  1397      */
  1398     private Thread fullGetFirstQueuedThread() {
  1399         /*
  1400          * The first node is normally head.next. Try to get its
  1401          * thread field, ensuring consistent reads: If thread
  1402          * field is nulled out or s.prev is no longer head, then
  1403          * some other thread(s) concurrently performed setHead in
  1404          * between some of our reads. We try this twice before
  1405          * resorting to traversal.
  1406          */
  1407         Node h, s;
  1408         Thread st;
  1409         if (((h = head) != null && (s = h.next) != null &&
  1410              s.prev == head && (st = s.thread) != null) ||
  1411             ((h = head) != null && (s = h.next) != null &&
  1412              s.prev == head && (st = s.thread) != null))
  1413             return st;
  1414 
  1415         /*
  1416          * Head's next field might not have been set yet, or may have
  1417          * been unset after setHead. So we must check to see if tail
  1418          * is actually first node. If not, we continue on, safely
  1419          * traversing from tail back to head to find first,
  1420          * guaranteeing termination.
  1421          */
  1422 
  1423         Node t = tail;
  1424         Thread firstThread = null;
  1425         while (t != null && t != head) {
  1426             Thread tt = t.thread;
  1427             if (tt != null)
  1428                 firstThread = tt;
  1429             t = t.prev;
  1430         }
  1431         return firstThread;
  1432     }
  1433 
  1434     /**
  1435      * Returns true if the given thread is currently queued.
  1436      *
  1437      * <p>This implementation traverses the queue to determine
  1438      * presence of the given thread.
  1439      *
  1440      * @param thread the thread
  1441      * @return {@code true} if the given thread is on the queue
  1442      * @throws NullPointerException if the thread is null
  1443      */
  1444     public final boolean isQueued(Thread thread) {
  1445         if (thread == null)
  1446             throw new NullPointerException();
  1447         for (Node p = tail; p != null; p = p.prev)
  1448             if (p.thread == thread)
  1449                 return true;
  1450         return false;
  1451     }
  1452 
  1453     /**
  1454      * Returns {@code true} if the apparent first queued thread, if one
  1455      * exists, is waiting in exclusive mode.  If this method returns
  1456      * {@code true}, and the current thread is attempting to acquire in
  1457      * shared mode (that is, this method is invoked from {@link
  1458      * #tryAcquireShared}) then it is guaranteed that the current thread
  1459      * is not the first queued thread.  Used only as a heuristic in
  1460      * ReentrantReadWriteLock.
  1461      */
  1462     final boolean apparentlyFirstQueuedIsExclusive() {
  1463         Node h, s;
  1464         return (h = head) != null &&
  1465             (s = h.next)  != null &&
  1466             !s.isShared()         &&
  1467             s.thread != null;
  1468     }
  1469 
  1470     /**
  1471      * Queries whether any threads have been waiting to acquire longer
  1472      * than the current thread.
  1473      *
  1474      * <p>An invocation of this method is equivalent to (but may be
  1475      * more efficient than):
  1476      *  <pre> {@code
  1477      * getFirstQueuedThread() != Thread.currentThread() &&
  1478      * hasQueuedThreads()}</pre>
  1479      *
  1480      * <p>Note that because cancellations due to interrupts and
  1481      * timeouts may occur at any time, a {@code true} return does not
  1482      * guarantee that some other thread will acquire before the current
  1483      * thread.  Likewise, it is possible for another thread to win a
  1484      * race to enqueue after this method has returned {@code false},
  1485      * due to the queue being empty.
  1486      *
  1487      * <p>This method is designed to be used by a fair synchronizer to
  1488      * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
  1489      * Such a synchronizer's {@link #tryAcquire} method should return
  1490      * {@code false}, and its {@link #tryAcquireShared} method should
  1491      * return a negative value, if this method returns {@code true}
  1492      * (unless this is a reentrant acquire).  For example, the {@code
  1493      * tryAcquire} method for a fair, reentrant, exclusive mode
  1494      * synchronizer might look like this:
  1495      *
  1496      *  <pre> {@code
  1497      * protected boolean tryAcquire(int arg) {
  1498      *   if (isHeldExclusively()) {
  1499      *     // A reentrant acquire; increment hold count
  1500      *     return true;
  1501      *   } else if (hasQueuedPredecessors()) {
  1502      *     return false;
  1503      *   } else {
  1504      *     // try to acquire normally
  1505      *   }
  1506      * }}</pre>
  1507      *
  1508      * @return {@code true} if there is a queued thread preceding the
  1509      *         current thread, and {@code false} if the current thread
  1510      *         is at the head of the queue or the queue is empty
  1511      * @since 1.7
  1512      */
  1513     public final boolean hasQueuedPredecessors() {
  1514         // The correctness of this depends on head being initialized
  1515         // before tail and on head.next being accurate if the current
  1516         // thread is first in queue.
  1517         Node t = tail; // Read fields in reverse initialization order
  1518         Node h = head;
  1519         Node s;
  1520         return h != t &&
  1521             ((s = h.next) == null || s.thread != Thread.currentThread());
  1522     }
  1523 
  1524 
  1525     // Instrumentation and monitoring methods
  1526 
  1527     /**
  1528      * Returns an estimate of the number of threads waiting to
  1529      * acquire.  The value is only an estimate because the number of
  1530      * threads may change dynamically while this method traverses
  1531      * internal data structures.  This method is designed for use in
  1532      * monitoring system state, not for synchronization
  1533      * control.
  1534      *
  1535      * @return the estimated number of threads waiting to acquire
  1536      */
  1537     public final int getQueueLength() {
  1538         int n = 0;
  1539         for (Node p = tail; p != null; p = p.prev) {
  1540             if (p.thread != null)
  1541                 ++n;
  1542         }
  1543         return n;
  1544     }
  1545 
  1546     /**
  1547      * Returns a collection containing threads that may be waiting to
  1548      * acquire.  Because the actual set of threads may change
  1549      * dynamically while constructing this result, the returned
  1550      * collection is only a best-effort estimate.  The elements of the
  1551      * returned collection are in no particular order.  This method is
  1552      * designed to facilitate construction of subclasses that provide
  1553      * more extensive monitoring facilities.
  1554      *
  1555      * @return the collection of threads
  1556      */
  1557     public final Collection<Thread> getQueuedThreads() {
  1558         ArrayList<Thread> list = new ArrayList<Thread>();
  1559         for (Node p = tail; p != null; p = p.prev) {
  1560             Thread t = p.thread;
  1561             if (t != null)
  1562                 list.add(t);
  1563         }
  1564         return list;
  1565     }
  1566 
  1567     /**
  1568      * Returns a collection containing threads that may be waiting to
  1569      * acquire in exclusive mode. This has the same properties
  1570      * as {@link #getQueuedThreads} except that it only returns
  1571      * those threads waiting due to an exclusive acquire.
  1572      *
  1573      * @return the collection of threads
  1574      */
  1575     public final Collection<Thread> getExclusiveQueuedThreads() {
  1576         ArrayList<Thread> list = new ArrayList<Thread>();
  1577         for (Node p = tail; p != null; p = p.prev) {
  1578             if (!p.isShared()) {
  1579                 Thread t = p.thread;
  1580                 if (t != null)
  1581                     list.add(t);
  1582             }
  1583         }
  1584         return list;
  1585     }
  1586 
  1587     /**
  1588      * Returns a collection containing threads that may be waiting to
  1589      * acquire in shared mode. This has the same properties
  1590      * as {@link #getQueuedThreads} except that it only returns
  1591      * those threads waiting due to a shared acquire.
  1592      *
  1593      * @return the collection of threads
  1594      */
  1595     public final Collection<Thread> getSharedQueuedThreads() {
  1596         ArrayList<Thread> list = new ArrayList<Thread>();
  1597         for (Node p = tail; p != null; p = p.prev) {
  1598             if (p.isShared()) {
  1599                 Thread t = p.thread;
  1600                 if (t != null)
  1601                     list.add(t);
  1602             }
  1603         }
  1604         return list;
  1605     }
  1606 
  1607     /**
  1608      * Returns a string identifying this synchronizer, as well as its state.
  1609      * The state, in brackets, includes the String {@code "State ="}
  1610      * followed by the current value of {@link #getState}, and either
  1611      * {@code "nonempty"} or {@code "empty"} depending on whether the
  1612      * queue is empty.
  1613      *
  1614      * @return a string identifying this synchronizer, as well as its state
  1615      */
  1616     public String toString() {
  1617         int s = getState();
  1618         String q  = hasQueuedThreads() ? "non" : "";
  1619         return super.toString() +
  1620             "[State = " + s + ", " + q + "empty queue]";
  1621     }
  1622 
  1623 
  1624     // Internal support methods for Conditions
  1625 
  1626     /**
  1627      * Returns true if a node, always one that was initially placed on
  1628      * a condition queue, is now waiting to reacquire on sync queue.
  1629      * @param node the node
  1630      * @return true if is reacquiring
  1631      */
  1632     final boolean isOnSyncQueue(Node node) {
  1633         if (node.waitStatus == Node.CONDITION || node.prev == null)
  1634             return false;
  1635         if (node.next != null) // If has successor, it must be on queue
  1636             return true;
  1637         /*
  1638          * node.prev can be non-null, but not yet on queue because
  1639          * the CAS to place it on queue can fail. So we have to
  1640          * traverse from tail to make sure it actually made it.  It
  1641          * will always be near the tail in calls to this method, and
  1642          * unless the CAS failed (which is unlikely), it will be
  1643          * there, so we hardly ever traverse much.
  1644          */
  1645         return findNodeFromTail(node);
  1646     }
  1647 
  1648     /**
  1649      * Returns true if node is on sync queue by searching backwards from tail.
  1650      * Called only when needed by isOnSyncQueue.
  1651      * @return true if present
  1652      */
  1653     private boolean findNodeFromTail(Node node) {
  1654         Node t = tail;
  1655         for (;;) {
  1656             if (t == node)
  1657                 return true;
  1658             if (t == null)
  1659                 return false;
  1660             t = t.prev;
  1661         }
  1662     }
  1663 
  1664     /**
  1665      * Transfers a node from a condition queue onto sync queue.
  1666      * Returns true if successful.
  1667      * @param node the node
  1668      * @return true if successfully transferred (else the node was
  1669      * cancelled before signal).
  1670      */
  1671     final boolean transferForSignal(Node node) {
  1672         /*
  1673          * If cannot change waitStatus, the node has been cancelled.
  1674          */
  1675         if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
  1676             return false;
  1677 
  1678         /*
  1679          * Splice onto queue and try to set waitStatus of predecessor to
  1680          * indicate that thread is (probably) waiting. If cancelled or
  1681          * attempt to set waitStatus fails, wake up to resync (in which
  1682          * case the waitStatus can be transiently and harmlessly wrong).
  1683          */
  1684         Node p = enq(node);
  1685         int ws = p.waitStatus;
  1686         if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
  1687             LockSupport.unpark(node.thread);
  1688         return true;
  1689     }
  1690 
  1691     /**
  1692      * Transfers node, if necessary, to sync queue after a cancelled
  1693      * wait. Returns true if thread was cancelled before being
  1694      * signalled.
  1695      * @param current the waiting thread
  1696      * @param node its node
  1697      * @return true if cancelled before the node was signalled
  1698      */
  1699     final boolean transferAfterCancelledWait(Node node) {
  1700         if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
  1701             enq(node);
  1702             return true;
  1703         }
  1704         /*
  1705          * If we lost out to a signal(), then we can't proceed
  1706          * until it finishes its enq().  Cancelling during an
  1707          * incomplete transfer is both rare and transient, so just
  1708          * spin.
  1709          */
  1710         while (!isOnSyncQueue(node))
  1711             Thread.yield();
  1712         return false;
  1713     }
  1714 
  1715     /**
  1716      * Invokes release with current state value; returns saved state.
  1717      * Cancels node and throws exception on failure.
  1718      * @param node the condition node for this wait
  1719      * @return previous sync state
  1720      */
  1721     final int fullyRelease(Node node) {
  1722         boolean failed = true;
  1723         try {
  1724             int savedState = getState();
  1725             if (release(savedState)) {
  1726                 failed = false;
  1727                 return savedState;
  1728             } else {
  1729                 throw new IllegalMonitorStateException();
  1730             }
  1731         } finally {
  1732             if (failed)
  1733                 node.waitStatus = Node.CANCELLED;
  1734         }
  1735     }
  1736 
  1737     // Instrumentation methods for conditions
  1738 
  1739     /**
  1740      * Queries whether the given ConditionObject
  1741      * uses this synchronizer as its lock.
  1742      *
  1743      * @param condition the condition
  1744      * @return <tt>true</tt> if owned
  1745      * @throws NullPointerException if the condition is null
  1746      */
  1747     public final boolean owns(ConditionObject condition) {
  1748         if (condition == null)
  1749             throw new NullPointerException();
  1750         return condition.isOwnedBy(this);
  1751     }
  1752 
  1753     /**
  1754      * Queries whether any threads are waiting on the given condition
  1755      * associated with this synchronizer. Note that because timeouts
  1756      * and interrupts may occur at any time, a <tt>true</tt> return
  1757      * does not guarantee that a future <tt>signal</tt> will awaken
  1758      * any threads.  This method is designed primarily for use in
  1759      * monitoring of the system state.
  1760      *
  1761      * @param condition the condition
  1762      * @return <tt>true</tt> if there are any waiting threads
  1763      * @throws IllegalMonitorStateException if exclusive synchronization
  1764      *         is not held
  1765      * @throws IllegalArgumentException if the given condition is
  1766      *         not associated with this synchronizer
  1767      * @throws NullPointerException if the condition is null
  1768      */
  1769     public final boolean hasWaiters(ConditionObject condition) {
  1770         if (!owns(condition))
  1771             throw new IllegalArgumentException("Not owner");
  1772         return condition.hasWaiters();
  1773     }
  1774 
  1775     /**
  1776      * Returns an estimate of the number of threads waiting on the
  1777      * given condition associated with this synchronizer. Note that
  1778      * because timeouts and interrupts may occur at any time, the
  1779      * estimate serves only as an upper bound on the actual number of
  1780      * waiters.  This method is designed for use in monitoring of the
  1781      * system state, not for synchronization control.
  1782      *
  1783      * @param condition the condition
  1784      * @return the estimated number of waiting threads
  1785      * @throws IllegalMonitorStateException if exclusive synchronization
  1786      *         is not held
  1787      * @throws IllegalArgumentException if the given condition is
  1788      *         not associated with this synchronizer
  1789      * @throws NullPointerException if the condition is null
  1790      */
  1791     public final int getWaitQueueLength(ConditionObject condition) {
  1792         if (!owns(condition))
  1793             throw new IllegalArgumentException("Not owner");
  1794         return condition.getWaitQueueLength();
  1795     }
  1796 
  1797     /**
  1798      * Returns a collection containing those threads that may be
  1799      * waiting on the given condition associated with this
  1800      * synchronizer.  Because the actual set of threads may change
  1801      * dynamically while constructing this result, the returned
  1802      * collection is only a best-effort estimate. The elements of the
  1803      * returned collection are in no particular order.
  1804      *
  1805      * @param condition the condition
  1806      * @return the collection of threads
  1807      * @throws IllegalMonitorStateException if exclusive synchronization
  1808      *         is not held
  1809      * @throws IllegalArgumentException if the given condition is
  1810      *         not associated with this synchronizer
  1811      * @throws NullPointerException if the condition is null
  1812      */
  1813     public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
  1814         if (!owns(condition))
  1815             throw new IllegalArgumentException("Not owner");
  1816         return condition.getWaitingThreads();
  1817     }
  1818 
  1819     /**
  1820      * Condition implementation for a {@link
  1821      * AbstractQueuedSynchronizer} serving as the basis of a {@link
  1822      * Lock} implementation.
  1823      *
  1824      * <p>Method documentation for this class describes mechanics,
  1825      * not behavioral specifications from the point of view of Lock
  1826      * and Condition users. Exported versions of this class will in
  1827      * general need to be accompanied by documentation describing
  1828      * condition semantics that rely on those of the associated
  1829      * <tt>AbstractQueuedSynchronizer</tt>.
  1830      *
  1831      * <p>This class is Serializable, but all fields are transient,
  1832      * so deserialized conditions have no waiters.
  1833      */
  1834     public class ConditionObject implements Condition, java.io.Serializable {
  1835         private static final long serialVersionUID = 1173984872572414699L;
  1836         /** First node of condition queue. */
  1837         private transient Node firstWaiter;
  1838         /** Last node of condition queue. */
  1839         private transient Node lastWaiter;
  1840 
  1841         /**
  1842          * Creates a new <tt>ConditionObject</tt> instance.
  1843          */
  1844         public ConditionObject() { }
  1845 
  1846         // Internal methods
  1847 
  1848         /**
  1849          * Adds a new waiter to wait queue.
  1850          * @return its new wait node
  1851          */
  1852         private Node addConditionWaiter() {
  1853             Node t = lastWaiter;
  1854             // If lastWaiter is cancelled, clean out.
  1855             if (t != null && t.waitStatus != Node.CONDITION) {
  1856                 unlinkCancelledWaiters();
  1857                 t = lastWaiter;
  1858             }
  1859             Node node = new Node(Thread.currentThread(), Node.CONDITION);
  1860             if (t == null)
  1861                 firstWaiter = node;
  1862             else
  1863                 t.nextWaiter = node;
  1864             lastWaiter = node;
  1865             return node;
  1866         }
  1867 
  1868         /**
  1869          * Removes and transfers nodes until hit non-cancelled one or
  1870          * null. Split out from signal in part to encourage compilers
  1871          * to inline the case of no waiters.
  1872          * @param first (non-null) the first node on condition queue
  1873          */
  1874         private void doSignal(Node first) {
  1875             do {
  1876                 if ( (firstWaiter = first.nextWaiter) == null)
  1877                     lastWaiter = null;
  1878                 first.nextWaiter = null;
  1879             } while (!transferForSignal(first) &&
  1880                      (first = firstWaiter) != null);
  1881         }
  1882 
  1883         /**
  1884          * Removes and transfers all nodes.
  1885          * @param first (non-null) the first node on condition queue
  1886          */
  1887         private void doSignalAll(Node first) {
  1888             lastWaiter = firstWaiter = null;
  1889             do {
  1890                 Node next = first.nextWaiter;
  1891                 first.nextWaiter = null;
  1892                 transferForSignal(first);
  1893                 first = next;
  1894             } while (first != null);
  1895         }
  1896 
  1897         /**
  1898          * Unlinks cancelled waiter nodes from condition queue.
  1899          * Called only while holding lock. This is called when
  1900          * cancellation occurred during condition wait, and upon
  1901          * insertion of a new waiter when lastWaiter is seen to have
  1902          * been cancelled. This method is needed to avoid garbage
  1903          * retention in the absence of signals. So even though it may
  1904          * require a full traversal, it comes into play only when
  1905          * timeouts or cancellations occur in the absence of
  1906          * signals. It traverses all nodes rather than stopping at a
  1907          * particular target to unlink all pointers to garbage nodes
  1908          * without requiring many re-traversals during cancellation
  1909          * storms.
  1910          */
  1911         private void unlinkCancelledWaiters() {
  1912             Node t = firstWaiter;
  1913             Node trail = null;
  1914             while (t != null) {
  1915                 Node next = t.nextWaiter;
  1916                 if (t.waitStatus != Node.CONDITION) {
  1917                     t.nextWaiter = null;
  1918                     if (trail == null)
  1919                         firstWaiter = next;
  1920                     else
  1921                         trail.nextWaiter = next;
  1922                     if (next == null)
  1923                         lastWaiter = trail;
  1924                 }
  1925                 else
  1926                     trail = t;
  1927                 t = next;
  1928             }
  1929         }
  1930 
  1931         // public methods
  1932 
  1933         /**
  1934          * Moves the longest-waiting thread, if one exists, from the
  1935          * wait queue for this condition to the wait queue for the
  1936          * owning lock.
  1937          *
  1938          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
  1939          *         returns {@code false}
  1940          */
  1941         public final void signal() {
  1942             if (!isHeldExclusively())
  1943                 throw new IllegalMonitorStateException();
  1944             Node first = firstWaiter;
  1945             if (first != null)
  1946                 doSignal(first);
  1947         }
  1948 
  1949         /**
  1950          * Moves all threads from the wait queue for this condition to
  1951          * the wait queue for the owning lock.
  1952          *
  1953          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
  1954          *         returns {@code false}
  1955          */
  1956         public final void signalAll() {
  1957             if (!isHeldExclusively())
  1958                 throw new IllegalMonitorStateException();
  1959             Node first = firstWaiter;
  1960             if (first != null)
  1961                 doSignalAll(first);
  1962         }
  1963 
  1964         /**
  1965          * Implements uninterruptible condition wait.
  1966          * <ol>
  1967          * <li> Save lock state returned by {@link #getState}.
  1968          * <li> Invoke {@link #release} with
  1969          *      saved state as argument, throwing
  1970          *      IllegalMonitorStateException if it fails.
  1971          * <li> Block until signalled.
  1972          * <li> Reacquire by invoking specialized version of
  1973          *      {@link #acquire} with saved state as argument.
  1974          * </ol>
  1975          */
  1976         public final void awaitUninterruptibly() {
  1977             Node node = addConditionWaiter();
  1978             int savedState = fullyRelease(node);
  1979             boolean interrupted = false;
  1980             while (!isOnSyncQueue(node)) {
  1981                 LockSupport.park(this);
  1982                 if (Thread.interrupted())
  1983                     interrupted = true;
  1984             }
  1985             if (acquireQueued(node, savedState) || interrupted)
  1986                 selfInterrupt();
  1987         }
  1988 
  1989         /*
  1990          * For interruptible waits, we need to track whether to throw
  1991          * InterruptedException, if interrupted while blocked on
  1992          * condition, versus reinterrupt current thread, if
  1993          * interrupted while blocked waiting to re-acquire.
  1994          */
  1995 
  1996         /** Mode meaning to reinterrupt on exit from wait */
  1997         private static final int REINTERRUPT =  1;
  1998         /** Mode meaning to throw InterruptedException on exit from wait */
  1999         private static final int THROW_IE    = -1;
  2000 
  2001         /**
  2002          * Checks for interrupt, returning THROW_IE if interrupted
  2003          * before signalled, REINTERRUPT if after signalled, or
  2004          * 0 if not interrupted.
  2005          */
  2006         private int checkInterruptWhileWaiting(Node node) {
  2007             return Thread.interrupted() ?
  2008                 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
  2009                 0;
  2010         }
  2011 
  2012         /**
  2013          * Throws InterruptedException, reinterrupts current thread, or
  2014          * does nothing, depending on mode.
  2015          */
  2016         private void reportInterruptAfterWait(int interruptMode)
  2017             throws InterruptedException {
  2018             if (interruptMode == THROW_IE)
  2019                 throw new InterruptedException();
  2020             else if (interruptMode == REINTERRUPT)
  2021                 selfInterrupt();
  2022         }
  2023 
  2024         /**
  2025          * Implements interruptible condition wait.
  2026          * <ol>
  2027          * <li> If current thread is interrupted, throw InterruptedException.
  2028          * <li> Save lock state returned by {@link #getState}.
  2029          * <li> Invoke {@link #release} with
  2030          *      saved state as argument, throwing
  2031          *      IllegalMonitorStateException if it fails.
  2032          * <li> Block until signalled or interrupted.
  2033          * <li> Reacquire by invoking specialized version of
  2034          *      {@link #acquire} with saved state as argument.
  2035          * <li> If interrupted while blocked in step 4, throw InterruptedException.
  2036          * </ol>
  2037          */
  2038         public final void await() throws InterruptedException {
  2039             if (Thread.interrupted())
  2040                 throw new InterruptedException();
  2041             Node node = addConditionWaiter();
  2042             int savedState = fullyRelease(node);
  2043             int interruptMode = 0;
  2044             while (!isOnSyncQueue(node)) {
  2045                 LockSupport.park(this);
  2046                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  2047                     break;
  2048             }
  2049             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  2050                 interruptMode = REINTERRUPT;
  2051             if (node.nextWaiter != null) // clean up if cancelled
  2052                 unlinkCancelledWaiters();
  2053             if (interruptMode != 0)
  2054                 reportInterruptAfterWait(interruptMode);
  2055         }
  2056 
  2057         /**
  2058          * Implements timed condition wait.
  2059          * <ol>
  2060          * <li> If current thread is interrupted, throw InterruptedException.
  2061          * <li> Save lock state returned by {@link #getState}.
  2062          * <li> Invoke {@link #release} with
  2063          *      saved state as argument, throwing
  2064          *      IllegalMonitorStateException if it fails.
  2065          * <li> Block until signalled, interrupted, or timed out.
  2066          * <li> Reacquire by invoking specialized version of
  2067          *      {@link #acquire} with saved state as argument.
  2068          * <li> If interrupted while blocked in step 4, throw InterruptedException.
  2069          * </ol>
  2070          */
  2071         public final long awaitNanos(long nanosTimeout)
  2072                 throws InterruptedException {
  2073             if (Thread.interrupted())
  2074                 throw new InterruptedException();
  2075             Node node = addConditionWaiter();
  2076             int savedState = fullyRelease(node);
  2077             long lastTime = System.nanoTime();
  2078             int interruptMode = 0;
  2079             while (!isOnSyncQueue(node)) {
  2080                 if (nanosTimeout <= 0L) {
  2081                     transferAfterCancelledWait(node);
  2082                     break;
  2083                 }
  2084                 LockSupport.parkNanos(this, nanosTimeout);
  2085                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  2086                     break;
  2087 
  2088                 long now = System.nanoTime();
  2089                 nanosTimeout -= now - lastTime;
  2090                 lastTime = now;
  2091             }
  2092             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  2093                 interruptMode = REINTERRUPT;
  2094             if (node.nextWaiter != null)
  2095                 unlinkCancelledWaiters();
  2096             if (interruptMode != 0)
  2097                 reportInterruptAfterWait(interruptMode);
  2098             return nanosTimeout - (System.nanoTime() - lastTime);
  2099         }
  2100 
  2101         /**
  2102          * Implements absolute timed condition wait.
  2103          * <ol>
  2104          * <li> If current thread is interrupted, throw InterruptedException.
  2105          * <li> Save lock state returned by {@link #getState}.
  2106          * <li> Invoke {@link #release} with
  2107          *      saved state as argument, throwing
  2108          *      IllegalMonitorStateException if it fails.
  2109          * <li> Block until signalled, interrupted, or timed out.
  2110          * <li> Reacquire by invoking specialized version of
  2111          *      {@link #acquire} with saved state as argument.
  2112          * <li> If interrupted while blocked in step 4, throw InterruptedException.
  2113          * <li> If timed out while blocked in step 4, return false, else true.
  2114          * </ol>
  2115          */
  2116         public final boolean awaitUntil(Date deadline)
  2117                 throws InterruptedException {
  2118             if (deadline == null)
  2119                 throw new NullPointerException();
  2120             long abstime = deadline.getTime();
  2121             if (Thread.interrupted())
  2122                 throw new InterruptedException();
  2123             Node node = addConditionWaiter();
  2124             int savedState = fullyRelease(node);
  2125             boolean timedout = false;
  2126             int interruptMode = 0;
  2127             while (!isOnSyncQueue(node)) {
  2128                 if (System.currentTimeMillis() > abstime) {
  2129                     timedout = transferAfterCancelledWait(node);
  2130                     break;
  2131                 }
  2132                 LockSupport.parkUntil(this, abstime);
  2133                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  2134                     break;
  2135             }
  2136             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  2137                 interruptMode = REINTERRUPT;
  2138             if (node.nextWaiter != null)
  2139                 unlinkCancelledWaiters();
  2140             if (interruptMode != 0)
  2141                 reportInterruptAfterWait(interruptMode);
  2142             return !timedout;
  2143         }
  2144 
  2145         /**
  2146          * Implements timed condition wait.
  2147          * <ol>
  2148          * <li> If current thread is interrupted, throw InterruptedException.
  2149          * <li> Save lock state returned by {@link #getState}.
  2150          * <li> Invoke {@link #release} with
  2151          *      saved state as argument, throwing
  2152          *      IllegalMonitorStateException if it fails.
  2153          * <li> Block until signalled, interrupted, or timed out.
  2154          * <li> Reacquire by invoking specialized version of
  2155          *      {@link #acquire} with saved state as argument.
  2156          * <li> If interrupted while blocked in step 4, throw InterruptedException.
  2157          * <li> If timed out while blocked in step 4, return false, else true.
  2158          * </ol>
  2159          */
  2160         public final boolean await(long time, TimeUnit unit)
  2161                 throws InterruptedException {
  2162             if (unit == null)
  2163                 throw new NullPointerException();
  2164             long nanosTimeout = unit.toNanos(time);
  2165             if (Thread.interrupted())
  2166                 throw new InterruptedException();
  2167             Node node = addConditionWaiter();
  2168             int savedState = fullyRelease(node);
  2169             long lastTime = System.nanoTime();
  2170             boolean timedout = false;
  2171             int interruptMode = 0;
  2172             while (!isOnSyncQueue(node)) {
  2173                 if (nanosTimeout <= 0L) {
  2174                     timedout = transferAfterCancelledWait(node);
  2175                     break;
  2176                 }
  2177                 if (nanosTimeout >= spinForTimeoutThreshold)
  2178                     LockSupport.parkNanos(this, nanosTimeout);
  2179                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
  2180                     break;
  2181                 long now = System.nanoTime();
  2182                 nanosTimeout -= now - lastTime;
  2183                 lastTime = now;
  2184             }
  2185             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
  2186                 interruptMode = REINTERRUPT;
  2187             if (node.nextWaiter != null)
  2188                 unlinkCancelledWaiters();
  2189             if (interruptMode != 0)
  2190                 reportInterruptAfterWait(interruptMode);
  2191             return !timedout;
  2192         }
  2193 
  2194         //  support for instrumentation
  2195 
  2196         /**
  2197          * Returns true if this condition was created by the given
  2198          * synchronization object.
  2199          *
  2200          * @return {@code true} if owned
  2201          */
  2202         final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
  2203             return sync == AbstractQueuedSynchronizer.this;
  2204         }
  2205 
  2206         /**
  2207          * Queries whether any threads are waiting on this condition.
  2208          * Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
  2209          *
  2210          * @return {@code true} if there are any waiting threads
  2211          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
  2212          *         returns {@code false}
  2213          */
  2214         protected final boolean hasWaiters() {
  2215             if (!isHeldExclusively())
  2216                 throw new IllegalMonitorStateException();
  2217             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
  2218                 if (w.waitStatus == Node.CONDITION)
  2219                     return true;
  2220             }
  2221             return false;
  2222         }
  2223 
  2224         /**
  2225          * Returns an estimate of the number of threads waiting on
  2226          * this condition.
  2227          * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
  2228          *
  2229          * @return the estimated number of waiting threads
  2230          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
  2231          *         returns {@code false}
  2232          */
  2233         protected final int getWaitQueueLength() {
  2234             if (!isHeldExclusively())
  2235                 throw new IllegalMonitorStateException();
  2236             int n = 0;
  2237             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
  2238                 if (w.waitStatus == Node.CONDITION)
  2239                     ++n;
  2240             }
  2241             return n;
  2242         }
  2243 
  2244         /**
  2245          * Returns a collection containing those threads that may be
  2246          * waiting on this Condition.
  2247          * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
  2248          *
  2249          * @return the collection of threads
  2250          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
  2251          *         returns {@code false}
  2252          */
  2253         protected final Collection<Thread> getWaitingThreads() {
  2254             if (!isHeldExclusively())
  2255                 throw new IllegalMonitorStateException();
  2256             ArrayList<Thread> list = new ArrayList<Thread>();
  2257             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
  2258                 if (w.waitStatus == Node.CONDITION) {
  2259                     Thread t = w.thread;
  2260                     if (t != null)
  2261                         list.add(t);
  2262                 }
  2263             }
  2264             return list;
  2265         }
  2266     }
  2267 
  2268     /**
  2269      * Setup to support compareAndSet. We need to natively implement
  2270      * this here: For the sake of permitting future enhancements, we
  2271      * cannot explicitly subclass AtomicInteger, which would be
  2272      * efficient and useful otherwise. So, as the lesser of evils, we
  2273      * natively implement using hotspot intrinsics API. And while we
  2274      * are at it, we do the same for other CASable fields (which could
  2275      * otherwise be done with atomic field updaters).
  2276      */
  2277 
  2278 
  2279     /**
  2280      * CAS head field. Used only by enq.
  2281      */
  2282     private final boolean compareAndSetHead(Node update) {
  2283         if (head == null) {
  2284             head = update;
  2285             return true;
  2286         }
  2287         return false;
  2288     }
  2289 
  2290     /**
  2291      * CAS tail field. Used only by enq.
  2292      */
  2293     private final boolean compareAndSetTail(Node expect, Node update) {
  2294         if (tail == null) {
  2295             tail = update;
  2296             return true;
  2297         }
  2298         return false;
  2299     }
  2300 
  2301     /**
  2302      * CAS waitStatus field of a node.
  2303      */
  2304     private static final boolean compareAndSetWaitStatus(Node node,
  2305                                                          int expect,
  2306                                                          int update) {
  2307         if (node.waitStatus == expect) {
  2308             node.waitStatus = update;
  2309             return true;
  2310         }
  2311         return false;
  2312     }
  2313 
  2314     /**
  2315      * CAS next field of a node.
  2316      */
  2317     private static final boolean compareAndSetNext(Node node,
  2318                                                    Node expect,
  2319                                                    Node update) {
  2320         if (node.next == expect) {
  2321             node.next = update;
  2322             return true;
  2323         }
  2324         return false;
  2325     }
  2326 }