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