2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
7 package java.util.concurrent.locks;
9 import java.util.ArrayList;
10 import java.util.Collection;
11 import java.util.Date;
12 import java.util.concurrent.CountDownLatch;
13 import java.util.concurrent.TimeUnit;
14 import sun.misc.Unsafe;
17 * Provides a framework for implementing blocking locks and related
18 * synchronizers (semaphores, events, etc) that rely on
19 * first-in-first-out (FIFO) wait queues. This class is designed to
20 * be a useful basis for most kinds of synchronizers that rely on a
21 * single atomic <tt>int</tt> value to represent state. Subclasses
22 * must define the protected methods that change this state, and which
23 * define what that state means in terms of this object being acquired
24 * or released. Given these, the other methods in this class carry
25 * out all queuing and blocking mechanics. Subclasses can maintain
26 * other state fields, but only the atomically updated <tt>int</tt>
27 * value manipulated using methods {@link #getState}, {@link
28 * #setState} and {@link #compareAndSetState} is tracked with respect
31 * <p>Subclasses should be defined as non-public internal helper
32 * classes that are used to implement the synchronization properties
33 * of their enclosing class. Class
34 * <tt>AbstractQueuedSynchronizer</tt> does not implement any
35 * synchronization interface. Instead it defines methods such as
36 * {@link #acquireInterruptibly} that can be invoked as
37 * appropriate by concrete locks and related synchronizers to
38 * implement their public methods.
40 * <p>This class supports either or both a default <em>exclusive</em>
41 * mode and a <em>shared</em> mode. When acquired in exclusive mode,
42 * attempted acquires by other threads cannot succeed. Shared mode
43 * acquires by multiple threads may (but need not) succeed. This class
44 * does not "understand" these differences except in the
45 * mechanical sense that when a shared mode acquire succeeds, the next
46 * waiting thread (if one exists) must also determine whether it can
47 * acquire as well. Threads waiting in the different modes share the
48 * same FIFO queue. Usually, implementation subclasses support only
49 * one of these modes, but both can come into play for example in a
50 * {@link ReadWriteLock}. Subclasses that support only exclusive or
51 * only shared modes need not define the methods supporting the unused mode.
53 * <p>This class defines a nested {@link ConditionObject} class that
54 * can be used as a {@link Condition} implementation by subclasses
55 * supporting exclusive mode for which method {@link
56 * #isHeldExclusively} reports whether synchronization is exclusively
57 * held with respect to the current thread, method {@link #release}
58 * invoked with the current {@link #getState} value fully releases
59 * this object, and {@link #acquire}, given this saved state value,
60 * eventually restores this object to its previous acquired state. No
61 * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
62 * condition, so if this constraint cannot be met, do not use it. The
63 * behavior of {@link ConditionObject} depends of course on the
64 * semantics of its synchronizer implementation.
66 * <p>This class provides inspection, instrumentation, and monitoring
67 * methods for the internal queue, as well as similar methods for
68 * condition objects. These can be exported as desired into classes
69 * using an <tt>AbstractQueuedSynchronizer</tt> for their
70 * synchronization mechanics.
72 * <p>Serialization of this class stores only the underlying atomic
73 * integer maintaining state, so deserialized objects have empty
74 * thread queues. Typical subclasses requiring serializability will
75 * define a <tt>readObject</tt> method that restores this to a known
76 * initial state upon deserialization.
80 * <p>To use this class as the basis of a synchronizer, redefine the
81 * following methods, as applicable, by inspecting and/or modifying
82 * the synchronization state using {@link #getState}, {@link
83 * #setState} and/or {@link #compareAndSetState}:
86 * <li> {@link #tryAcquire}
87 * <li> {@link #tryRelease}
88 * <li> {@link #tryAcquireShared}
89 * <li> {@link #tryReleaseShared}
90 * <li> {@link #isHeldExclusively}
93 * Each of these methods by default throws {@link
94 * UnsupportedOperationException}. Implementations of these methods
95 * must be internally thread-safe, and should in general be short and
96 * not block. Defining these methods is the <em>only</em> supported
97 * means of using this class. All other methods are declared
98 * <tt>final</tt> because they cannot be independently varied.
100 * <p>You may also find the inherited methods from {@link
101 * AbstractOwnableSynchronizer} useful to keep track of the thread
102 * owning an exclusive synchronizer. You are encouraged to use them
103 * -- this enables monitoring and diagnostic tools to assist users in
104 * determining which threads hold locks.
106 * <p>Even though this class is based on an internal FIFO queue, it
107 * does not automatically enforce FIFO acquisition policies. The core
108 * of exclusive synchronization takes the form:
112 * while (!tryAcquire(arg)) {
113 * <em>enqueue thread if it is not already queued</em>;
114 * <em>possibly block current thread</em>;
118 * if (tryRelease(arg))
119 * <em>unblock the first queued thread</em>;
122 * (Shared mode is similar but may involve cascading signals.)
124 * <p><a name="barging">Because checks in acquire are invoked before
125 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
126 * others that are blocked and queued. However, you can, if desired,
127 * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to
128 * disable barging by internally invoking one or more of the inspection
129 * methods, thereby providing a <em>fair</em> FIFO acquisition order.
130 * In particular, most fair synchronizers can define <tt>tryAcquire</tt>
131 * to return <tt>false</tt> if {@code hasQueuedPredecessors} (a method
132 * specifically designed to be used by fair synchronizers) returns
133 * <tt>true</tt>. Other variations are possible.
135 * <p>Throughput and scalability are generally highest for the
136 * default barging (also known as <em>greedy</em>,
137 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
138 * While this is not guaranteed to be fair or starvation-free, earlier
139 * queued threads are allowed to recontend before later queued
140 * threads, and each recontention has an unbiased chance to succeed
141 * against incoming threads. Also, while acquires do not
142 * "spin" in the usual sense, they may perform multiple
143 * invocations of <tt>tryAcquire</tt> interspersed with other
144 * computations before blocking. This gives most of the benefits of
145 * spins when exclusive synchronization is only briefly held, without
146 * most of the liabilities when it isn't. If so desired, you can
147 * augment this by preceding calls to acquire methods with
148 * "fast-path" checks, possibly prechecking {@link #hasContended}
149 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
150 * is likely not to be contended.
152 * <p>This class provides an efficient and scalable basis for
153 * synchronization in part by specializing its range of use to
154 * synchronizers that can rely on <tt>int</tt> state, acquire, and
155 * release parameters, and an internal FIFO wait queue. When this does
156 * not suffice, you can build synchronizers from a lower level using
157 * {@link java.util.concurrent.atomic atomic} classes, your own custom
158 * {@link java.util.Queue} classes, and {@link LockSupport} blocking
161 * <h3>Usage Examples</h3>
163 * <p>Here is a non-reentrant mutual exclusion lock class that uses
164 * the value zero to represent the unlocked state, and one to
165 * represent the locked state. While a non-reentrant lock
166 * does not strictly require recording of the current owner
167 * thread, this class does so anyway to make usage easier to monitor.
168 * It also supports conditions and exposes
169 * one of the instrumentation methods:
172 * class Mutex implements Lock, java.io.Serializable {
174 * // Our internal helper class
175 * private static class Sync extends AbstractQueuedSynchronizer {
176 * // Report whether in locked state
177 * protected boolean isHeldExclusively() {
178 * return getState() == 1;
181 * // Acquire the lock if state is zero
182 * public boolean tryAcquire(int acquires) {
183 * assert acquires == 1; // Otherwise unused
184 * if (compareAndSetState(0, 1)) {
185 * setExclusiveOwnerThread(Thread.currentThread());
191 * // Release the lock by setting state to zero
192 * protected boolean tryRelease(int releases) {
193 * assert releases == 1; // Otherwise unused
194 * if (getState() == 0) throw new IllegalMonitorStateException();
195 * setExclusiveOwnerThread(null);
200 * // Provide a Condition
201 * Condition newCondition() { return new ConditionObject(); }
203 * // Deserialize properly
204 * private void readObject(ObjectInputStream s)
205 * throws IOException, ClassNotFoundException {
206 * s.defaultReadObject();
207 * setState(0); // reset to unlocked state
211 * // The sync object does all the hard work. We just forward to it.
212 * private final Sync sync = new Sync();
214 * public void lock() { sync.acquire(1); }
215 * public boolean tryLock() { return sync.tryAcquire(1); }
216 * public void unlock() { sync.release(1); }
217 * public Condition newCondition() { return sync.newCondition(); }
218 * public boolean isLocked() { return sync.isHeldExclusively(); }
219 * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
220 * public void lockInterruptibly() throws InterruptedException {
221 * sync.acquireInterruptibly(1);
223 * public boolean tryLock(long timeout, TimeUnit unit)
224 * throws InterruptedException {
225 * return sync.tryAcquireNanos(1, unit.toNanos(timeout));
230 * <p>Here is a latch class that is like a {@link CountDownLatch}
231 * except that it only requires a single <tt>signal</tt> to
232 * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
233 * acquire and release methods.
236 * class BooleanLatch {
238 * private static class Sync extends AbstractQueuedSynchronizer {
239 * boolean isSignalled() { return getState() != 0; }
241 * protected int tryAcquireShared(int ignore) {
242 * return isSignalled()? 1 : -1;
245 * protected boolean tryReleaseShared(int ignore) {
251 * private final Sync sync = new Sync();
252 * public boolean isSignalled() { return sync.isSignalled(); }
253 * public void signal() { sync.releaseShared(1); }
254 * public void await() throws InterruptedException {
255 * sync.acquireSharedInterruptibly(1);
263 public abstract class AbstractQueuedSynchronizer
264 extends AbstractOwnableSynchronizer
265 implements java.io.Serializable {
267 private static final long serialVersionUID = 7373984972572414691L;
270 * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
271 * with initial synchronization state of zero.
273 protected AbstractQueuedSynchronizer() { }
276 * Wait queue node class.
278 * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
279 * Hagersten) lock queue. CLH locks are normally used for
280 * spinlocks. We instead use them for blocking synchronizers, but
281 * use the same basic tactic of holding some of the control
282 * information about a thread in the predecessor of its node. A
283 * "status" field in each node keeps track of whether a thread
284 * should block. A node is signalled when its predecessor
285 * releases. Each node of the queue otherwise serves as a
286 * specific-notification-style monitor holding a single waiting
287 * thread. The status field does NOT control whether threads are
288 * granted locks etc though. A thread may try to acquire if it is
289 * first in the queue. But being first does not guarantee success;
290 * it only gives the right to contend. So the currently released
291 * contender thread may need to rewait.
293 * <p>To enqueue into a CLH lock, you atomically splice it in as new
294 * tail. To dequeue, you just set the head field.
296 * +------+ prev +-----+ +-----+
297 * head | | <---- | | <---- | | tail
298 * +------+ +-----+ +-----+
301 * <p>Insertion into a CLH queue requires only a single atomic
302 * operation on "tail", so there is a simple atomic point of
303 * demarcation from unqueued to queued. Similarly, dequeing
304 * involves only updating the "head". However, it takes a bit
305 * more work for nodes to determine who their successors are,
306 * in part to deal with possible cancellation due to timeouts
309 * <p>The "prev" links (not used in original CLH locks), are mainly
310 * needed to handle cancellation. If a node is cancelled, its
311 * successor is (normally) relinked to a non-cancelled
312 * predecessor. For explanation of similar mechanics in the case
313 * of spin locks, see the papers by Scott and Scherer at
314 * http://www.cs.rochester.edu/u/scott/synchronization/
316 * <p>We also use "next" links to implement blocking mechanics.
317 * The thread id for each node is kept in its own node, so a
318 * predecessor signals the next node to wake up by traversing
319 * next link to determine which thread it is. Determination of
320 * successor must avoid races with newly queued nodes to set
321 * the "next" fields of their predecessors. This is solved
322 * when necessary by checking backwards from the atomically
323 * updated "tail" when a node's successor appears to be null.
324 * (Or, said differently, the next-links are an optimization
325 * so that we don't usually need a backward scan.)
327 * <p>Cancellation introduces some conservatism to the basic
328 * algorithms. Since we must poll for cancellation of other
329 * nodes, we can miss noticing whether a cancelled node is
330 * ahead or behind us. This is dealt with by always unparking
331 * successors upon cancellation, allowing them to stabilize on
332 * a new predecessor, unless we can identify an uncancelled
333 * predecessor who will carry this responsibility.
335 * <p>CLH queues need a dummy header node to get started. But
336 * we don't create them on construction, because it would be wasted
337 * effort if there is never contention. Instead, the node
338 * is constructed and head and tail pointers are set upon first
341 * <p>Threads waiting on Conditions use the same nodes, but
342 * use an additional link. Conditions only need to link nodes
343 * in simple (non-concurrent) linked queues because they are
344 * only accessed when exclusively held. Upon await, a node is
345 * inserted into a condition queue. Upon signal, the node is
346 * transferred to the main queue. A special value of status
347 * field is used to mark which queue a node is on.
349 * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
350 * Scherer and Michael Scott, along with members of JSR-166
351 * expert group, for helpful ideas, discussions, and critiques
352 * on the design of this class.
354 static final class Node {
355 /** Marker to indicate a node is waiting in shared mode */
356 static final Node SHARED = new Node();
357 /** Marker to indicate a node is waiting in exclusive mode */
358 static final Node EXCLUSIVE = null;
360 /** waitStatus value to indicate thread has cancelled */
361 static final int CANCELLED = 1;
362 /** waitStatus value to indicate successor's thread needs unparking */
363 static final int SIGNAL = -1;
364 /** waitStatus value to indicate thread is waiting on condition */
365 static final int CONDITION = -2;
367 * waitStatus value to indicate the next acquireShared should
368 * unconditionally propagate
370 static final int PROPAGATE = -3;
373 * Status field, taking on only the values:
374 * SIGNAL: The successor of this node is (or will soon be)
375 * blocked (via park), so the current node must
376 * unpark its successor when it releases or
377 * cancels. To avoid races, acquire methods must
378 * first indicate they need a signal,
379 * then retry the atomic acquire, and then,
381 * CANCELLED: This node is cancelled due to timeout or interrupt.
382 * Nodes never leave this state. In particular,
383 * a thread with cancelled node never again blocks.
384 * CONDITION: This node is currently on a condition queue.
385 * It will not be used as a sync queue node
386 * until transferred, at which time the status
387 * will be set to 0. (Use of this value here has
388 * nothing to do with the other uses of the
389 * field, but simplifies mechanics.)
390 * PROPAGATE: A releaseShared should be propagated to other
391 * nodes. This is set (for head node only) in
392 * doReleaseShared to ensure propagation
393 * continues, even if other operations have
395 * 0: None of the above
397 * The values are arranged numerically to simplify use.
398 * Non-negative values mean that a node doesn't need to
399 * signal. So, most code doesn't need to check for particular
400 * values, just for sign.
402 * The field is initialized to 0 for normal sync nodes, and
403 * CONDITION for condition nodes. It is modified using CAS
404 * (or when possible, unconditional volatile writes).
406 volatile int waitStatus;
409 * Link to predecessor node that current node/thread relies on
410 * for checking waitStatus. Assigned during enqueing, and nulled
411 * out (for sake of GC) only upon dequeuing. Also, upon
412 * cancellation of a predecessor, we short-circuit while
413 * finding a non-cancelled one, which will always exist
414 * because the head node is never cancelled: A node becomes
415 * head only as a result of successful acquire. A
416 * cancelled thread never succeeds in acquiring, and a thread only
417 * cancels itself, not any other node.
422 * Link to the successor node that the current node/thread
423 * unparks upon release. Assigned during enqueuing, adjusted
424 * when bypassing cancelled predecessors, and nulled out (for
425 * sake of GC) when dequeued. The enq operation does not
426 * assign next field of a predecessor until after attachment,
427 * so seeing a null next field does not necessarily mean that
428 * node is at end of queue. However, if a next field appears
429 * to be null, we can scan prev's from the tail to
430 * double-check. The next field of cancelled nodes is set to
431 * point to the node itself instead of null, to make life
432 * easier for isOnSyncQueue.
437 * The thread that enqueued this node. Initialized on
438 * construction and nulled out after use.
440 volatile Thread thread;
443 * Link to next node waiting on condition, or the special
444 * value SHARED. Because condition queues are accessed only
445 * when holding in exclusive mode, we just need a simple
446 * linked queue to hold nodes while they are waiting on
447 * conditions. They are then transferred to the queue to
448 * re-acquire. And because conditions can only be exclusive,
449 * we save a field by using special value to indicate shared
455 * Returns true if node is waiting in shared mode
457 final boolean isShared() {
458 return nextWaiter == SHARED;
462 * Returns previous node, or throws NullPointerException if null.
463 * Use when predecessor cannot be null. The null check could
464 * be elided, but is present to help the VM.
466 * @return the predecessor of this node
468 final Node predecessor() throws NullPointerException {
471 throw new NullPointerException();
476 Node() { // Used to establish initial head or SHARED marker
479 Node(Thread thread, Node mode) { // Used by addWaiter
480 this.nextWaiter = mode;
481 this.thread = thread;
484 Node(Thread thread, int waitStatus) { // Used by Condition
485 this.waitStatus = waitStatus;
486 this.thread = thread;
491 * Head of the wait queue, lazily initialized. Except for
492 * initialization, it is modified only via method setHead. Note:
493 * If head exists, its waitStatus is guaranteed not to be
496 private transient volatile Node head;
499 * Tail of the wait queue, lazily initialized. Modified only via
500 * method enq to add new wait node.
502 private transient volatile Node tail;
505 * The synchronization state.
507 private volatile int state;
510 * Returns the current value of synchronization state.
511 * This operation has memory semantics of a <tt>volatile</tt> read.
512 * @return current state value
514 protected final int getState() {
519 * Sets the value of synchronization state.
520 * This operation has memory semantics of a <tt>volatile</tt> write.
521 * @param newState the new state value
523 protected final void setState(int newState) {
528 * Atomically sets synchronization state to the given updated
529 * value if the current state value equals the expected value.
530 * This operation has memory semantics of a <tt>volatile</tt> read
533 * @param expect the expected value
534 * @param update the new value
535 * @return true if successful. False return indicates that the actual
536 * value was not equal to the expected value.
538 protected final boolean compareAndSetState(int expect, int update) {
539 // See below for intrinsics setup to support this
540 return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
546 * The number of nanoseconds for which it is faster to spin
547 * rather than to use timed park. A rough estimate suffices
548 * to improve responsiveness with very short timeouts.
550 static final long spinForTimeoutThreshold = 1000L;
553 * Inserts node into queue, initializing if necessary. See picture above.
554 * @param node the node to insert
555 * @return node's predecessor
557 private Node enq(final Node node) {
560 if (t == null) { // Must initialize
561 if (compareAndSetHead(new Node()))
565 if (compareAndSetTail(t, node)) {
574 * Creates and enqueues node for current thread and given mode.
576 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
577 * @return the new node
579 private Node addWaiter(Node mode) {
580 Node node = new Node(Thread.currentThread(), mode);
581 // Try the fast path of enq; backup to full enq on failure
585 if (compareAndSetTail(pred, node)) {
595 * Sets head of queue to be node, thus dequeuing. Called only by
596 * acquire methods. Also nulls out unused fields for sake of GC
597 * and to suppress unnecessary signals and traversals.
599 * @param node the node
601 private void setHead(Node node) {
608 * Wakes up node's successor, if one exists.
610 * @param node the node
612 private void unparkSuccessor(Node node) {
614 * If status is negative (i.e., possibly needing signal) try
615 * to clear in anticipation of signalling. It is OK if this
616 * fails or if status is changed by waiting thread.
618 int ws = node.waitStatus;
620 compareAndSetWaitStatus(node, ws, 0);
623 * Thread to unpark is held in successor, which is normally
624 * just the next node. But if cancelled or apparently null,
625 * traverse backwards from tail to find the actual
626 * non-cancelled successor.
629 if (s == null || s.waitStatus > 0) {
631 for (Node t = tail; t != null && t != node; t = t.prev)
632 if (t.waitStatus <= 0)
636 LockSupport.unpark(s.thread);
640 * Release action for shared mode -- signal successor and ensure
641 * propagation. (Note: For exclusive mode, release just amounts
642 * to calling unparkSuccessor of head if it needs signal.)
644 private void doReleaseShared() {
646 * Ensure that a release propagates, even if there are other
647 * in-progress acquires/releases. This proceeds in the usual
648 * way of trying to unparkSuccessor of head if it needs
649 * signal. But if it does not, status is set to PROPAGATE to
650 * ensure that upon release, propagation continues.
651 * Additionally, we must loop in case a new node is added
652 * while we are doing this. Also, unlike other uses of
653 * unparkSuccessor, we need to know if CAS to reset status
654 * fails, if so rechecking.
658 if (h != null && h != tail) {
659 int ws = h.waitStatus;
660 if (ws == Node.SIGNAL) {
661 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
662 continue; // loop to recheck cases
666 !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
667 continue; // loop on failed CAS
669 if (h == head) // loop if head changed
675 * Sets head of queue, and checks if successor may be waiting
676 * in shared mode, if so propagating if either propagate > 0 or
677 * PROPAGATE status was set.
679 * @param node the node
680 * @param propagate the return value from a tryAcquireShared
682 private void setHeadAndPropagate(Node node, int propagate) {
683 Node h = head; // Record old head for check below
686 * Try to signal next queued node if:
687 * Propagation was indicated by caller,
688 * or was recorded (as h.waitStatus) by a previous operation
689 * (note: this uses sign-check of waitStatus because
690 * PROPAGATE status may transition to SIGNAL.)
692 * The next node is waiting in shared mode,
693 * or we don't know, because it appears null
695 * The conservatism in both of these checks may cause
696 * unnecessary wake-ups, but only when there are multiple
697 * racing acquires/releases, so most need signals now or soon
700 if (propagate > 0 || h == null || h.waitStatus < 0) {
702 if (s == null || s.isShared())
707 // Utilities for various versions of acquire
710 * Cancels an ongoing attempt to acquire.
712 * @param node the node
714 private void cancelAcquire(Node node) {
715 // Ignore if node doesn't exist
721 // Skip cancelled predecessors
722 Node pred = node.prev;
723 while (pred.waitStatus > 0)
724 node.prev = pred = pred.prev;
726 // predNext is the apparent node to unsplice. CASes below will
727 // fail if not, in which case, we lost race vs another cancel
728 // or signal, so no further action is necessary.
729 Node predNext = pred.next;
731 // Can use unconditional write instead of CAS here.
732 // After this atomic step, other Nodes can skip past us.
733 // Before, we are free of interference from other threads.
734 node.waitStatus = Node.CANCELLED;
736 // If we are the tail, remove ourselves.
737 if (node == tail && compareAndSetTail(node, pred)) {
738 compareAndSetNext(pred, predNext, null);
740 // If successor needs signal, try to set pred's next-link
741 // so it will get one. Otherwise wake it up to propagate.
744 ((ws = pred.waitStatus) == Node.SIGNAL ||
745 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
746 pred.thread != null) {
747 Node next = node.next;
748 if (next != null && next.waitStatus <= 0)
749 compareAndSetNext(pred, predNext, next);
751 unparkSuccessor(node);
754 node.next = node; // help GC
759 * Checks and updates status for a node that failed to acquire.
760 * Returns true if thread should block. This is the main signal
761 * control in all acquire loops. Requires that pred == node.prev
763 * @param pred node's predecessor holding status
764 * @param node the node
765 * @return {@code true} if thread should block
767 private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
768 int ws = pred.waitStatus;
769 if (ws == Node.SIGNAL)
771 * This node has already set status asking a release
772 * to signal it, so it can safely park.
777 * Predecessor was cancelled. Skip over predecessors and
781 node.prev = pred = pred.prev;
782 } while (pred.waitStatus > 0);
786 * waitStatus must be 0 or PROPAGATE. Indicate that we
787 * need a signal, but don't park yet. Caller will need to
788 * retry to make sure it cannot acquire before parking.
790 compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
796 * Convenience method to interrupt current thread.
798 private static void selfInterrupt() {
799 Thread.currentThread().interrupt();
803 * Convenience method to park and then check if interrupted
805 * @return {@code true} if interrupted
807 private final boolean parkAndCheckInterrupt() {
808 LockSupport.park(this);
809 return Thread.interrupted();
813 * Various flavors of acquire, varying in exclusive/shared and
814 * control modes. Each is mostly the same, but annoyingly
815 * different. Only a little bit of factoring is possible due to
816 * interactions of exception mechanics (including ensuring that we
817 * cancel if tryAcquire throws exception) and other control, at
818 * least not without hurting performance too much.
822 * Acquires in exclusive uninterruptible mode for thread already in
823 * queue. Used by condition wait methods as well as acquire.
825 * @param node the node
826 * @param arg the acquire argument
827 * @return {@code true} if interrupted while waiting
829 final boolean acquireQueued(final Node node, int arg) {
830 boolean failed = true;
832 boolean interrupted = false;
834 final Node p = node.predecessor();
835 if (p == head && tryAcquire(arg)) {
837 p.next = null; // help GC
841 if (shouldParkAfterFailedAcquire(p, node) &&
842 parkAndCheckInterrupt())
852 * Acquires in exclusive interruptible mode.
853 * @param arg the acquire argument
855 private void doAcquireInterruptibly(int arg)
856 throws InterruptedException {
857 final Node node = addWaiter(Node.EXCLUSIVE);
858 boolean failed = true;
861 final Node p = node.predecessor();
862 if (p == head && tryAcquire(arg)) {
864 p.next = null; // help GC
868 if (shouldParkAfterFailedAcquire(p, node) &&
869 parkAndCheckInterrupt())
870 throw new InterruptedException();
879 * Acquires in exclusive timed mode.
881 * @param arg the acquire argument
882 * @param nanosTimeout max wait time
883 * @return {@code true} if acquired
885 private boolean doAcquireNanos(int arg, long nanosTimeout)
886 throws InterruptedException {
887 long lastTime = System.nanoTime();
888 final Node node = addWaiter(Node.EXCLUSIVE);
889 boolean failed = true;
892 final Node p = node.predecessor();
893 if (p == head && tryAcquire(arg)) {
895 p.next = null; // help GC
899 if (nanosTimeout <= 0)
901 if (shouldParkAfterFailedAcquire(p, node) &&
902 nanosTimeout > spinForTimeoutThreshold)
903 LockSupport.parkNanos(this, nanosTimeout);
904 long now = System.nanoTime();
905 nanosTimeout -= now - lastTime;
907 if (Thread.interrupted())
908 throw new InterruptedException();
917 * Acquires in shared uninterruptible mode.
918 * @param arg the acquire argument
920 private void doAcquireShared(int arg) {
921 final Node node = addWaiter(Node.SHARED);
922 boolean failed = true;
924 boolean interrupted = false;
926 final Node p = node.predecessor();
928 int r = tryAcquireShared(arg);
930 setHeadAndPropagate(node, r);
931 p.next = null; // help GC
938 if (shouldParkAfterFailedAcquire(p, node) &&
939 parkAndCheckInterrupt())
949 * Acquires in shared interruptible mode.
950 * @param arg the acquire argument
952 private void doAcquireSharedInterruptibly(int arg)
953 throws InterruptedException {
954 final Node node = addWaiter(Node.SHARED);
955 boolean failed = true;
958 final Node p = node.predecessor();
960 int r = tryAcquireShared(arg);
962 setHeadAndPropagate(node, r);
963 p.next = null; // help GC
968 if (shouldParkAfterFailedAcquire(p, node) &&
969 parkAndCheckInterrupt())
970 throw new InterruptedException();
979 * Acquires in shared timed mode.
981 * @param arg the acquire argument
982 * @param nanosTimeout max wait time
983 * @return {@code true} if acquired
985 private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
986 throws InterruptedException {
988 long lastTime = System.nanoTime();
989 final Node node = addWaiter(Node.SHARED);
990 boolean failed = true;
993 final Node p = node.predecessor();
995 int r = tryAcquireShared(arg);
997 setHeadAndPropagate(node, r);
998 p.next = null; // help GC
1003 if (nanosTimeout <= 0)
1005 if (shouldParkAfterFailedAcquire(p, node) &&
1006 nanosTimeout > spinForTimeoutThreshold)
1007 LockSupport.parkNanos(this, nanosTimeout);
1008 long now = System.nanoTime();
1009 nanosTimeout -= now - lastTime;
1011 if (Thread.interrupted())
1012 throw new InterruptedException();
1016 cancelAcquire(node);
1020 // Main exported methods
1023 * Attempts to acquire in exclusive mode. This method should query
1024 * if the state of the object permits it to be acquired in the
1025 * exclusive mode, and if so to acquire it.
1027 * <p>This method is always invoked by the thread performing
1028 * acquire. If this method reports failure, the acquire method
1029 * may queue the thread, if it is not already queued, until it is
1030 * signalled by a release from some other thread. This can be used
1031 * to implement method {@link Lock#tryLock()}.
1034 * implementation throws {@link UnsupportedOperationException}.
1036 * @param arg the acquire argument. This value is always the one
1037 * passed to an acquire method, or is the value saved on entry
1038 * to a condition wait. The value is otherwise uninterpreted
1039 * and can represent anything you like.
1040 * @return {@code true} if successful. Upon success, this object has
1042 * @throws IllegalMonitorStateException if acquiring would place this
1043 * synchronizer in an illegal state. This exception must be
1044 * thrown in a consistent fashion for synchronization to work
1046 * @throws UnsupportedOperationException if exclusive mode is not supported
1048 protected boolean tryAcquire(int arg) {
1049 throw new UnsupportedOperationException();
1053 * Attempts to set the state to reflect a release in exclusive
1056 * <p>This method is always invoked by the thread performing release.
1058 * <p>The default implementation throws
1059 * {@link UnsupportedOperationException}.
1061 * @param arg the release argument. This value is always the one
1062 * passed to a release method, or the current state value upon
1063 * entry to a condition wait. The value is otherwise
1064 * uninterpreted and can represent anything you like.
1065 * @return {@code true} if this object is now in a fully released
1066 * state, so that any waiting threads may attempt to acquire;
1067 * and {@code false} otherwise.
1068 * @throws IllegalMonitorStateException if releasing would place this
1069 * synchronizer in an illegal state. This exception must be
1070 * thrown in a consistent fashion for synchronization to work
1072 * @throws UnsupportedOperationException if exclusive mode is not supported
1074 protected boolean tryRelease(int arg) {
1075 throw new UnsupportedOperationException();
1079 * Attempts to acquire in shared mode. This method should query if
1080 * the state of the object permits it to be acquired in the shared
1081 * mode, and if so to acquire it.
1083 * <p>This method is always invoked by the thread performing
1084 * acquire. If this method reports failure, the acquire method
1085 * may queue the thread, if it is not already queued, until it is
1086 * signalled by a release from some other thread.
1088 * <p>The default implementation throws {@link
1089 * UnsupportedOperationException}.
1091 * @param arg the acquire argument. This value is always the one
1092 * passed to an acquire method, or is the value saved on entry
1093 * to a condition wait. The value is otherwise uninterpreted
1094 * and can represent anything you like.
1095 * @return a negative value on failure; zero if acquisition in shared
1096 * mode succeeded but no subsequent shared-mode acquire can
1097 * succeed; and a positive value if acquisition in shared
1098 * mode succeeded and subsequent shared-mode acquires might
1099 * also succeed, in which case a subsequent waiting thread
1100 * must check availability. (Support for three different
1101 * return values enables this method to be used in contexts
1102 * where acquires only sometimes act exclusively.) Upon
1103 * success, this object has been acquired.
1104 * @throws IllegalMonitorStateException if acquiring would place this
1105 * synchronizer in an illegal state. This exception must be
1106 * thrown in a consistent fashion for synchronization to work
1108 * @throws UnsupportedOperationException if shared mode is not supported
1110 protected int tryAcquireShared(int arg) {
1111 throw new UnsupportedOperationException();
1115 * Attempts to set the state to reflect a release in shared mode.
1117 * <p>This method is always invoked by the thread performing release.
1119 * <p>The default implementation throws
1120 * {@link UnsupportedOperationException}.
1122 * @param arg the release argument. This value is always the one
1123 * passed to a release method, or the current state value upon
1124 * entry to a condition wait. The value is otherwise
1125 * uninterpreted and can represent anything you like.
1126 * @return {@code true} if this release of shared mode may permit a
1127 * waiting acquire (shared or exclusive) to succeed; and
1128 * {@code false} otherwise
1129 * @throws IllegalMonitorStateException if releasing would place this
1130 * synchronizer in an illegal state. This exception must be
1131 * thrown in a consistent fashion for synchronization to work
1133 * @throws UnsupportedOperationException if shared mode is not supported
1135 protected boolean tryReleaseShared(int arg) {
1136 throw new UnsupportedOperationException();
1140 * Returns {@code true} if synchronization is held exclusively with
1141 * respect to the current (calling) thread. This method is invoked
1142 * upon each call to a non-waiting {@link ConditionObject} method.
1143 * (Waiting methods instead invoke {@link #release}.)
1145 * <p>The default implementation throws {@link
1146 * UnsupportedOperationException}. This method is invoked
1147 * internally only within {@link ConditionObject} methods, so need
1148 * not be defined if conditions are not used.
1150 * @return {@code true} if synchronization is held exclusively;
1151 * {@code false} otherwise
1152 * @throws UnsupportedOperationException if conditions are not supported
1154 protected boolean isHeldExclusively() {
1155 throw new UnsupportedOperationException();
1159 * Acquires in exclusive mode, ignoring interrupts. Implemented
1160 * by invoking at least once {@link #tryAcquire},
1161 * returning on success. Otherwise the thread is queued, possibly
1162 * repeatedly blocking and unblocking, invoking {@link
1163 * #tryAcquire} until success. This method can be used
1164 * to implement method {@link Lock#lock}.
1166 * @param arg the acquire argument. This value is conveyed to
1167 * {@link #tryAcquire} but is otherwise uninterpreted and
1168 * can represent anything you like.
1170 public final void acquire(int arg) {
1171 if (!tryAcquire(arg) &&
1172 acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
1177 * Acquires in exclusive mode, aborting if interrupted.
1178 * Implemented by first checking interrupt status, then invoking
1179 * at least once {@link #tryAcquire}, returning on
1180 * success. Otherwise the thread is queued, possibly repeatedly
1181 * blocking and unblocking, invoking {@link #tryAcquire}
1182 * until success or the thread is interrupted. This method can be
1183 * used to implement method {@link Lock#lockInterruptibly}.
1185 * @param arg the acquire argument. This value is conveyed to
1186 * {@link #tryAcquire} but is otherwise uninterpreted and
1187 * can represent anything you like.
1188 * @throws InterruptedException if the current thread is interrupted
1190 public final void acquireInterruptibly(int arg) throws InterruptedException {
1191 if (Thread.interrupted())
1192 throw new InterruptedException();
1193 if (!tryAcquire(arg))
1194 doAcquireInterruptibly(arg);
1198 * Attempts to acquire in exclusive mode, aborting if interrupted,
1199 * and failing if the given timeout elapses. Implemented by first
1200 * checking interrupt status, then invoking at least once {@link
1201 * #tryAcquire}, returning on success. Otherwise, the thread is
1202 * queued, possibly repeatedly blocking and unblocking, invoking
1203 * {@link #tryAcquire} until success or the thread is interrupted
1204 * or the timeout elapses. This method can be used to implement
1205 * method {@link Lock#tryLock(long, TimeUnit)}.
1207 * @param arg the acquire argument. This value is conveyed to
1208 * {@link #tryAcquire} but is otherwise uninterpreted and
1209 * can represent anything you like.
1210 * @param nanosTimeout the maximum number of nanoseconds to wait
1211 * @return {@code true} if acquired; {@code false} if timed out
1212 * @throws InterruptedException if the current thread is interrupted
1214 public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException {
1215 if (Thread.interrupted())
1216 throw new InterruptedException();
1217 return tryAcquire(arg) ||
1218 doAcquireNanos(arg, nanosTimeout);
1222 * Releases in exclusive mode. Implemented by unblocking one or
1223 * more threads if {@link #tryRelease} returns true.
1224 * This method can be used to implement method {@link Lock#unlock}.
1226 * @param arg the release argument. This value is conveyed to
1227 * {@link #tryRelease} but is otherwise uninterpreted and
1228 * can represent anything you like.
1229 * @return the value returned from {@link #tryRelease}
1231 public final boolean release(int arg) {
1232 if (tryRelease(arg)) {
1234 if (h != null && h.waitStatus != 0)
1242 * Acquires in shared mode, ignoring interrupts. Implemented by
1243 * first invoking at least once {@link #tryAcquireShared},
1244 * returning on success. Otherwise the thread is queued, possibly
1245 * repeatedly blocking and unblocking, invoking {@link
1246 * #tryAcquireShared} until success.
1248 * @param arg the acquire argument. This value is conveyed to
1249 * {@link #tryAcquireShared} but is otherwise uninterpreted
1250 * and can represent anything you like.
1252 public final void acquireShared(int arg) {
1253 if (tryAcquireShared(arg) < 0)
1254 doAcquireShared(arg);
1258 * Acquires in shared mode, aborting if interrupted. Implemented
1259 * by first checking interrupt status, then invoking at least once
1260 * {@link #tryAcquireShared}, returning on success. Otherwise the
1261 * thread is queued, possibly repeatedly blocking and unblocking,
1262 * invoking {@link #tryAcquireShared} until success or the thread
1264 * @param arg the acquire argument
1265 * This value is conveyed to {@link #tryAcquireShared} but is
1266 * otherwise uninterpreted and can represent anything
1268 * @throws InterruptedException if the current thread is interrupted
1270 public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
1271 if (Thread.interrupted())
1272 throw new InterruptedException();
1273 if (tryAcquireShared(arg) < 0)
1274 doAcquireSharedInterruptibly(arg);
1278 * Attempts to acquire in shared mode, aborting if interrupted, and
1279 * failing if the given timeout elapses. Implemented by first
1280 * checking interrupt status, then invoking at least once {@link
1281 * #tryAcquireShared}, returning on success. Otherwise, the
1282 * thread is queued, possibly repeatedly blocking and unblocking,
1283 * invoking {@link #tryAcquireShared} until success or the thread
1284 * is interrupted or the timeout elapses.
1286 * @param arg the acquire argument. This value is conveyed to
1287 * {@link #tryAcquireShared} but is otherwise uninterpreted
1288 * and can represent anything you like.
1289 * @param nanosTimeout the maximum number of nanoseconds to wait
1290 * @return {@code true} if acquired; {@code false} if timed out
1291 * @throws InterruptedException if the current thread is interrupted
1293 public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException {
1294 if (Thread.interrupted())
1295 throw new InterruptedException();
1296 return tryAcquireShared(arg) >= 0 ||
1297 doAcquireSharedNanos(arg, nanosTimeout);
1301 * Releases in shared mode. Implemented by unblocking one or more
1302 * threads if {@link #tryReleaseShared} returns true.
1304 * @param arg the release argument. This value is conveyed to
1305 * {@link #tryReleaseShared} but is otherwise uninterpreted
1306 * and can represent anything you like.
1307 * @return the value returned from {@link #tryReleaseShared}
1309 public final boolean releaseShared(int arg) {
1310 if (tryReleaseShared(arg)) {
1317 // Queue inspection methods
1320 * Queries whether any threads are waiting to acquire. Note that
1321 * because cancellations due to interrupts and timeouts may occur
1322 * at any time, a {@code true} return does not guarantee that any
1323 * other thread will ever acquire.
1325 * <p>In this implementation, this operation returns in
1328 * @return {@code true} if there may be other threads waiting to acquire
1330 public final boolean hasQueuedThreads() {
1331 return head != tail;
1335 * Queries whether any threads have ever contended to acquire this
1336 * synchronizer; that is if an acquire method has ever blocked.
1338 * <p>In this implementation, this operation returns in
1341 * @return {@code true} if there has ever been contention
1343 public final boolean hasContended() {
1344 return head != null;
1348 * Returns the first (longest-waiting) thread in the queue, or
1349 * {@code null} if no threads are currently queued.
1351 * <p>In this implementation, this operation normally returns in
1352 * constant time, but may iterate upon contention if other threads are
1353 * concurrently modifying the queue.
1355 * @return the first (longest-waiting) thread in the queue, or
1356 * {@code null} if no threads are currently queued
1358 public final Thread getFirstQueuedThread() {
1359 // handle only fast path, else relay
1360 return (head == tail) ? null : fullGetFirstQueuedThread();
1364 * Version of getFirstQueuedThread called when fastpath fails
1366 private Thread fullGetFirstQueuedThread() {
1368 * The first node is normally head.next. Try to get its
1369 * thread field, ensuring consistent reads: If thread
1370 * field is nulled out or s.prev is no longer head, then
1371 * some other thread(s) concurrently performed setHead in
1372 * between some of our reads. We try this twice before
1373 * resorting to traversal.
1377 if (((h = head) != null && (s = h.next) != null &&
1378 s.prev == head && (st = s.thread) != null) ||
1379 ((h = head) != null && (s = h.next) != null &&
1380 s.prev == head && (st = s.thread) != null))
1384 * Head's next field might not have been set yet, or may have
1385 * been unset after setHead. So we must check to see if tail
1386 * is actually first node. If not, we continue on, safely
1387 * traversing from tail back to head to find first,
1388 * guaranteeing termination.
1392 Thread firstThread = null;
1393 while (t != null && t != head) {
1394 Thread tt = t.thread;
1403 * Returns true if the given thread is currently queued.
1405 * <p>This implementation traverses the queue to determine
1406 * presence of the given thread.
1408 * @param thread the thread
1409 * @return {@code true} if the given thread is on the queue
1410 * @throws NullPointerException if the thread is null
1412 public final boolean isQueued(Thread thread) {
1414 throw new NullPointerException();
1415 for (Node p = tail; p != null; p = p.prev)
1416 if (p.thread == thread)
1422 * Returns {@code true} if the apparent first queued thread, if one
1423 * exists, is waiting in exclusive mode. If this method returns
1424 * {@code true}, and the current thread is attempting to acquire in
1425 * shared mode (that is, this method is invoked from {@link
1426 * #tryAcquireShared}) then it is guaranteed that the current thread
1427 * is not the first queued thread. Used only as a heuristic in
1428 * ReentrantReadWriteLock.
1430 final boolean apparentlyFirstQueuedIsExclusive() {
1432 return (h = head) != null &&
1433 (s = h.next) != null &&
1439 * Queries whether any threads have been waiting to acquire longer
1440 * than the current thread.
1442 * <p>An invocation of this method is equivalent to (but may be
1443 * more efficient than):
1445 * getFirstQueuedThread() != Thread.currentThread() &&
1446 * hasQueuedThreads()}</pre>
1448 * <p>Note that because cancellations due to interrupts and
1449 * timeouts may occur at any time, a {@code true} return does not
1450 * guarantee that some other thread will acquire before the current
1451 * thread. Likewise, it is possible for another thread to win a
1452 * race to enqueue after this method has returned {@code false},
1453 * due to the queue being empty.
1455 * <p>This method is designed to be used by a fair synchronizer to
1456 * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
1457 * Such a synchronizer's {@link #tryAcquire} method should return
1458 * {@code false}, and its {@link #tryAcquireShared} method should
1459 * return a negative value, if this method returns {@code true}
1460 * (unless this is a reentrant acquire). For example, the {@code
1461 * tryAcquire} method for a fair, reentrant, exclusive mode
1462 * synchronizer might look like this:
1465 * protected boolean tryAcquire(int arg) {
1466 * if (isHeldExclusively()) {
1467 * // A reentrant acquire; increment hold count
1469 * } else if (hasQueuedPredecessors()) {
1472 * // try to acquire normally
1476 * @return {@code true} if there is a queued thread preceding the
1477 * current thread, and {@code false} if the current thread
1478 * is at the head of the queue or the queue is empty
1482 public final boolean hasQueuedPredecessors() {
1483 // The correctness of this depends on head being initialized
1484 // before tail and on head.next being accurate if the current
1485 // thread is first in queue.
1486 Node t = tail; // Read fields in reverse initialization order
1490 ((s = h.next) == null || s.thread != Thread.currentThread());
1494 // Instrumentation and monitoring methods
1497 * Returns an estimate of the number of threads waiting to
1498 * acquire. The value is only an estimate because the number of
1499 * threads may change dynamically while this method traverses
1500 * internal data structures. This method is designed for use in
1501 * monitoring system state, not for synchronization
1504 * @return the estimated number of threads waiting to acquire
1506 public final int getQueueLength() {
1508 for (Node p = tail; p != null; p = p.prev) {
1509 if (p.thread != null)
1516 * Returns a collection containing threads that may be waiting to
1517 * acquire. Because the actual set of threads may change
1518 * dynamically while constructing this result, the returned
1519 * collection is only a best-effort estimate. The elements of the
1520 * returned collection are in no particular order. This method is
1521 * designed to facilitate construction of subclasses that provide
1522 * more extensive monitoring facilities.
1524 * @return the collection of threads
1526 public final Collection<Thread> getQueuedThreads() {
1527 ArrayList<Thread> list = new ArrayList<Thread>();
1528 for (Node p = tail; p != null; p = p.prev) {
1529 Thread t = p.thread;
1537 * Returns a collection containing threads that may be waiting to
1538 * acquire in exclusive mode. This has the same properties
1539 * as {@link #getQueuedThreads} except that it only returns
1540 * those threads waiting due to an exclusive acquire.
1542 * @return the collection of threads
1544 public final Collection<Thread> getExclusiveQueuedThreads() {
1545 ArrayList<Thread> list = new ArrayList<Thread>();
1546 for (Node p = tail; p != null; p = p.prev) {
1547 if (!p.isShared()) {
1548 Thread t = p.thread;
1557 * Returns a collection containing threads that may be waiting to
1558 * acquire in shared mode. This has the same properties
1559 * as {@link #getQueuedThreads} except that it only returns
1560 * those threads waiting due to a shared acquire.
1562 * @return the collection of threads
1564 public final Collection<Thread> getSharedQueuedThreads() {
1565 ArrayList<Thread> list = new ArrayList<Thread>();
1566 for (Node p = tail; p != null; p = p.prev) {
1568 Thread t = p.thread;
1577 * Returns a string identifying this synchronizer, as well as its state.
1578 * The state, in brackets, includes the String {@code "State ="}
1579 * followed by the current value of {@link #getState}, and either
1580 * {@code "nonempty"} or {@code "empty"} depending on whether the
1583 * @return a string identifying this synchronizer, as well as its state
1585 public String toString() {
1587 String q = hasQueuedThreads() ? "non" : "";
1588 return super.toString() +
1589 "[State = " + s + ", " + q + "empty queue]";
1593 // Internal support methods for Conditions
1596 * Returns true if a node, always one that was initially placed on
1597 * a condition queue, is now waiting to reacquire on sync queue.
1598 * @param node the node
1599 * @return true if is reacquiring
1601 final boolean isOnSyncQueue(Node node) {
1602 if (node.waitStatus == Node.CONDITION || node.prev == null)
1604 if (node.next != null) // If has successor, it must be on queue
1607 * node.prev can be non-null, but not yet on queue because
1608 * the CAS to place it on queue can fail. So we have to
1609 * traverse from tail to make sure it actually made it. It
1610 * will always be near the tail in calls to this method, and
1611 * unless the CAS failed (which is unlikely), it will be
1612 * there, so we hardly ever traverse much.
1614 return findNodeFromTail(node);
1618 * Returns true if node is on sync queue by searching backwards from tail.
1619 * Called only when needed by isOnSyncQueue.
1620 * @return true if present
1622 private boolean findNodeFromTail(Node node) {
1634 * Transfers a node from a condition queue onto sync queue.
1635 * Returns true if successful.
1636 * @param node the node
1637 * @return true if successfully transferred (else the node was
1638 * cancelled before signal).
1640 final boolean transferForSignal(Node node) {
1642 * If cannot change waitStatus, the node has been cancelled.
1644 if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
1648 * Splice onto queue and try to set waitStatus of predecessor to
1649 * indicate that thread is (probably) waiting. If cancelled or
1650 * attempt to set waitStatus fails, wake up to resync (in which
1651 * case the waitStatus can be transiently and harmlessly wrong).
1654 int ws = p.waitStatus;
1655 if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
1656 LockSupport.unpark(node.thread);
1661 * Transfers node, if necessary, to sync queue after a cancelled
1662 * wait. Returns true if thread was cancelled before being
1664 * @param node its node
1665 * @return true if cancelled before the node was signalled
1667 final boolean transferAfterCancelledWait(Node node) {
1668 if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
1673 * If we lost out to a signal(), then we can't proceed
1674 * until it finishes its enq(). Cancelling during an
1675 * incomplete transfer is both rare and transient, so just
1678 while (!isOnSyncQueue(node))
1684 * Invokes release with current state value; returns saved state.
1685 * Cancels node and throws exception on failure.
1686 * @param node the condition node for this wait
1687 * @return previous sync state
1689 final int fullyRelease(Node node) {
1690 boolean failed = true;
1692 int savedState = getState();
1693 if (release(savedState)) {
1697 throw new IllegalMonitorStateException();
1701 node.waitStatus = Node.CANCELLED;
1705 // Instrumentation methods for conditions
1708 * Queries whether the given ConditionObject
1709 * uses this synchronizer as its lock.
1711 * @param condition the condition
1712 * @return <tt>true</tt> if owned
1713 * @throws NullPointerException if the condition is null
1715 public final boolean owns(ConditionObject condition) {
1716 if (condition == null)
1717 throw new NullPointerException();
1718 return condition.isOwnedBy(this);
1722 * Queries whether any threads are waiting on the given condition
1723 * associated with this synchronizer. Note that because timeouts
1724 * and interrupts may occur at any time, a <tt>true</tt> return
1725 * does not guarantee that a future <tt>signal</tt> will awaken
1726 * any threads. This method is designed primarily for use in
1727 * monitoring of the system state.
1729 * @param condition the condition
1730 * @return <tt>true</tt> if there are any waiting threads
1731 * @throws IllegalMonitorStateException if exclusive synchronization
1733 * @throws IllegalArgumentException if the given condition is
1734 * not associated with this synchronizer
1735 * @throws NullPointerException if the condition is null
1737 public final boolean hasWaiters(ConditionObject condition) {
1738 if (!owns(condition))
1739 throw new IllegalArgumentException("Not owner");
1740 return condition.hasWaiters();
1744 * Returns an estimate of the number of threads waiting on the
1745 * given condition associated with this synchronizer. Note that
1746 * because timeouts and interrupts may occur at any time, the
1747 * estimate serves only as an upper bound on the actual number of
1748 * waiters. This method is designed for use in monitoring of the
1749 * system state, not for synchronization control.
1751 * @param condition the condition
1752 * @return the estimated number of waiting threads
1753 * @throws IllegalMonitorStateException if exclusive synchronization
1755 * @throws IllegalArgumentException if the given condition is
1756 * not associated with this synchronizer
1757 * @throws NullPointerException if the condition is null
1759 public final int getWaitQueueLength(ConditionObject condition) {
1760 if (!owns(condition))
1761 throw new IllegalArgumentException("Not owner");
1762 return condition.getWaitQueueLength();
1766 * Returns a collection containing those threads that may be
1767 * waiting on the given condition associated with this
1768 * synchronizer. Because the actual set of threads may change
1769 * dynamically while constructing this result, the returned
1770 * collection is only a best-effort estimate. The elements of the
1771 * returned collection are in no particular order.
1773 * @param condition the condition
1774 * @return the collection of threads
1775 * @throws IllegalMonitorStateException if exclusive synchronization
1777 * @throws IllegalArgumentException if the given condition is
1778 * not associated with this synchronizer
1779 * @throws NullPointerException if the condition is null
1781 public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
1782 if (!owns(condition))
1783 throw new IllegalArgumentException("Not owner");
1784 return condition.getWaitingThreads();
1788 * Condition implementation for a {@link
1789 * AbstractQueuedSynchronizer} serving as the basis of a {@link
1790 * Lock} implementation.
1792 * <p>Method documentation for this class describes mechanics,
1793 * not behavioral specifications from the point of view of Lock
1794 * and Condition users. Exported versions of this class will in
1795 * general need to be accompanied by documentation describing
1796 * condition semantics that rely on those of the associated
1797 * <tt>AbstractQueuedSynchronizer</tt>.
1799 * <p>This class is Serializable, but all fields are transient,
1800 * so deserialized conditions have no waiters.
1802 public class ConditionObject implements Condition, java.io.Serializable {
1803 private static final long serialVersionUID = 1173984872572414699L;
1804 /** First node of condition queue. */
1805 private transient Node firstWaiter;
1806 /** Last node of condition queue. */
1807 private transient Node lastWaiter;
1810 * Creates a new <tt>ConditionObject</tt> instance.
1812 public ConditionObject() { }
1817 * Adds a new waiter to wait queue.
1818 * @return its new wait node
1820 private Node addConditionWaiter() {
1821 Node t = lastWaiter;
1822 // If lastWaiter is cancelled, clean out.
1823 if (t != null && t.waitStatus != Node.CONDITION) {
1824 unlinkCancelledWaiters();
1827 Node node = new Node(Thread.currentThread(), Node.CONDITION);
1831 t.nextWaiter = node;
1837 * Removes and transfers nodes until hit non-cancelled one or
1838 * null. Split out from signal in part to encourage compilers
1839 * to inline the case of no waiters.
1840 * @param first (non-null) the first node on condition queue
1842 private void doSignal(Node first) {
1844 if ( (firstWaiter = first.nextWaiter) == null)
1846 first.nextWaiter = null;
1847 } while (!transferForSignal(first) &&
1848 (first = firstWaiter) != null);
1852 * Removes and transfers all nodes.
1853 * @param first (non-null) the first node on condition queue
1855 private void doSignalAll(Node first) {
1856 lastWaiter = firstWaiter = null;
1858 Node next = first.nextWaiter;
1859 first.nextWaiter = null;
1860 transferForSignal(first);
1862 } while (first != null);
1866 * Unlinks cancelled waiter nodes from condition queue.
1867 * Called only while holding lock. This is called when
1868 * cancellation occurred during condition wait, and upon
1869 * insertion of a new waiter when lastWaiter is seen to have
1870 * been cancelled. This method is needed to avoid garbage
1871 * retention in the absence of signals. So even though it may
1872 * require a full traversal, it comes into play only when
1873 * timeouts or cancellations occur in the absence of
1874 * signals. It traverses all nodes rather than stopping at a
1875 * particular target to unlink all pointers to garbage nodes
1876 * without requiring many re-traversals during cancellation
1879 private void unlinkCancelledWaiters() {
1880 Node t = firstWaiter;
1883 Node next = t.nextWaiter;
1884 if (t.waitStatus != Node.CONDITION) {
1885 t.nextWaiter = null;
1889 trail.nextWaiter = next;
1902 * Moves the longest-waiting thread, if one exists, from the
1903 * wait queue for this condition to the wait queue for the
1906 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1907 * returns {@code false}
1909 public final void signal() {
1910 if (!isHeldExclusively())
1911 throw new IllegalMonitorStateException();
1912 Node first = firstWaiter;
1918 * Moves all threads from the wait queue for this condition to
1919 * the wait queue for the owning lock.
1921 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1922 * returns {@code false}
1924 public final void signalAll() {
1925 if (!isHeldExclusively())
1926 throw new IllegalMonitorStateException();
1927 Node first = firstWaiter;
1933 * Implements uninterruptible condition wait.
1935 * <li> Save lock state returned by {@link #getState}.
1936 * <li> Invoke {@link #release} with
1937 * saved state as argument, throwing
1938 * IllegalMonitorStateException if it fails.
1939 * <li> Block until signalled.
1940 * <li> Reacquire by invoking specialized version of
1941 * {@link #acquire} with saved state as argument.
1944 public final void awaitUninterruptibly() {
1945 Node node = addConditionWaiter();
1946 int savedState = fullyRelease(node);
1947 boolean interrupted = false;
1948 while (!isOnSyncQueue(node)) {
1949 LockSupport.park(this);
1950 if (Thread.interrupted())
1953 if (acquireQueued(node, savedState) || interrupted)
1958 * For interruptible waits, we need to track whether to throw
1959 * InterruptedException, if interrupted while blocked on
1960 * condition, versus reinterrupt current thread, if
1961 * interrupted while blocked waiting to re-acquire.
1964 /** Mode meaning to reinterrupt on exit from wait */
1965 private static final int REINTERRUPT = 1;
1966 /** Mode meaning to throw InterruptedException on exit from wait */
1967 private static final int THROW_IE = -1;
1970 * Checks for interrupt, returning THROW_IE if interrupted
1971 * before signalled, REINTERRUPT if after signalled, or
1972 * 0 if not interrupted.
1974 private int checkInterruptWhileWaiting(Node node) {
1975 return Thread.interrupted() ?
1976 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
1981 * Throws InterruptedException, reinterrupts current thread, or
1982 * does nothing, depending on mode.
1984 private void reportInterruptAfterWait(int interruptMode)
1985 throws InterruptedException {
1986 if (interruptMode == THROW_IE)
1987 throw new InterruptedException();
1988 else if (interruptMode == REINTERRUPT)
1993 * Implements interruptible condition wait.
1995 * <li> If current thread is interrupted, throw InterruptedException.
1996 * <li> Save lock state returned by {@link #getState}.
1997 * <li> Invoke {@link #release} with
1998 * saved state as argument, throwing
1999 * IllegalMonitorStateException if it fails.
2000 * <li> Block until signalled or interrupted.
2001 * <li> Reacquire by invoking specialized version of
2002 * {@link #acquire} with saved state as argument.
2003 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2006 * @throws InterruptedException if the current thread is interrupted (and
2007 * interruption of thread suspension is supported).
2009 public final void await() throws InterruptedException {
2010 if (Thread.interrupted())
2011 throw new InterruptedException();
2012 Node node = addConditionWaiter();
2013 int savedState = fullyRelease(node);
2014 int interruptMode = 0;
2015 while (!isOnSyncQueue(node)) {
2016 LockSupport.park(this);
2017 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2020 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2021 interruptMode = REINTERRUPT;
2022 if (node.nextWaiter != null) // clean up if cancelled
2023 unlinkCancelledWaiters();
2024 if (interruptMode != 0)
2025 reportInterruptAfterWait(interruptMode);
2029 * Implements timed condition wait.
2031 * <li> If current thread is interrupted, throw InterruptedException.
2032 * <li> Save lock state returned by {@link #getState}.
2033 * <li> Invoke {@link #release} with
2034 * saved state as argument, throwing
2035 * IllegalMonitorStateException if it fails.
2036 * <li> Block until signalled, interrupted, or timed out.
2037 * <li> Reacquire by invoking specialized version of
2038 * {@link #acquire} with saved state as argument.
2039 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2042 * @param nanosTimeout the maximum time to wait, in nanoseconds
2043 * @return A value less than or equal to zero if the wait has
2044 * timed out; otherwise an estimate, that
2045 * is strictly less than the <tt>nanosTimeout</tt> argument,
2046 * of the time still remaining when this method returned.
2048 * @throws InterruptedException if the current thread is interrupted (and
2049 * interruption of thread suspension is supported).
2051 public final long awaitNanos(long nanosTimeout) throws InterruptedException {
2052 if (Thread.interrupted())
2053 throw new InterruptedException();
2054 Node node = addConditionWaiter();
2055 int savedState = fullyRelease(node);
2056 long lastTime = System.nanoTime();
2057 int interruptMode = 0;
2058 while (!isOnSyncQueue(node)) {
2059 if (nanosTimeout <= 0L) {
2060 transferAfterCancelledWait(node);
2063 LockSupport.parkNanos(this, nanosTimeout);
2064 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2067 long now = System.nanoTime();
2068 nanosTimeout -= now - lastTime;
2071 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2072 interruptMode = REINTERRUPT;
2073 if (node.nextWaiter != null)
2074 unlinkCancelledWaiters();
2075 if (interruptMode != 0)
2076 reportInterruptAfterWait(interruptMode);
2077 return nanosTimeout - (System.nanoTime() - lastTime);
2081 * Implements absolute timed condition wait.
2083 * <li> If current thread is interrupted, throw InterruptedException.
2084 * <li> Save lock state returned by {@link #getState}.
2085 * <li> Invoke {@link #release} with
2086 * saved state as argument, throwing
2087 * IllegalMonitorStateException if it fails.
2088 * <li> Block until signalled, interrupted, or timed out.
2089 * <li> Reacquire by invoking specialized version of
2090 * {@link #acquire} with saved state as argument.
2091 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2092 * <li> If timed out while blocked in step 4, return false, else true.
2095 * @param deadline the absolute time to wait until
2096 * @return <tt>false</tt> if the deadline has
2097 * elapsed upon return, else <tt>true</tt>.
2099 * @throws InterruptedException if the current thread is interrupted (and
2100 * interruption of thread suspension is supported).
2102 public final boolean awaitUntil(Date deadline) throws InterruptedException {
2103 if (deadline == null)
2104 throw new NullPointerException();
2105 long abstime = deadline.getTime();
2106 if (Thread.interrupted())
2107 throw new InterruptedException();
2108 Node node = addConditionWaiter();
2109 int savedState = fullyRelease(node);
2110 boolean timedout = false;
2111 int interruptMode = 0;
2112 while (!isOnSyncQueue(node)) {
2113 if (System.currentTimeMillis() > abstime) {
2114 timedout = transferAfterCancelledWait(node);
2117 LockSupport.parkUntil(this, abstime);
2118 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2121 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2122 interruptMode = REINTERRUPT;
2123 if (node.nextWaiter != null)
2124 unlinkCancelledWaiters();
2125 if (interruptMode != 0)
2126 reportInterruptAfterWait(interruptMode);
2131 * Implements timed condition wait.
2133 * <li> If current thread is interrupted, throw InterruptedException.
2134 * <li> Save lock state returned by {@link #getState}.
2135 * <li> Invoke {@link #release} with
2136 * saved state as argument, throwing
2137 * IllegalMonitorStateException if it fails.
2138 * <li> Block until signalled, interrupted, or timed out.
2139 * <li> Reacquire by invoking specialized version of
2140 * {@link #acquire} with saved state as argument.
2141 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2142 * <li> If timed out while blocked in step 4, return false, else true.
2145 * @param time the maximum time to wait
2146 * @param unit the time unit of the <tt>time</tt> argument.
2147 * @return <tt>false</tt> if the waiting time detectably elapsed
2148 * before return from the method, else <tt>true</tt>.
2149 * @throws InterruptedException if the current thread is interrupted (and
2150 * interruption of thread suspension is supported).
2152 public final boolean await(long time, TimeUnit unit) throws InterruptedException {
2154 throw new NullPointerException();
2155 long nanosTimeout = unit.toNanos(time);
2156 if (Thread.interrupted())
2157 throw new InterruptedException();
2158 Node node = addConditionWaiter();
2159 int savedState = fullyRelease(node);
2160 long lastTime = System.nanoTime();
2161 boolean timedout = false;
2162 int interruptMode = 0;
2163 while (!isOnSyncQueue(node)) {
2164 if (nanosTimeout <= 0L) {
2165 timedout = transferAfterCancelledWait(node);
2168 if (nanosTimeout >= spinForTimeoutThreshold)
2169 LockSupport.parkNanos(this, nanosTimeout);
2170 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2172 long now = System.nanoTime();
2173 nanosTimeout -= now - lastTime;
2176 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2177 interruptMode = REINTERRUPT;
2178 if (node.nextWaiter != null)
2179 unlinkCancelledWaiters();
2180 if (interruptMode != 0)
2181 reportInterruptAfterWait(interruptMode);
2185 // support for instrumentation
2188 * Returns true if this condition was created by the given
2189 * synchronization object.
2191 * @return {@code true} if owned
2193 final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
2194 return sync == AbstractQueuedSynchronizer.this;
2198 * Queries whether any threads are waiting on this condition.
2199 * Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
2201 * @return {@code true} if there are any waiting threads
2202 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2203 * returns {@code false}
2205 protected final boolean hasWaiters() {
2206 if (!isHeldExclusively())
2207 throw new IllegalMonitorStateException();
2208 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2209 if (w.waitStatus == Node.CONDITION)
2216 * Returns an estimate of the number of threads waiting on
2218 * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
2220 * @return the estimated number of waiting threads
2221 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2222 * returns {@code false}
2224 protected final int getWaitQueueLength() {
2225 if (!isHeldExclusively())
2226 throw new IllegalMonitorStateException();
2228 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2229 if (w.waitStatus == Node.CONDITION)
2236 * Returns a collection containing those threads that may be
2237 * waiting on this Condition.
2238 * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
2240 * @return the collection of threads
2241 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2242 * returns {@code false}
2244 protected final Collection<Thread> getWaitingThreads() {
2245 if (!isHeldExclusively())
2246 throw new IllegalMonitorStateException();
2247 ArrayList<Thread> list = new ArrayList<Thread>();
2248 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2249 if (w.waitStatus == Node.CONDITION) {
2250 Thread t = w.thread;
2260 * Setup to support compareAndSet. We need to natively implement
2261 * this here: For the sake of permitting future enhancements, we
2262 * cannot explicitly subclass AtomicInteger, which would be
2263 * efficient and useful otherwise. So, as the lesser of evils, we
2264 * natively implement using hotspot intrinsics API. And while we
2265 * are at it, we do the same for other CASable fields (which could
2266 * otherwise be done with atomic field updaters).
2268 // BEGIN android-changed
2269 private static final Unsafe unsafe = UnsafeAccess.THE_ONE;
2270 // END android-changed
2271 private static final long stateOffset;
2272 private static final long headOffset;
2273 private static final long tailOffset;
2274 private static final long waitStatusOffset;
2275 private static final long nextOffset;
2279 stateOffset = unsafe.objectFieldOffset
2280 (AbstractQueuedSynchronizer.class.getDeclaredField("state"));
2281 headOffset = unsafe.objectFieldOffset
2282 (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
2283 tailOffset = unsafe.objectFieldOffset
2284 (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
2285 waitStatusOffset = unsafe.objectFieldOffset
2286 (Node.class.getDeclaredField("waitStatus"));
2287 nextOffset = unsafe.objectFieldOffset
2288 (Node.class.getDeclaredField("next"));
2290 } catch (Exception ex) { throw new Error(ex); }
2294 * CAS head field. Used only by enq.
2296 private final boolean compareAndSetHead(Node update) {
2297 return unsafe.compareAndSwapObject(this, headOffset, null, update);
2301 * CAS tail field. Used only by enq.
2303 private final boolean compareAndSetTail(Node expect, Node update) {
2304 return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
2308 * CAS waitStatus field of a node.
2310 private final static boolean compareAndSetWaitStatus(Node node,
2313 return unsafe.compareAndSwapInt(node, waitStatusOffset,
2318 * CAS next field of a node.
2320 private final static boolean compareAndSetNext(Node node,
2323 return unsafe.compareAndSwapObject(node, nextOffset, expect, update);