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