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