rt/emul/compact/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
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
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/
36 package java.util.concurrent.locks;
38 import java.util.concurrent.*;
41 * Provides a framework for implementing blocking locks and related
42 * synchronizers (semaphores, events, etc) that rely on
43 * first-in-first-out (FIFO) wait queues. This class is designed to
44 * be a useful basis for most kinds of synchronizers that rely on a
45 * single atomic <tt>int</tt> value to represent state. Subclasses
46 * must define the protected methods that change this state, and which
47 * define what that state means in terms of this object being acquired
48 * or released. Given these, the other methods in this class carry
49 * out all queuing and blocking mechanics. Subclasses can maintain
50 * other state fields, but only the atomically updated <tt>int</tt>
51 * value manipulated using methods {@link #getState}, {@link
52 * #setState} and {@link #compareAndSetState} is tracked with respect
55 * <p>Subclasses should be defined as non-public internal helper
56 * classes that are used to implement the synchronization properties
57 * of their enclosing class. Class
58 * <tt>AbstractQueuedSynchronizer</tt> does not implement any
59 * synchronization interface. Instead it defines methods such as
60 * {@link #acquireInterruptibly} that can be invoked as
61 * appropriate by concrete locks and related synchronizers to
62 * implement their public methods.
64 * <p>This class supports either or both a default <em>exclusive</em>
65 * mode and a <em>shared</em> mode. When acquired in exclusive mode,
66 * attempted acquires by other threads cannot succeed. Shared mode
67 * acquires by multiple threads may (but need not) succeed. This class
68 * does not "understand" these differences except in the
69 * mechanical sense that when a shared mode acquire succeeds, the next
70 * waiting thread (if one exists) must also determine whether it can
71 * acquire as well. Threads waiting in the different modes share the
72 * same FIFO queue. Usually, implementation subclasses support only
73 * one of these modes, but both can come into play for example in a
74 * {@link ReadWriteLock}. Subclasses that support only exclusive or
75 * only shared modes need not define the methods supporting the unused mode.
77 * <p>This class defines a nested {@link ConditionObject} class that
78 * can be used as a {@link Condition} implementation by subclasses
79 * supporting exclusive mode for which method {@link
80 * #isHeldExclusively} reports whether synchronization is exclusively
81 * held with respect to the current thread, method {@link #release}
82 * invoked with the current {@link #getState} value fully releases
83 * this object, and {@link #acquire}, given this saved state value,
84 * eventually restores this object to its previous acquired state. No
85 * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
86 * condition, so if this constraint cannot be met, do not use it. The
87 * behavior of {@link ConditionObject} depends of course on the
88 * semantics of its synchronizer implementation.
90 * <p>This class provides inspection, instrumentation, and monitoring
91 * methods for the internal queue, as well as similar methods for
92 * condition objects. These can be exported as desired into classes
93 * using an <tt>AbstractQueuedSynchronizer</tt> for their
94 * synchronization mechanics.
96 * <p>Serialization of this class stores only the underlying atomic
97 * integer maintaining state, so deserialized objects have empty
98 * thread queues. Typical subclasses requiring serializability will
99 * define a <tt>readObject</tt> method that restores this to a known
100 * initial state upon deserialization.
104 * <p>To use this class as the basis of a synchronizer, redefine the
105 * following methods, as applicable, by inspecting and/or modifying
106 * the synchronization state using {@link #getState}, {@link
107 * #setState} and/or {@link #compareAndSetState}:
110 * <li> {@link #tryAcquire}
111 * <li> {@link #tryRelease}
112 * <li> {@link #tryAcquireShared}
113 * <li> {@link #tryReleaseShared}
114 * <li> {@link #isHeldExclusively}
117 * Each of these methods by default throws {@link
118 * UnsupportedOperationException}. Implementations of these methods
119 * must be internally thread-safe, and should in general be short and
120 * not block. Defining these methods is the <em>only</em> supported
121 * means of using this class. All other methods are declared
122 * <tt>final</tt> because they cannot be independently varied.
124 * <p>You may also find the inherited methods from {@link
125 * AbstractOwnableSynchronizer} useful to keep track of the thread
126 * owning an exclusive synchronizer. You are encouraged to use them
127 * -- this enables monitoring and diagnostic tools to assist users in
128 * determining which threads hold locks.
130 * <p>Even though this class is based on an internal FIFO queue, it
131 * does not automatically enforce FIFO acquisition policies. The core
132 * of exclusive synchronization takes the form:
136 * while (!tryAcquire(arg)) {
137 * <em>enqueue thread if it is not already queued</em>;
138 * <em>possibly block current thread</em>;
142 * if (tryRelease(arg))
143 * <em>unblock the first queued thread</em>;
146 * (Shared mode is similar but may involve cascading signals.)
148 * <p><a name="barging">Because checks in acquire are invoked before
149 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
150 * others that are blocked and queued. However, you can, if desired,
151 * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to
152 * disable barging by internally invoking one or more of the inspection
153 * methods, thereby providing a <em>fair</em> FIFO acquisition order.
154 * In particular, most fair synchronizers can define <tt>tryAcquire</tt>
155 * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method
156 * specifically designed to be used by fair synchronizers) returns
157 * <tt>true</tt>. Other variations are possible.
159 * <p>Throughput and scalability are generally highest for the
160 * default barging (also known as <em>greedy</em>,
161 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
162 * While this is not guaranteed to be fair or starvation-free, earlier
163 * queued threads are allowed to recontend before later queued
164 * threads, and each recontention has an unbiased chance to succeed
165 * against incoming threads. Also, while acquires do not
166 * "spin" in the usual sense, they may perform multiple
167 * invocations of <tt>tryAcquire</tt> interspersed with other
168 * computations before blocking. This gives most of the benefits of
169 * spins when exclusive synchronization is only briefly held, without
170 * most of the liabilities when it isn't. If so desired, you can
171 * augment this by preceding calls to acquire methods with
172 * "fast-path" checks, possibly prechecking {@link #hasContended}
173 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
174 * is likely not to be contended.
176 * <p>This class provides an efficient and scalable basis for
177 * synchronization in part by specializing its range of use to
178 * synchronizers that can rely on <tt>int</tt> state, acquire, and
179 * release parameters, and an internal FIFO wait queue. When this does
180 * not suffice, you can build synchronizers from a lower level using
181 * {@link java.util.concurrent.atomic atomic} classes, your own custom
182 * {@link java.util.Queue} classes, and {@link LockSupport} blocking
185 * <h3>Usage Examples</h3>
187 * <p>Here is a non-reentrant mutual exclusion lock class that uses
188 * the value zero to represent the unlocked state, and one to
189 * represent the locked state. While a non-reentrant lock
190 * does not strictly require recording of the current owner
191 * thread, this class does so anyway to make usage easier to monitor.
192 * It also supports conditions and exposes
193 * one of the instrumentation methods:
196 * class Mutex implements Lock, java.io.Serializable {
198 * // Our internal helper class
199 * private static class Sync extends AbstractQueuedSynchronizer {
200 * // Report whether in locked state
201 * protected boolean isHeldExclusively() {
202 * return getState() == 1;
205 * // Acquire the lock if state is zero
206 * public boolean tryAcquire(int acquires) {
207 * assert acquires == 1; // Otherwise unused
208 * if (compareAndSetState(0, 1)) {
209 * setExclusiveOwnerThread(Thread.currentThread());
215 * // Release the lock by setting state to zero
216 * protected boolean tryRelease(int releases) {
217 * assert releases == 1; // Otherwise unused
218 * if (getState() == 0) throw new IllegalMonitorStateException();
219 * setExclusiveOwnerThread(null);
224 * // Provide a Condition
225 * Condition newCondition() { return new ConditionObject(); }
227 * // Deserialize properly
228 * private void readObject(ObjectInputStream s)
229 * throws IOException, ClassNotFoundException {
230 * s.defaultReadObject();
231 * setState(0); // reset to unlocked state
235 * // The sync object does all the hard work. We just forward to it.
236 * private final Sync sync = new Sync();
238 * public void lock() { sync.acquire(1); }
239 * public boolean tryLock() { return sync.tryAcquire(1); }
240 * public void unlock() { sync.release(1); }
241 * public Condition newCondition() { return sync.newCondition(); }
242 * public boolean isLocked() { return sync.isHeldExclusively(); }
243 * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
244 * public void lockInterruptibly() throws InterruptedException {
245 * sync.acquireInterruptibly(1);
247 * public boolean tryLock(long timeout, TimeUnit unit)
248 * throws InterruptedException {
249 * return sync.tryAcquireNanos(1, unit.toNanos(timeout));
254 * <p>Here is a latch class that is like a {@link CountDownLatch}
255 * except that it only requires a single <tt>signal</tt> to
256 * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
257 * acquire and release methods.
260 * class BooleanLatch {
262 * private static class Sync extends AbstractQueuedSynchronizer {
263 * boolean isSignalled() { return getState() != 0; }
265 * protected int tryAcquireShared(int ignore) {
266 * return isSignalled() ? 1 : -1;
269 * protected boolean tryReleaseShared(int ignore) {
275 * private final Sync sync = new Sync();
276 * public boolean isSignalled() { return sync.isSignalled(); }
277 * public void signal() { sync.releaseShared(1); }
278 * public void await() throws InterruptedException {
279 * sync.acquireSharedInterruptibly(1);
287 public abstract class AbstractQueuedSynchronizer
288 extends AbstractOwnableSynchronizer
289 implements java.io.Serializable {
291 private static final long serialVersionUID = 7373984972572414691L;
294 * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
295 * with initial synchronization state of zero.
297 protected AbstractQueuedSynchronizer() { }
300 * Wait queue node class.
302 * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
303 * Hagersten) lock queue. CLH locks are normally used for
304 * spinlocks. We instead use them for blocking synchronizers, but
305 * use the same basic tactic of holding some of the control
306 * information about a thread in the predecessor of its node. A
307 * "status" field in each node keeps track of whether a thread
308 * should block. A node is signalled when its predecessor
309 * releases. Each node of the queue otherwise serves as a
310 * specific-notification-style monitor holding a single waiting
311 * thread. The status field does NOT control whether threads are
312 * granted locks etc though. A thread may try to acquire if it is
313 * first in the queue. But being first does not guarantee success;
314 * it only gives the right to contend. So the currently released
315 * contender thread may need to rewait.
317 * <p>To enqueue into a CLH lock, you atomically splice it in as new
318 * tail. To dequeue, you just set the head field.
320 * +------+ prev +-----+ +-----+
321 * head | | <---- | | <---- | | tail
322 * +------+ +-----+ +-----+
325 * <p>Insertion into a CLH queue requires only a single atomic
326 * operation on "tail", so there is a simple atomic point of
327 * demarcation from unqueued to queued. Similarly, dequeing
328 * involves only updating the "head". However, it takes a bit
329 * more work for nodes to determine who their successors are,
330 * in part to deal with possible cancellation due to timeouts
333 * <p>The "prev" links (not used in original CLH locks), are mainly
334 * needed to handle cancellation. If a node is cancelled, its
335 * successor is (normally) relinked to a non-cancelled
336 * predecessor. For explanation of similar mechanics in the case
337 * of spin locks, see the papers by Scott and Scherer at
338 * http://www.cs.rochester.edu/u/scott/synchronization/
340 * <p>We also use "next" links to implement blocking mechanics.
341 * The thread id for each node is kept in its own node, so a
342 * predecessor signals the next node to wake up by traversing
343 * next link to determine which thread it is. Determination of
344 * successor must avoid races with newly queued nodes to set
345 * the "next" fields of their predecessors. This is solved
346 * when necessary by checking backwards from the atomically
347 * updated "tail" when a node's successor appears to be null.
348 * (Or, said differently, the next-links are an optimization
349 * so that we don't usually need a backward scan.)
351 * <p>Cancellation introduces some conservatism to the basic
352 * algorithms. Since we must poll for cancellation of other
353 * nodes, we can miss noticing whether a cancelled node is
354 * ahead or behind us. This is dealt with by always unparking
355 * successors upon cancellation, allowing them to stabilize on
356 * a new predecessor, unless we can identify an uncancelled
357 * predecessor who will carry this responsibility.
359 * <p>CLH queues need a dummy header node to get started. But
360 * we don't create them on construction, because it would be wasted
361 * effort if there is never contention. Instead, the node
362 * is constructed and head and tail pointers are set upon first
365 * <p>Threads waiting on Conditions use the same nodes, but
366 * use an additional link. Conditions only need to link nodes
367 * in simple (non-concurrent) linked queues because they are
368 * only accessed when exclusively held. Upon await, a node is
369 * inserted into a condition queue. Upon signal, the node is
370 * transferred to the main queue. A special value of status
371 * field is used to mark which queue a node is on.
373 * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
374 * Scherer and Michael Scott, along with members of JSR-166
375 * expert group, for helpful ideas, discussions, and critiques
376 * on the design of this class.
378 static final class Node {
379 /** Marker to indicate a node is waiting in shared mode */
380 static final Node SHARED = new Node();
381 /** Marker to indicate a node is waiting in exclusive mode */
382 static final Node EXCLUSIVE = null;
384 /** waitStatus value to indicate thread has cancelled */
385 static final int CANCELLED = 1;
386 /** waitStatus value to indicate successor's thread needs unparking */
387 static final int SIGNAL = -1;
388 /** waitStatus value to indicate thread is waiting on condition */
389 static final int CONDITION = -2;
391 * waitStatus value to indicate the next acquireShared should
392 * unconditionally propagate
394 static final int PROPAGATE = -3;
397 * Status field, taking on only the values:
398 * SIGNAL: The successor of this node is (or will soon be)
399 * blocked (via park), so the current node must
400 * unpark its successor when it releases or
401 * cancels. To avoid races, acquire methods must
402 * first indicate they need a signal,
403 * then retry the atomic acquire, and then,
405 * CANCELLED: This node is cancelled due to timeout or interrupt.
406 * Nodes never leave this state. In particular,
407 * a thread with cancelled node never again blocks.
408 * CONDITION: This node is currently on a condition queue.
409 * It will not be used as a sync queue node
410 * until transferred, at which time the status
411 * will be set to 0. (Use of this value here has
412 * nothing to do with the other uses of the
413 * field, but simplifies mechanics.)
414 * PROPAGATE: A releaseShared should be propagated to other
415 * nodes. This is set (for head node only) in
416 * doReleaseShared to ensure propagation
417 * continues, even if other operations have
419 * 0: None of the above
421 * The values are arranged numerically to simplify use.
422 * Non-negative values mean that a node doesn't need to
423 * signal. So, most code doesn't need to check for particular
424 * values, just for sign.
426 * The field is initialized to 0 for normal sync nodes, and
427 * CONDITION for condition nodes. It is modified using CAS
428 * (or when possible, unconditional volatile writes).
430 volatile int waitStatus;
433 * Link to predecessor node that current node/thread relies on
434 * for checking waitStatus. Assigned during enqueing, and nulled
435 * out (for sake of GC) only upon dequeuing. Also, upon
436 * cancellation of a predecessor, we short-circuit while
437 * finding a non-cancelled one, which will always exist
438 * because the head node is never cancelled: A node becomes
439 * head only as a result of successful acquire. A
440 * cancelled thread never succeeds in acquiring, and a thread only
441 * cancels itself, not any other node.
446 * Link to the successor node that the current node/thread
447 * unparks upon release. Assigned during enqueuing, adjusted
448 * when bypassing cancelled predecessors, and nulled out (for
449 * sake of GC) when dequeued. The enq operation does not
450 * assign next field of a predecessor until after attachment,
451 * so seeing a null next field does not necessarily mean that
452 * node is at end of queue. However, if a next field appears
453 * to be null, we can scan prev's from the tail to
454 * double-check. The next field of cancelled nodes is set to
455 * point to the node itself instead of null, to make life
456 * easier for isOnSyncQueue.
461 * The thread that enqueued this node. Initialized on
462 * construction and nulled out after use.
464 volatile Thread thread;
467 * Link to next node waiting on condition, or the special
468 * value SHARED. Because condition queues are accessed only
469 * when holding in exclusive mode, we just need a simple
470 * linked queue to hold nodes while they are waiting on
471 * conditions. They are then transferred to the queue to
472 * re-acquire. And because conditions can only be exclusive,
473 * we save a field by using special value to indicate shared
479 * Returns true if node is waiting in shared mode
481 final boolean isShared() {
482 return nextWaiter == SHARED;
486 * Returns previous node, or throws NullPointerException if null.
487 * Use when predecessor cannot be null. The null check could
488 * be elided, but is present to help the VM.
490 * @return the predecessor of this node
492 final Node predecessor() throws NullPointerException {
495 throw new NullPointerException();
500 Node() { // Used to establish initial head or SHARED marker
503 Node(Thread thread, Node mode) { // Used by addWaiter
504 this.nextWaiter = mode;
505 this.thread = thread;
508 Node(Thread thread, int waitStatus) { // Used by Condition
509 this.waitStatus = waitStatus;
510 this.thread = thread;
515 * Head of the wait queue, lazily initialized. Except for
516 * initialization, it is modified only via method setHead. Note:
517 * If head exists, its waitStatus is guaranteed not to be
520 private transient volatile Node head;
523 * Tail of the wait queue, lazily initialized. Modified only via
524 * method enq to add new wait node.
526 private transient volatile Node tail;
529 * The synchronization state.
531 private volatile int state;
534 * Returns the current value of synchronization state.
535 * This operation has memory semantics of a <tt>volatile</tt> read.
536 * @return current state value
538 protected final int getState() {
543 * Sets the value of synchronization state.
544 * This operation has memory semantics of a <tt>volatile</tt> write.
545 * @param newState the new state value
547 protected final void setState(int newState) {
552 * Atomically sets synchronization state to the given updated
553 * value if the current state value equals the expected value.
554 * This operation has memory semantics of a <tt>volatile</tt> read
557 * @param expect the expected value
558 * @param update the new value
559 * @return true if successful. False return indicates that the actual
560 * value was not equal to the expected value.
562 protected final boolean compareAndSetState(int expect, int update) {
563 // See below for intrinsics setup to support this
564 if (this.state == expect) {
574 * The number of nanoseconds for which it is faster to spin
575 * rather than to use timed park. A rough estimate suffices
576 * to improve responsiveness with very short timeouts.
578 static final long spinForTimeoutThreshold = 1000L;
581 * Inserts node into queue, initializing if necessary. See picture above.
582 * @param node the node to insert
583 * @return node's predecessor
585 private Node enq(final Node node) {
588 if (t == null) { // Must initialize
589 if (compareAndSetHead(new Node()))
593 if (compareAndSetTail(t, node)) {
602 * Creates and enqueues node for current thread and given mode.
604 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
605 * @return the new node
607 private Node addWaiter(Node mode) {
608 Node node = new Node(Thread.currentThread(), mode);
609 // Try the fast path of enq; backup to full enq on failure
613 if (compareAndSetTail(pred, node)) {
623 * Sets head of queue to be node, thus dequeuing. Called only by
624 * acquire methods. Also nulls out unused fields for sake of GC
625 * and to suppress unnecessary signals and traversals.
627 * @param node the node
629 private void setHead(Node node) {
636 * Wakes up node's successor, if one exists.
638 * @param node the node
640 private void unparkSuccessor(Node node) {
642 * If status is negative (i.e., possibly needing signal) try
643 * to clear in anticipation of signalling. It is OK if this
644 * fails or if status is changed by waiting thread.
646 int ws = node.waitStatus;
648 compareAndSetWaitStatus(node, ws, 0);
651 * Thread to unpark is held in successor, which is normally
652 * just the next node. But if cancelled or apparently null,
653 * traverse backwards from tail to find the actual
654 * non-cancelled successor.
657 if (s == null || s.waitStatus > 0) {
659 for (Node t = tail; t != null && t != node; t = t.prev)
660 if (t.waitStatus <= 0)
664 LockSupport.unpark(s.thread);
668 * Release action for shared mode -- signal successor and ensure
669 * propagation. (Note: For exclusive mode, release just amounts
670 * to calling unparkSuccessor of head if it needs signal.)
672 private void doReleaseShared() {
674 * Ensure that a release propagates, even if there are other
675 * in-progress acquires/releases. This proceeds in the usual
676 * way of trying to unparkSuccessor of head if it needs
677 * signal. But if it does not, status is set to PROPAGATE to
678 * ensure that upon release, propagation continues.
679 * Additionally, we must loop in case a new node is added
680 * while we are doing this. Also, unlike other uses of
681 * unparkSuccessor, we need to know if CAS to reset status
682 * fails, if so rechecking.
686 if (h != null && h != tail) {
687 int ws = h.waitStatus;
688 if (ws == Node.SIGNAL) {
689 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
690 continue; // loop to recheck cases
694 !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
695 continue; // loop on failed CAS
697 if (h == head) // loop if head changed
703 * Sets head of queue, and checks if successor may be waiting
704 * in shared mode, if so propagating if either propagate > 0 or
705 * PROPAGATE status was set.
707 * @param node the node
708 * @param propagate the return value from a tryAcquireShared
710 private void setHeadAndPropagate(Node node, int propagate) {
711 Node h = head; // Record old head for check below
714 * Try to signal next queued node if:
715 * Propagation was indicated by caller,
716 * or was recorded (as h.waitStatus) by a previous operation
717 * (note: this uses sign-check of waitStatus because
718 * PROPAGATE status may transition to SIGNAL.)
720 * The next node is waiting in shared mode,
721 * or we don't know, because it appears null
723 * The conservatism in both of these checks may cause
724 * unnecessary wake-ups, but only when there are multiple
725 * racing acquires/releases, so most need signals now or soon
728 if (propagate > 0 || h == null || h.waitStatus < 0) {
730 if (s == null || s.isShared())
735 // Utilities for various versions of acquire
738 * Cancels an ongoing attempt to acquire.
740 * @param node the node
742 private void cancelAcquire(Node node) {
743 // Ignore if node doesn't exist
749 // Skip cancelled predecessors
750 Node pred = node.prev;
751 while (pred.waitStatus > 0)
752 node.prev = pred = pred.prev;
754 // predNext is the apparent node to unsplice. CASes below will
755 // fail if not, in which case, we lost race vs another cancel
756 // or signal, so no further action is necessary.
757 Node predNext = pred.next;
759 // Can use unconditional write instead of CAS here.
760 // After this atomic step, other Nodes can skip past us.
761 // Before, we are free of interference from other threads.
762 node.waitStatus = Node.CANCELLED;
764 // If we are the tail, remove ourselves.
765 if (node == tail && compareAndSetTail(node, pred)) {
766 compareAndSetNext(pred, predNext, null);
768 // If successor needs signal, try to set pred's next-link
769 // so it will get one. Otherwise wake it up to propagate.
772 ((ws = pred.waitStatus) == Node.SIGNAL ||
773 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
774 pred.thread != null) {
775 Node next = node.next;
776 if (next != null && next.waitStatus <= 0)
777 compareAndSetNext(pred, predNext, next);
779 unparkSuccessor(node);
782 node.next = node; // help GC
787 * Checks and updates status for a node that failed to acquire.
788 * Returns true if thread should block. This is the main signal
789 * control in all acquire loops. Requires that pred == node.prev
791 * @param pred node's predecessor holding status
792 * @param node the node
793 * @return {@code true} if thread should block
795 private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
796 int ws = pred.waitStatus;
797 if (ws == Node.SIGNAL)
799 * This node has already set status asking a release
800 * to signal it, so it can safely park.
805 * Predecessor was cancelled. Skip over predecessors and
809 node.prev = pred = pred.prev;
810 } while (pred.waitStatus > 0);
814 * waitStatus must be 0 or PROPAGATE. Indicate that we
815 * need a signal, but don't park yet. Caller will need to
816 * retry to make sure it cannot acquire before parking.
818 compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
824 * Convenience method to interrupt current thread.
826 private static void selfInterrupt() {
827 Thread.currentThread().interrupt();
831 * Convenience method to park and then check if interrupted
833 * @return {@code true} if interrupted
835 private final boolean parkAndCheckInterrupt() {
836 LockSupport.park(this);
837 return Thread.interrupted();
841 * Various flavors of acquire, varying in exclusive/shared and
842 * control modes. Each is mostly the same, but annoyingly
843 * different. Only a little bit of factoring is possible due to
844 * interactions of exception mechanics (including ensuring that we
845 * cancel if tryAcquire throws exception) and other control, at
846 * least not without hurting performance too much.
850 * Acquires in exclusive uninterruptible mode for thread already in
851 * queue. Used by condition wait methods as well as acquire.
853 * @param node the node
854 * @param arg the acquire argument
855 * @return {@code true} if interrupted while waiting
857 final boolean acquireQueued(final Node node, int arg) {
858 boolean failed = true;
860 boolean interrupted = false;
862 final Node p = node.predecessor();
863 if (p == head && tryAcquire(arg)) {
865 p.next = null; // help GC
869 if (shouldParkAfterFailedAcquire(p, node) &&
870 parkAndCheckInterrupt())
880 * Acquires in exclusive interruptible mode.
881 * @param arg the acquire argument
883 private void doAcquireInterruptibly(int arg)
884 throws InterruptedException {
885 final Node node = addWaiter(Node.EXCLUSIVE);
886 boolean failed = true;
889 final Node p = node.predecessor();
890 if (p == head && tryAcquire(arg)) {
892 p.next = null; // help GC
896 if (shouldParkAfterFailedAcquire(p, node) &&
897 parkAndCheckInterrupt())
898 throw new InterruptedException();
907 * Acquires in exclusive timed mode.
909 * @param arg the acquire argument
910 * @param nanosTimeout max wait time
911 * @return {@code true} if acquired
913 private boolean doAcquireNanos(int arg, long nanosTimeout)
914 throws InterruptedException {
915 long lastTime = System.nanoTime();
916 final Node node = addWaiter(Node.EXCLUSIVE);
917 boolean failed = true;
920 final Node p = node.predecessor();
921 if (p == head && tryAcquire(arg)) {
923 p.next = null; // help GC
927 if (nanosTimeout <= 0)
929 if (shouldParkAfterFailedAcquire(p, node) &&
930 nanosTimeout > spinForTimeoutThreshold)
931 LockSupport.parkNanos(this, nanosTimeout);
932 long now = System.nanoTime();
933 nanosTimeout -= now - lastTime;
935 if (Thread.interrupted())
936 throw new InterruptedException();
945 * Acquires in shared uninterruptible mode.
946 * @param arg the acquire argument
948 private void doAcquireShared(int arg) {
949 final Node node = addWaiter(Node.SHARED);
950 boolean failed = true;
952 boolean interrupted = false;
954 final Node p = node.predecessor();
956 int r = tryAcquireShared(arg);
958 setHeadAndPropagate(node, r);
959 p.next = null; // help GC
966 if (shouldParkAfterFailedAcquire(p, node) &&
967 parkAndCheckInterrupt())
977 * Acquires in shared interruptible mode.
978 * @param arg the acquire argument
980 private void doAcquireSharedInterruptibly(int arg)
981 throws InterruptedException {
982 final Node node = addWaiter(Node.SHARED);
983 boolean failed = true;
986 final Node p = node.predecessor();
988 int r = tryAcquireShared(arg);
990 setHeadAndPropagate(node, r);
991 p.next = null; // help GC
996 if (shouldParkAfterFailedAcquire(p, node) &&
997 parkAndCheckInterrupt())
998 throw new InterruptedException();
1002 cancelAcquire(node);
1007 * Acquires in shared timed mode.
1009 * @param arg the acquire argument
1010 * @param nanosTimeout max wait time
1011 * @return {@code true} if acquired
1013 private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
1014 throws InterruptedException {
1016 long lastTime = System.nanoTime();
1017 final Node node = addWaiter(Node.SHARED);
1018 boolean failed = true;
1021 final Node p = node.predecessor();
1023 int r = tryAcquireShared(arg);
1025 setHeadAndPropagate(node, r);
1026 p.next = null; // help GC
1031 if (nanosTimeout <= 0)
1033 if (shouldParkAfterFailedAcquire(p, node) &&
1034 nanosTimeout > spinForTimeoutThreshold)
1035 LockSupport.parkNanos(this, nanosTimeout);
1036 long now = System.nanoTime();
1037 nanosTimeout -= now - lastTime;
1039 if (Thread.interrupted())
1040 throw new InterruptedException();
1044 cancelAcquire(node);
1048 // Main exported methods
1051 * Attempts to acquire in exclusive mode. This method should query
1052 * if the state of the object permits it to be acquired in the
1053 * exclusive mode, and if so to acquire it.
1055 * <p>This method is always invoked by the thread performing
1056 * acquire. If this method reports failure, the acquire method
1057 * may queue the thread, if it is not already queued, until it is
1058 * signalled by a release from some other thread. This can be used
1059 * to implement method {@link Lock#tryLock()}.
1062 * implementation throws {@link UnsupportedOperationException}.
1064 * @param arg the acquire argument. This value is always the one
1065 * passed to an acquire method, or is the value saved on entry
1066 * to a condition wait. The value is otherwise uninterpreted
1067 * and can represent anything you like.
1068 * @return {@code true} if successful. Upon success, this object has
1070 * @throws IllegalMonitorStateException if acquiring would place this
1071 * synchronizer in an illegal state. This exception must be
1072 * thrown in a consistent fashion for synchronization to work
1074 * @throws UnsupportedOperationException if exclusive mode is not supported
1076 protected boolean tryAcquire(int arg) {
1077 throw new UnsupportedOperationException();
1081 * Attempts to set the state to reflect a release in exclusive
1084 * <p>This method is always invoked by the thread performing release.
1086 * <p>The default implementation throws
1087 * {@link UnsupportedOperationException}.
1089 * @param arg the release argument. This value is always the one
1090 * passed to a release method, or the current state value upon
1091 * entry to a condition wait. The value is otherwise
1092 * uninterpreted and can represent anything you like.
1093 * @return {@code true} if this object is now in a fully released
1094 * state, so that any waiting threads may attempt to acquire;
1095 * and {@code false} otherwise.
1096 * @throws IllegalMonitorStateException if releasing would place this
1097 * synchronizer in an illegal state. This exception must be
1098 * thrown in a consistent fashion for synchronization to work
1100 * @throws UnsupportedOperationException if exclusive mode is not supported
1102 protected boolean tryRelease(int arg) {
1103 throw new UnsupportedOperationException();
1107 * Attempts to acquire in shared mode. This method should query if
1108 * the state of the object permits it to be acquired in the shared
1109 * mode, and if so to acquire it.
1111 * <p>This method is always invoked by the thread performing
1112 * acquire. If this method reports failure, the acquire method
1113 * may queue the thread, if it is not already queued, until it is
1114 * signalled by a release from some other thread.
1116 * <p>The default implementation throws {@link
1117 * UnsupportedOperationException}.
1119 * @param arg the acquire argument. This value is always the one
1120 * passed to an acquire method, or is the value saved on entry
1121 * to a condition wait. The value is otherwise uninterpreted
1122 * and can represent anything you like.
1123 * @return a negative value on failure; zero if acquisition in shared
1124 * mode succeeded but no subsequent shared-mode acquire can
1125 * succeed; and a positive value if acquisition in shared
1126 * mode succeeded and subsequent shared-mode acquires might
1127 * also succeed, in which case a subsequent waiting thread
1128 * must check availability. (Support for three different
1129 * return values enables this method to be used in contexts
1130 * where acquires only sometimes act exclusively.) Upon
1131 * success, this object has been acquired.
1132 * @throws IllegalMonitorStateException if acquiring would place this
1133 * synchronizer in an illegal state. This exception must be
1134 * thrown in a consistent fashion for synchronization to work
1136 * @throws UnsupportedOperationException if shared mode is not supported
1138 protected int tryAcquireShared(int arg) {
1139 throw new UnsupportedOperationException();
1143 * Attempts to set the state to reflect a release in shared mode.
1145 * <p>This method is always invoked by the thread performing release.
1147 * <p>The default implementation throws
1148 * {@link UnsupportedOperationException}.
1150 * @param arg the release argument. This value is always the one
1151 * passed to a release method, or the current state value upon
1152 * entry to a condition wait. The value is otherwise
1153 * uninterpreted and can represent anything you like.
1154 * @return {@code true} if this release of shared mode may permit a
1155 * waiting acquire (shared or exclusive) to succeed; and
1156 * {@code false} otherwise
1157 * @throws IllegalMonitorStateException if releasing would place this
1158 * synchronizer in an illegal state. This exception must be
1159 * thrown in a consistent fashion for synchronization to work
1161 * @throws UnsupportedOperationException if shared mode is not supported
1163 protected boolean tryReleaseShared(int arg) {
1164 throw new UnsupportedOperationException();
1168 * Returns {@code true} if synchronization is held exclusively with
1169 * respect to the current (calling) thread. This method is invoked
1170 * upon each call to a non-waiting {@link ConditionObject} method.
1171 * (Waiting methods instead invoke {@link #release}.)
1173 * <p>The default implementation throws {@link
1174 * UnsupportedOperationException}. This method is invoked
1175 * internally only within {@link ConditionObject} methods, so need
1176 * not be defined if conditions are not used.
1178 * @return {@code true} if synchronization is held exclusively;
1179 * {@code false} otherwise
1180 * @throws UnsupportedOperationException if conditions are not supported
1182 protected boolean isHeldExclusively() {
1183 throw new UnsupportedOperationException();
1187 * Acquires in exclusive mode, ignoring interrupts. Implemented
1188 * by invoking at least once {@link #tryAcquire},
1189 * returning on success. Otherwise the thread is queued, possibly
1190 * repeatedly blocking and unblocking, invoking {@link
1191 * #tryAcquire} until success. This method can be used
1192 * to implement method {@link Lock#lock}.
1194 * @param arg the acquire argument. This value is conveyed to
1195 * {@link #tryAcquire} but is otherwise uninterpreted and
1196 * can represent anything you like.
1198 public final void acquire(int arg) {
1199 if (!tryAcquire(arg) &&
1200 acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
1205 * Acquires in exclusive mode, aborting if interrupted.
1206 * Implemented by first checking interrupt status, then invoking
1207 * at least once {@link #tryAcquire}, returning on
1208 * success. Otherwise the thread is queued, possibly repeatedly
1209 * blocking and unblocking, invoking {@link #tryAcquire}
1210 * until success or the thread is interrupted. This method can be
1211 * used to implement method {@link Lock#lockInterruptibly}.
1213 * @param arg the acquire argument. This value is conveyed to
1214 * {@link #tryAcquire} but is otherwise uninterpreted and
1215 * can represent anything you like.
1216 * @throws InterruptedException if the current thread is interrupted
1218 public final void acquireInterruptibly(int arg)
1219 throws InterruptedException {
1220 if (Thread.interrupted())
1221 throw new InterruptedException();
1222 if (!tryAcquire(arg))
1223 doAcquireInterruptibly(arg);
1227 * Attempts to acquire in exclusive mode, aborting if interrupted,
1228 * and failing if the given timeout elapses. Implemented by first
1229 * checking interrupt status, then invoking at least once {@link
1230 * #tryAcquire}, returning on success. Otherwise, the thread is
1231 * queued, possibly repeatedly blocking and unblocking, invoking
1232 * {@link #tryAcquire} until success or the thread is interrupted
1233 * or the timeout elapses. This method can be used to implement
1234 * method {@link Lock#tryLock(long, TimeUnit)}.
1236 * @param arg the acquire argument. This value is conveyed to
1237 * {@link #tryAcquire} but is otherwise uninterpreted and
1238 * can represent anything you like.
1239 * @param nanosTimeout the maximum number of nanoseconds to wait
1240 * @return {@code true} if acquired; {@code false} if timed out
1241 * @throws InterruptedException if the current thread is interrupted
1243 public final boolean tryAcquireNanos(int arg, long nanosTimeout)
1244 throws InterruptedException {
1245 if (Thread.interrupted())
1246 throw new InterruptedException();
1247 return tryAcquire(arg) ||
1248 doAcquireNanos(arg, nanosTimeout);
1252 * Releases in exclusive mode. Implemented by unblocking one or
1253 * more threads if {@link #tryRelease} returns true.
1254 * This method can be used to implement method {@link Lock#unlock}.
1256 * @param arg the release argument. This value is conveyed to
1257 * {@link #tryRelease} but is otherwise uninterpreted and
1258 * can represent anything you like.
1259 * @return the value returned from {@link #tryRelease}
1261 public final boolean release(int arg) {
1262 if (tryRelease(arg)) {
1264 if (h != null && h.waitStatus != 0)
1272 * Acquires in shared mode, ignoring interrupts. Implemented by
1273 * first invoking at least once {@link #tryAcquireShared},
1274 * returning on success. Otherwise the thread is queued, possibly
1275 * repeatedly blocking and unblocking, invoking {@link
1276 * #tryAcquireShared} until success.
1278 * @param arg the acquire argument. This value is conveyed to
1279 * {@link #tryAcquireShared} but is otherwise uninterpreted
1280 * and can represent anything you like.
1282 public final void acquireShared(int arg) {
1283 if (tryAcquireShared(arg) < 0)
1284 doAcquireShared(arg);
1288 * Acquires in shared mode, aborting if interrupted. Implemented
1289 * by first checking interrupt status, then invoking at least once
1290 * {@link #tryAcquireShared}, returning on success. Otherwise the
1291 * thread is queued, possibly repeatedly blocking and unblocking,
1292 * invoking {@link #tryAcquireShared} until success or the thread
1294 * @param arg the acquire argument
1295 * This value is conveyed to {@link #tryAcquireShared} but is
1296 * otherwise uninterpreted and can represent anything
1298 * @throws InterruptedException if the current thread is interrupted
1300 public final void acquireSharedInterruptibly(int arg)
1301 throws InterruptedException {
1302 if (Thread.interrupted())
1303 throw new InterruptedException();
1304 if (tryAcquireShared(arg) < 0)
1305 doAcquireSharedInterruptibly(arg);
1309 * Attempts to acquire in shared mode, aborting if interrupted, and
1310 * failing if the given timeout elapses. Implemented by first
1311 * checking interrupt status, then invoking at least once {@link
1312 * #tryAcquireShared}, returning on success. Otherwise, the
1313 * thread is queued, possibly repeatedly blocking and unblocking,
1314 * invoking {@link #tryAcquireShared} until success or the thread
1315 * is interrupted or the timeout elapses.
1317 * @param arg the acquire argument. This value is conveyed to
1318 * {@link #tryAcquireShared} but is otherwise uninterpreted
1319 * and can represent anything you like.
1320 * @param nanosTimeout the maximum number of nanoseconds to wait
1321 * @return {@code true} if acquired; {@code false} if timed out
1322 * @throws InterruptedException if the current thread is interrupted
1324 public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
1325 throws InterruptedException {
1326 if (Thread.interrupted())
1327 throw new InterruptedException();
1328 return tryAcquireShared(arg) >= 0 ||
1329 doAcquireSharedNanos(arg, nanosTimeout);
1333 * Releases in shared mode. Implemented by unblocking one or more
1334 * threads if {@link #tryReleaseShared} returns true.
1336 * @param arg the release argument. This value is conveyed to
1337 * {@link #tryReleaseShared} but is otherwise uninterpreted
1338 * and can represent anything you like.
1339 * @return the value returned from {@link #tryReleaseShared}
1341 public final boolean releaseShared(int arg) {
1342 if (tryReleaseShared(arg)) {
1349 // Queue inspection methods
1352 * Queries whether any threads are waiting to acquire. Note that
1353 * because cancellations due to interrupts and timeouts may occur
1354 * at any time, a {@code true} return does not guarantee that any
1355 * other thread will ever acquire.
1357 * <p>In this implementation, this operation returns in
1360 * @return {@code true} if there may be other threads waiting to acquire
1362 public final boolean hasQueuedThreads() {
1363 return head != tail;
1367 * Queries whether any threads have ever contended to acquire this
1368 * synchronizer; that is if an acquire method has ever blocked.
1370 * <p>In this implementation, this operation returns in
1373 * @return {@code true} if there has ever been contention
1375 public final boolean hasContended() {
1376 return head != null;
1380 * Returns the first (longest-waiting) thread in the queue, or
1381 * {@code null} if no threads are currently queued.
1383 * <p>In this implementation, this operation normally returns in
1384 * constant time, but may iterate upon contention if other threads are
1385 * concurrently modifying the queue.
1387 * @return the first (longest-waiting) thread in the queue, or
1388 * {@code null} if no threads are currently queued
1390 public final Thread getFirstQueuedThread() {
1391 // handle only fast path, else relay
1392 return (head == tail) ? null : fullGetFirstQueuedThread();
1396 * Version of getFirstQueuedThread called when fastpath fails
1398 private Thread fullGetFirstQueuedThread() {
1400 * The first node is normally head.next. Try to get its
1401 * thread field, ensuring consistent reads: If thread
1402 * field is nulled out or s.prev is no longer head, then
1403 * some other thread(s) concurrently performed setHead in
1404 * between some of our reads. We try this twice before
1405 * resorting to traversal.
1409 if (((h = head) != null && (s = h.next) != null &&
1410 s.prev == head && (st = s.thread) != null) ||
1411 ((h = head) != null && (s = h.next) != null &&
1412 s.prev == head && (st = s.thread) != null))
1416 * Head's next field might not have been set yet, or may have
1417 * been unset after setHead. So we must check to see if tail
1418 * is actually first node. If not, we continue on, safely
1419 * traversing from tail back to head to find first,
1420 * guaranteeing termination.
1424 Thread firstThread = null;
1425 while (t != null && t != head) {
1426 Thread tt = t.thread;
1435 * Returns true if the given thread is currently queued.
1437 * <p>This implementation traverses the queue to determine
1438 * presence of the given thread.
1440 * @param thread the thread
1441 * @return {@code true} if the given thread is on the queue
1442 * @throws NullPointerException if the thread is null
1444 public final boolean isQueued(Thread thread) {
1446 throw new NullPointerException();
1447 for (Node p = tail; p != null; p = p.prev)
1448 if (p.thread == thread)
1454 * Returns {@code true} if the apparent first queued thread, if one
1455 * exists, is waiting in exclusive mode. If this method returns
1456 * {@code true}, and the current thread is attempting to acquire in
1457 * shared mode (that is, this method is invoked from {@link
1458 * #tryAcquireShared}) then it is guaranteed that the current thread
1459 * is not the first queued thread. Used only as a heuristic in
1460 * ReentrantReadWriteLock.
1462 final boolean apparentlyFirstQueuedIsExclusive() {
1464 return (h = head) != null &&
1465 (s = h.next) != null &&
1471 * Queries whether any threads have been waiting to acquire longer
1472 * than the current thread.
1474 * <p>An invocation of this method is equivalent to (but may be
1475 * more efficient than):
1477 * getFirstQueuedThread() != Thread.currentThread() &&
1478 * hasQueuedThreads()}</pre>
1480 * <p>Note that because cancellations due to interrupts and
1481 * timeouts may occur at any time, a {@code true} return does not
1482 * guarantee that some other thread will acquire before the current
1483 * thread. Likewise, it is possible for another thread to win a
1484 * race to enqueue after this method has returned {@code false},
1485 * due to the queue being empty.
1487 * <p>This method is designed to be used by a fair synchronizer to
1488 * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
1489 * Such a synchronizer's {@link #tryAcquire} method should return
1490 * {@code false}, and its {@link #tryAcquireShared} method should
1491 * return a negative value, if this method returns {@code true}
1492 * (unless this is a reentrant acquire). For example, the {@code
1493 * tryAcquire} method for a fair, reentrant, exclusive mode
1494 * synchronizer might look like this:
1497 * protected boolean tryAcquire(int arg) {
1498 * if (isHeldExclusively()) {
1499 * // A reentrant acquire; increment hold count
1501 * } else if (hasQueuedPredecessors()) {
1504 * // try to acquire normally
1508 * @return {@code true} if there is a queued thread preceding the
1509 * current thread, and {@code false} if the current thread
1510 * is at the head of the queue or the queue is empty
1513 public final boolean hasQueuedPredecessors() {
1514 // The correctness of this depends on head being initialized
1515 // before tail and on head.next being accurate if the current
1516 // thread is first in queue.
1517 Node t = tail; // Read fields in reverse initialization order
1521 ((s = h.next) == null || s.thread != Thread.currentThread());
1525 // Instrumentation and monitoring methods
1528 * Returns an estimate of the number of threads waiting to
1529 * acquire. The value is only an estimate because the number of
1530 * threads may change dynamically while this method traverses
1531 * internal data structures. This method is designed for use in
1532 * monitoring system state, not for synchronization
1535 * @return the estimated number of threads waiting to acquire
1537 public final int getQueueLength() {
1539 for (Node p = tail; p != null; p = p.prev) {
1540 if (p.thread != null)
1547 * Returns a collection containing threads that may be waiting to
1548 * acquire. Because the actual set of threads may change
1549 * dynamically while constructing this result, the returned
1550 * collection is only a best-effort estimate. The elements of the
1551 * returned collection are in no particular order. This method is
1552 * designed to facilitate construction of subclasses that provide
1553 * more extensive monitoring facilities.
1555 * @return the collection of threads
1557 public final Collection<Thread> getQueuedThreads() {
1558 ArrayList<Thread> list = new ArrayList<Thread>();
1559 for (Node p = tail; p != null; p = p.prev) {
1560 Thread t = p.thread;
1568 * Returns a collection containing threads that may be waiting to
1569 * acquire in exclusive mode. This has the same properties
1570 * as {@link #getQueuedThreads} except that it only returns
1571 * those threads waiting due to an exclusive acquire.
1573 * @return the collection of threads
1575 public final Collection<Thread> getExclusiveQueuedThreads() {
1576 ArrayList<Thread> list = new ArrayList<Thread>();
1577 for (Node p = tail; p != null; p = p.prev) {
1578 if (!p.isShared()) {
1579 Thread t = p.thread;
1588 * Returns a collection containing threads that may be waiting to
1589 * acquire in shared mode. This has the same properties
1590 * as {@link #getQueuedThreads} except that it only returns
1591 * those threads waiting due to a shared acquire.
1593 * @return the collection of threads
1595 public final Collection<Thread> getSharedQueuedThreads() {
1596 ArrayList<Thread> list = new ArrayList<Thread>();
1597 for (Node p = tail; p != null; p = p.prev) {
1599 Thread t = p.thread;
1608 * Returns a string identifying this synchronizer, as well as its state.
1609 * The state, in brackets, includes the String {@code "State ="}
1610 * followed by the current value of {@link #getState}, and either
1611 * {@code "nonempty"} or {@code "empty"} depending on whether the
1614 * @return a string identifying this synchronizer, as well as its state
1616 public String toString() {
1618 String q = hasQueuedThreads() ? "non" : "";
1619 return super.toString() +
1620 "[State = " + s + ", " + q + "empty queue]";
1624 // Internal support methods for Conditions
1627 * Returns true if a node, always one that was initially placed on
1628 * a condition queue, is now waiting to reacquire on sync queue.
1629 * @param node the node
1630 * @return true if is reacquiring
1632 final boolean isOnSyncQueue(Node node) {
1633 if (node.waitStatus == Node.CONDITION || node.prev == null)
1635 if (node.next != null) // If has successor, it must be on queue
1638 * node.prev can be non-null, but not yet on queue because
1639 * the CAS to place it on queue can fail. So we have to
1640 * traverse from tail to make sure it actually made it. It
1641 * will always be near the tail in calls to this method, and
1642 * unless the CAS failed (which is unlikely), it will be
1643 * there, so we hardly ever traverse much.
1645 return findNodeFromTail(node);
1649 * Returns true if node is on sync queue by searching backwards from tail.
1650 * Called only when needed by isOnSyncQueue.
1651 * @return true if present
1653 private boolean findNodeFromTail(Node node) {
1665 * Transfers a node from a condition queue onto sync queue.
1666 * Returns true if successful.
1667 * @param node the node
1668 * @return true if successfully transferred (else the node was
1669 * cancelled before signal).
1671 final boolean transferForSignal(Node node) {
1673 * If cannot change waitStatus, the node has been cancelled.
1675 if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
1679 * Splice onto queue and try to set waitStatus of predecessor to
1680 * indicate that thread is (probably) waiting. If cancelled or
1681 * attempt to set waitStatus fails, wake up to resync (in which
1682 * case the waitStatus can be transiently and harmlessly wrong).
1685 int ws = p.waitStatus;
1686 if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
1687 LockSupport.unpark(node.thread);
1692 * Transfers node, if necessary, to sync queue after a cancelled
1693 * wait. Returns true if thread was cancelled before being
1695 * @param current the waiting thread
1696 * @param node its node
1697 * @return true if cancelled before the node was signalled
1699 final boolean transferAfterCancelledWait(Node node) {
1700 if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
1705 * If we lost out to a signal(), then we can't proceed
1706 * until it finishes its enq(). Cancelling during an
1707 * incomplete transfer is both rare and transient, so just
1710 while (!isOnSyncQueue(node))
1716 * Invokes release with current state value; returns saved state.
1717 * Cancels node and throws exception on failure.
1718 * @param node the condition node for this wait
1719 * @return previous sync state
1721 final int fullyRelease(Node node) {
1722 boolean failed = true;
1724 int savedState = getState();
1725 if (release(savedState)) {
1729 throw new IllegalMonitorStateException();
1733 node.waitStatus = Node.CANCELLED;
1737 // Instrumentation methods for conditions
1740 * Queries whether the given ConditionObject
1741 * uses this synchronizer as its lock.
1743 * @param condition the condition
1744 * @return <tt>true</tt> if owned
1745 * @throws NullPointerException if the condition is null
1747 public final boolean owns(ConditionObject condition) {
1748 if (condition == null)
1749 throw new NullPointerException();
1750 return condition.isOwnedBy(this);
1754 * Queries whether any threads are waiting on the given condition
1755 * associated with this synchronizer. Note that because timeouts
1756 * and interrupts may occur at any time, a <tt>true</tt> return
1757 * does not guarantee that a future <tt>signal</tt> will awaken
1758 * any threads. This method is designed primarily for use in
1759 * monitoring of the system state.
1761 * @param condition the condition
1762 * @return <tt>true</tt> if there are any waiting threads
1763 * @throws IllegalMonitorStateException if exclusive synchronization
1765 * @throws IllegalArgumentException if the given condition is
1766 * not associated with this synchronizer
1767 * @throws NullPointerException if the condition is null
1769 public final boolean hasWaiters(ConditionObject condition) {
1770 if (!owns(condition))
1771 throw new IllegalArgumentException("Not owner");
1772 return condition.hasWaiters();
1776 * Returns an estimate of the number of threads waiting on the
1777 * given condition associated with this synchronizer. Note that
1778 * because timeouts and interrupts may occur at any time, the
1779 * estimate serves only as an upper bound on the actual number of
1780 * waiters. This method is designed for use in monitoring of the
1781 * system state, not for synchronization control.
1783 * @param condition the condition
1784 * @return the estimated number of waiting threads
1785 * @throws IllegalMonitorStateException if exclusive synchronization
1787 * @throws IllegalArgumentException if the given condition is
1788 * not associated with this synchronizer
1789 * @throws NullPointerException if the condition is null
1791 public final int getWaitQueueLength(ConditionObject condition) {
1792 if (!owns(condition))
1793 throw new IllegalArgumentException("Not owner");
1794 return condition.getWaitQueueLength();
1798 * Returns a collection containing those threads that may be
1799 * waiting on the given condition associated with this
1800 * synchronizer. Because the actual set of threads may change
1801 * dynamically while constructing this result, the returned
1802 * collection is only a best-effort estimate. The elements of the
1803 * returned collection are in no particular order.
1805 * @param condition the condition
1806 * @return the collection of threads
1807 * @throws IllegalMonitorStateException if exclusive synchronization
1809 * @throws IllegalArgumentException if the given condition is
1810 * not associated with this synchronizer
1811 * @throws NullPointerException if the condition is null
1813 public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
1814 if (!owns(condition))
1815 throw new IllegalArgumentException("Not owner");
1816 return condition.getWaitingThreads();
1820 * Condition implementation for a {@link
1821 * AbstractQueuedSynchronizer} serving as the basis of a {@link
1822 * Lock} implementation.
1824 * <p>Method documentation for this class describes mechanics,
1825 * not behavioral specifications from the point of view of Lock
1826 * and Condition users. Exported versions of this class will in
1827 * general need to be accompanied by documentation describing
1828 * condition semantics that rely on those of the associated
1829 * <tt>AbstractQueuedSynchronizer</tt>.
1831 * <p>This class is Serializable, but all fields are transient,
1832 * so deserialized conditions have no waiters.
1834 public class ConditionObject implements Condition, java.io.Serializable {
1835 private static final long serialVersionUID = 1173984872572414699L;
1836 /** First node of condition queue. */
1837 private transient Node firstWaiter;
1838 /** Last node of condition queue. */
1839 private transient Node lastWaiter;
1842 * Creates a new <tt>ConditionObject</tt> instance.
1844 public ConditionObject() { }
1849 * Adds a new waiter to wait queue.
1850 * @return its new wait node
1852 private Node addConditionWaiter() {
1853 Node t = lastWaiter;
1854 // If lastWaiter is cancelled, clean out.
1855 if (t != null && t.waitStatus != Node.CONDITION) {
1856 unlinkCancelledWaiters();
1859 Node node = new Node(Thread.currentThread(), Node.CONDITION);
1863 t.nextWaiter = node;
1869 * Removes and transfers nodes until hit non-cancelled one or
1870 * null. Split out from signal in part to encourage compilers
1871 * to inline the case of no waiters.
1872 * @param first (non-null) the first node on condition queue
1874 private void doSignal(Node first) {
1876 if ( (firstWaiter = first.nextWaiter) == null)
1878 first.nextWaiter = null;
1879 } while (!transferForSignal(first) &&
1880 (first = firstWaiter) != null);
1884 * Removes and transfers all nodes.
1885 * @param first (non-null) the first node on condition queue
1887 private void doSignalAll(Node first) {
1888 lastWaiter = firstWaiter = null;
1890 Node next = first.nextWaiter;
1891 first.nextWaiter = null;
1892 transferForSignal(first);
1894 } while (first != null);
1898 * Unlinks cancelled waiter nodes from condition queue.
1899 * Called only while holding lock. This is called when
1900 * cancellation occurred during condition wait, and upon
1901 * insertion of a new waiter when lastWaiter is seen to have
1902 * been cancelled. This method is needed to avoid garbage
1903 * retention in the absence of signals. So even though it may
1904 * require a full traversal, it comes into play only when
1905 * timeouts or cancellations occur in the absence of
1906 * signals. It traverses all nodes rather than stopping at a
1907 * particular target to unlink all pointers to garbage nodes
1908 * without requiring many re-traversals during cancellation
1911 private void unlinkCancelledWaiters() {
1912 Node t = firstWaiter;
1915 Node next = t.nextWaiter;
1916 if (t.waitStatus != Node.CONDITION) {
1917 t.nextWaiter = null;
1921 trail.nextWaiter = next;
1934 * Moves the longest-waiting thread, if one exists, from the
1935 * wait queue for this condition to the wait queue for the
1938 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1939 * returns {@code false}
1941 public final void signal() {
1942 if (!isHeldExclusively())
1943 throw new IllegalMonitorStateException();
1944 Node first = firstWaiter;
1950 * Moves all threads from the wait queue for this condition to
1951 * the wait queue for the owning lock.
1953 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1954 * returns {@code false}
1956 public final void signalAll() {
1957 if (!isHeldExclusively())
1958 throw new IllegalMonitorStateException();
1959 Node first = firstWaiter;
1965 * Implements uninterruptible condition wait.
1967 * <li> Save lock state returned by {@link #getState}.
1968 * <li> Invoke {@link #release} with
1969 * saved state as argument, throwing
1970 * IllegalMonitorStateException if it fails.
1971 * <li> Block until signalled.
1972 * <li> Reacquire by invoking specialized version of
1973 * {@link #acquire} with saved state as argument.
1976 public final void awaitUninterruptibly() {
1977 Node node = addConditionWaiter();
1978 int savedState = fullyRelease(node);
1979 boolean interrupted = false;
1980 while (!isOnSyncQueue(node)) {
1981 LockSupport.park(this);
1982 if (Thread.interrupted())
1985 if (acquireQueued(node, savedState) || interrupted)
1990 * For interruptible waits, we need to track whether to throw
1991 * InterruptedException, if interrupted while blocked on
1992 * condition, versus reinterrupt current thread, if
1993 * interrupted while blocked waiting to re-acquire.
1996 /** Mode meaning to reinterrupt on exit from wait */
1997 private static final int REINTERRUPT = 1;
1998 /** Mode meaning to throw InterruptedException on exit from wait */
1999 private static final int THROW_IE = -1;
2002 * Checks for interrupt, returning THROW_IE if interrupted
2003 * before signalled, REINTERRUPT if after signalled, or
2004 * 0 if not interrupted.
2006 private int checkInterruptWhileWaiting(Node node) {
2007 return Thread.interrupted() ?
2008 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
2013 * Throws InterruptedException, reinterrupts current thread, or
2014 * does nothing, depending on mode.
2016 private void reportInterruptAfterWait(int interruptMode)
2017 throws InterruptedException {
2018 if (interruptMode == THROW_IE)
2019 throw new InterruptedException();
2020 else if (interruptMode == REINTERRUPT)
2025 * Implements interruptible condition wait.
2027 * <li> If current thread is interrupted, throw InterruptedException.
2028 * <li> Save lock state returned by {@link #getState}.
2029 * <li> Invoke {@link #release} with
2030 * saved state as argument, throwing
2031 * IllegalMonitorStateException if it fails.
2032 * <li> Block until signalled or interrupted.
2033 * <li> Reacquire by invoking specialized version of
2034 * {@link #acquire} with saved state as argument.
2035 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2038 public final void await() throws InterruptedException {
2039 if (Thread.interrupted())
2040 throw new InterruptedException();
2041 Node node = addConditionWaiter();
2042 int savedState = fullyRelease(node);
2043 int interruptMode = 0;
2044 while (!isOnSyncQueue(node)) {
2045 LockSupport.park(this);
2046 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2049 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2050 interruptMode = REINTERRUPT;
2051 if (node.nextWaiter != null) // clean up if cancelled
2052 unlinkCancelledWaiters();
2053 if (interruptMode != 0)
2054 reportInterruptAfterWait(interruptMode);
2058 * Implements timed condition wait.
2060 * <li> If current thread is interrupted, throw InterruptedException.
2061 * <li> Save lock state returned by {@link #getState}.
2062 * <li> Invoke {@link #release} with
2063 * saved state as argument, throwing
2064 * IllegalMonitorStateException if it fails.
2065 * <li> Block until signalled, interrupted, or timed out.
2066 * <li> Reacquire by invoking specialized version of
2067 * {@link #acquire} with saved state as argument.
2068 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2071 public final long awaitNanos(long nanosTimeout)
2072 throws InterruptedException {
2073 if (Thread.interrupted())
2074 throw new InterruptedException();
2075 Node node = addConditionWaiter();
2076 int savedState = fullyRelease(node);
2077 long lastTime = System.nanoTime();
2078 int interruptMode = 0;
2079 while (!isOnSyncQueue(node)) {
2080 if (nanosTimeout <= 0L) {
2081 transferAfterCancelledWait(node);
2084 LockSupport.parkNanos(this, nanosTimeout);
2085 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2088 long now = System.nanoTime();
2089 nanosTimeout -= now - lastTime;
2092 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2093 interruptMode = REINTERRUPT;
2094 if (node.nextWaiter != null)
2095 unlinkCancelledWaiters();
2096 if (interruptMode != 0)
2097 reportInterruptAfterWait(interruptMode);
2098 return nanosTimeout - (System.nanoTime() - lastTime);
2102 * Implements absolute timed condition wait.
2104 * <li> If current thread is interrupted, throw InterruptedException.
2105 * <li> Save lock state returned by {@link #getState}.
2106 * <li> Invoke {@link #release} with
2107 * saved state as argument, throwing
2108 * IllegalMonitorStateException if it fails.
2109 * <li> Block until signalled, interrupted, or timed out.
2110 * <li> Reacquire by invoking specialized version of
2111 * {@link #acquire} with saved state as argument.
2112 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2113 * <li> If timed out while blocked in step 4, return false, else true.
2116 public final boolean awaitUntil(Date deadline)
2117 throws InterruptedException {
2118 if (deadline == null)
2119 throw new NullPointerException();
2120 long abstime = deadline.getTime();
2121 if (Thread.interrupted())
2122 throw new InterruptedException();
2123 Node node = addConditionWaiter();
2124 int savedState = fullyRelease(node);
2125 boolean timedout = false;
2126 int interruptMode = 0;
2127 while (!isOnSyncQueue(node)) {
2128 if (System.currentTimeMillis() > abstime) {
2129 timedout = transferAfterCancelledWait(node);
2132 LockSupport.parkUntil(this, abstime);
2133 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2136 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2137 interruptMode = REINTERRUPT;
2138 if (node.nextWaiter != null)
2139 unlinkCancelledWaiters();
2140 if (interruptMode != 0)
2141 reportInterruptAfterWait(interruptMode);
2146 * Implements timed condition wait.
2148 * <li> If current thread is interrupted, throw InterruptedException.
2149 * <li> Save lock state returned by {@link #getState}.
2150 * <li> Invoke {@link #release} with
2151 * saved state as argument, throwing
2152 * IllegalMonitorStateException if it fails.
2153 * <li> Block until signalled, interrupted, or timed out.
2154 * <li> Reacquire by invoking specialized version of
2155 * {@link #acquire} with saved state as argument.
2156 * <li> If interrupted while blocked in step 4, throw InterruptedException.
2157 * <li> If timed out while blocked in step 4, return false, else true.
2160 public final boolean await(long time, TimeUnit unit)
2161 throws InterruptedException {
2163 throw new NullPointerException();
2164 long nanosTimeout = unit.toNanos(time);
2165 if (Thread.interrupted())
2166 throw new InterruptedException();
2167 Node node = addConditionWaiter();
2168 int savedState = fullyRelease(node);
2169 long lastTime = System.nanoTime();
2170 boolean timedout = false;
2171 int interruptMode = 0;
2172 while (!isOnSyncQueue(node)) {
2173 if (nanosTimeout <= 0L) {
2174 timedout = transferAfterCancelledWait(node);
2177 if (nanosTimeout >= spinForTimeoutThreshold)
2178 LockSupport.parkNanos(this, nanosTimeout);
2179 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2181 long now = System.nanoTime();
2182 nanosTimeout -= now - lastTime;
2185 if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2186 interruptMode = REINTERRUPT;
2187 if (node.nextWaiter != null)
2188 unlinkCancelledWaiters();
2189 if (interruptMode != 0)
2190 reportInterruptAfterWait(interruptMode);
2194 // support for instrumentation
2197 * Returns true if this condition was created by the given
2198 * synchronization object.
2200 * @return {@code true} if owned
2202 final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
2203 return sync == AbstractQueuedSynchronizer.this;
2207 * Queries whether any threads are waiting on this condition.
2208 * Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
2210 * @return {@code true} if there are any waiting threads
2211 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2212 * returns {@code false}
2214 protected final boolean hasWaiters() {
2215 if (!isHeldExclusively())
2216 throw new IllegalMonitorStateException();
2217 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2218 if (w.waitStatus == Node.CONDITION)
2225 * Returns an estimate of the number of threads waiting on
2227 * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
2229 * @return the estimated number of waiting threads
2230 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2231 * returns {@code false}
2233 protected final int getWaitQueueLength() {
2234 if (!isHeldExclusively())
2235 throw new IllegalMonitorStateException();
2237 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2238 if (w.waitStatus == Node.CONDITION)
2245 * Returns a collection containing those threads that may be
2246 * waiting on this Condition.
2247 * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
2249 * @return the collection of threads
2250 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2251 * returns {@code false}
2253 protected final Collection<Thread> getWaitingThreads() {
2254 if (!isHeldExclusively())
2255 throw new IllegalMonitorStateException();
2256 ArrayList<Thread> list = new ArrayList<Thread>();
2257 for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2258 if (w.waitStatus == Node.CONDITION) {
2259 Thread t = w.thread;
2269 * Setup to support compareAndSet. We need to natively implement
2270 * this here: For the sake of permitting future enhancements, we
2271 * cannot explicitly subclass AtomicInteger, which would be
2272 * efficient and useful otherwise. So, as the lesser of evils, we
2273 * natively implement using hotspot intrinsics API. And while we
2274 * are at it, we do the same for other CASable fields (which could
2275 * otherwise be done with atomic field updaters).
2280 * CAS head field. Used only by enq.
2282 private final boolean compareAndSetHead(Node update) {
2291 * CAS tail field. Used only by enq.
2293 private final boolean compareAndSetTail(Node expect, Node update) {
2302 * CAS waitStatus field of a node.
2304 private static final boolean compareAndSetWaitStatus(Node node,
2307 if (node.waitStatus == expect) {
2308 node.waitStatus = update;
2315 * CAS next field of a node.
2317 private static final boolean compareAndSetNext(Node node,
2320 if (node.next == expect) {