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