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