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