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