ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
Revision: 1.17
Committed: Thu Nov 19 01:08:34 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.16: +2 -2 lines
Log Message:
use spinForTimeoutThreshold consistently

File Contents

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