OSDN Git Service

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