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