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