KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > locks > AbstractQueuedSynchronizer


1 /*
2  * @(#)AbstractQueuedSynchronizer.java 1.4 07/01/04
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util.concurrent.locks;
9 import java.util.*;
10 import java.util.concurrent.*;
11 import java.util.concurrent.atomic.*;
12 import sun.misc.Unsafe;
13
14 /**
15  * Provides a framework for implementing blocking locks and related
16  * synchronizers (semaphores, events, etc) that rely on
17  * first-in-first-out (FIFO) wait queues. This class is designed to
18  * be a useful basis for most kinds of synchronizers that rely on a
19  * single atomic <tt>int</tt> value to represent state. Subclasses
20  * must define the protected methods that change this state, and which
21  * define what that state means in terms of this object being acquired
22  * or released. Given these, the other methods in this class carry
23  * out all queuing and blocking mechanics. Subclasses can maintain
24  * other state fields, but only the atomically updated <tt>int</tt>
25  * value manipulated using methods {@link #getState}, {@link
26  * #setState} and {@link #compareAndSetState} is tracked with respect
27  * to synchronization.
28  *
29  * <p>Subclasses should be defined as non-public internal helper
30  * classes that are used to implement the synchronization properties
31  * of their enclosing class. Class
32  * <tt>AbstractQueuedSynchronizer</tt> does not implement any
33  * synchronization interface. Instead it defines methods such as
34  * {@link #acquireInterruptibly} that can be invoked as
35  * appropriate by concrete locks and related synchronizers to
36  * implement their public methods.
37  *
38  * <p>This class supports either or both a default <em>exclusive</em>
39  * mode and a <em>shared</em> mode. When acquired in exclusive mode,
40  * attempted acquires by other threads cannot succeed. Shared mode
41  * acquires by multiple threads may (but need not) succeed. This class
42  * does not &quot;understand&quot; these differences except in the
43  * mechanical sense that when a shared mode acquire succeeds, the next
44  * waiting thread (if one exists) must also determine whether it can
45  * acquire as well. Threads waiting in the different modes share the
46  * same FIFO queue. Usually, implementation subclasses support only
47  * one of these modes, but both can come into play for example in a
48  * {@link ReadWriteLock}. Subclasses that support only exclusive or
49  * only shared modes need not define the methods supporting the unused mode.
50  *
51  * <p>This class defines a nested {@link ConditionObject} class that
52  * can be used as a {@link Condition} implementation by subclasses
53  * supporting exclusive mode for which method {@link
54  * #isHeldExclusively} reports whether synchronization is exclusively
55  * held with respect to the current thread, method {@link #release}
56  * invoked with the current {@link #getState} value fully releases
57  * this object, and {@link #acquire}, given this saved state value,
58  * eventually restores this object to its previous acquired state. No
59  * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
60  * condition, so if this constraint cannot be met, do not use it. The
61  * behavior of {@link ConditionObject} depends of course on the
62  * semantics of its synchronizer implementation.
63  *
64  * <p> This class provides inspection, instrumentation, and monitoring
65  * methods for the internal queue, as well as similar methods for
66  * condition objects. These can be exported as desired into classes
67  * using an <tt>AbstractQueuedSynchronizer</tt> for their
68  * synchronization mechanics.
69  *
70  * <p> Serialization of this class stores only the underlying atomic
71  * integer maintaining state, so deserialized objects have empty
72  * thread queues. Typical subclasses requiring serializability will
73  * define a <tt>readObject</tt> method that restores this to a known
74  * initial state upon deserialization.
75  *
76  * <h3>Usage</h3>
77  *
78  * <p> To use this class as the basis of a synchronizer, redefine the
79  * following methods, as applicable, by inspecting and/or modifying
80  * the synchronization state using {@link #getState}, {@link
81  * #setState} and/or {@link #compareAndSetState}:
82  *
83  * <ul>
84  * <li> {@link #tryAcquire}
85  * <li> {@link #tryRelease}
86  * <li> {@link #tryAcquireShared}
87  * <li> {@link #tryReleaseShared}
88  * <li> {@link #isHeldExclusively}
89  *</ul>
90  *
91  * Each of these methods by default throws {@link
92  * UnsupportedOperationException}. Implementations of these methods
93  * must be internally thread-safe, and should in general be short and
94  * not block. Defining these methods is the <em>only</em> supported
95  * means of using this class. All other methods are declared
96  * <tt>final</tt> because they cannot be independently varied.
97  *
98  * <p> Even though this class is based on an internal FIFO queue, it
99  * does not automatically enforce FIFO acquisition policies. The core
100  * of exclusive synchronization takes the form:
101  *
102  * <pre>
103  * Acquire:
104  * while (!tryAcquire(arg)) {
105  * <em>enqueue thread if it is not already queued</em>;
106  * <em>possibly block current thread</em>;
107  * }
108  *
109  * Release:
110  * if (tryRelease(arg))
111  * <em>unblock the first queued thread</em>;
112  * </pre>
113  *
114  * (Shared mode is similar but may involve cascading signals.)
115  *
116  * <p> Because checks in acquire are invoked before enqueuing, a newly
117  * acquiring thread may <em>barge</em> ahead of others that are
118  * blocked and queued. However, you can, if desired, define
119  * <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to disable
120  * barging by internally invoking one or more of the inspection
121  * methods. In particular, a strict FIFO lock can define
122  * <tt>tryAcquire</tt> to immediately return <tt>false</tt> if {@link
123  * #getFirstQueuedThread} does not return the current thread. A
124  * normally preferable non-strict fair version can immediately return
125  * <tt>false</tt> only if {@link #hasQueuedThreads} returns
126  * <tt>true</tt> and <tt>getFirstQueuedThread</tt> is not the current
127  * thread; or equivalently, that <tt>getFirstQueuedThread</tt> is both
128  * non-null and not the current thread. Further variations are
129  * possible.
130  *
131  * <p> Throughput and scalability are generally highest for the
132  * default barging (also known as <em>greedy</em>,
133  * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
134  * While this is not guaranteed to be fair or starvation-free, earlier
135  * queued threads are allowed to recontend before later queued
136  * threads, and each recontention has an unbiased chance to succeed
137  * against incoming threads. Also, while acquires do not
138  * &quot;spin&quot; in the usual sense, they may perform multiple
139  * invocations of <tt>tryAcquire</tt> interspersed with other
140  * computations before blocking. This gives most of the benefits of
141  * spins when exclusive synchronization is only briefly held, without
142  * most of the liabilities when it isn't. If so desired, you can
143  * augment this by preceding calls to acquire methods with
144  * "fast-path" checks, possibly prechecking {@link #hasContended}
145  * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
146  * is likely not to be contended.
147  *
148  * <p> This class provides an efficient and scalable basis for
149  * synchronization in part by specializing its range of use to
150  * synchronizers that can rely on <tt>int</tt> state, acquire, and
151  * release parameters, and an internal FIFO wait queue. When this does
152  * not suffice, you can build synchronizers from a lower level using
153  * {@link java.util.concurrent.atomic atomic} classes, your own custom
154  * {@link java.util.Queue} classes, and {@link LockSupport} blocking
155  * support.
156  *
157  * <h3>Usage Examples</h3>
158  *
159  * <p>Here is a non-reentrant mutual exclusion lock class that uses
160  * the value zero to represent the unlocked state, and one to
161  * represent the locked state. It also supports conditions and exposes
162  * one of the instrumentation methods:
163  *
164  * <pre>
165  * class Mutex implements Lock, java.io.Serializable {
166  *
167  * // Our internal helper class
168  * private static class Sync extends AbstractQueuedSynchronizer {
169  * // Report whether in locked state
170  * protected boolean isHeldExclusively() {
171  * return getState() == 1;
172  * }
173  *
174  * // Acquire the lock if state is zero
175  * public boolean tryAcquire(int acquires) {
176  * assert acquires == 1; // Otherwise unused
177  * return compareAndSetState(0, 1);
178  * }
179  *
180  * // Release the lock by setting state to zero
181  * protected boolean tryRelease(int releases) {
182  * assert releases == 1; // Otherwise unused
183  * if (getState() == 0) throw new IllegalMonitorStateException();
184  * setState(0);
185  * return true;
186  * }
187  *
188  * // Provide a Condition
189  * Condition newCondition() { return new ConditionObject(); }
190  *
191  * // Deserialize properly
192  * private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
193  * s.defaultReadObject();
194  * setState(0); // reset to unlocked state
195  * }
196  * }
197  *
198  * // The sync object does all the hard work. We just forward to it.
199  * private final Sync sync = new Sync();
200  *
201  * public void lock() { sync.acquire(1); }
202  * public boolean tryLock() { return sync.tryAcquire(1); }
203  * public void unlock() { sync.release(1); }
204  * public Condition newCondition() { return sync.newCondition(); }
205  * public boolean isLocked() { return sync.isHeldExclusively(); }
206  * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
207  * public void lockInterruptibly() throws InterruptedException {
208  * sync.acquireInterruptibly(1);
209  * }
210  * public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
211  * return sync.tryAcquireNanos(1, unit.toNanos(timeout));
212  * }
213  * }
214  * </pre>
215  *
216  * <p> Here is a latch class that is like a {@link CountDownLatch}
217  * except that it only requires a single <tt>signal</tt> to
218  * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
219  * acquire and release methods.
220  *
221  * <pre>
222  * class BooleanLatch {
223  *
224  * private static class Sync extends AbstractQueuedSynchronizer {
225  * boolean isSignalled() { return getState() != 0; }
226  *
227  * protected int tryAcquireShared(int ignore) {
228  * return isSignalled()? 1 : -1;
229  * }
230  *
231  * protected boolean tryReleaseShared(int ignore) {
232  * setState(1);
233  * return true;
234  * }
235  * }
236  *
237  * private final Sync sync = new Sync();
238  * public boolean isSignalled() { return sync.isSignalled(); }
239  * public void signal() { sync.releaseShared(1); }
240  * public void await() throws InterruptedException {
241  * sync.acquireSharedInterruptibly(1);
242  * }
243  * }
244  *
245  * </pre>
246  *
247  * @since 1.5
248  * @author Doug Lea
249  */

250 public abstract class AbstractQueuedSynchronizer implements java.io.Serializable JavaDoc {
251     private static final long serialVersionUID = 7373984972572414691L;
252
253     /**
254      * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
255      * with initial synchronization state of zero.
256      */

257     protected AbstractQueuedSynchronizer() { }
258
259     /**
260      * Wait queue node class.
261      *
262      * <p> The wait queue is a variant of a "CLH" (Craig, Landin, and
263      * Hagersten) lock queue. CLH locks are normally used for
264      * spinlocks. We instead use them for blocking synchronizers, but
265      * use the same basic tactic of holding some of the control
266      * information about a thread in the predecessor of its node. A
267      * "status" field in each node keeps track of whether a thread
268      * should block. A node is signalled when its predecessor
269      * releases. Each node of the queue otherwise serves as a
270      * specific-notification-style monitor holding a single waiting
271      * thread. The status field does NOT control whether threads are
272      * granted locks etc though. A thread may try to acquire if it is
273      * first in the queue. But being first does not guarantee success;
274      * it only gives the right to contend. So the currently released
275      * contender thread may need to rewait.
276      *
277      * <p>To enqueue into a CLH lock, you atomically splice it in as new
278      * tail. To dequeue, you just set the head field.
279      * <pre>
280      * +------+ prev +-----+ +-----+
281      * head | | <---- | | <---- | | tail
282      * +------+ +-----+ +-----+
283      * </pre>
284      *
285      * <p>Insertion into a CLH queue requires only a single atomic
286      * operation on "tail", so there is a simple atomic point of
287      * demarcation from unqueued to queued. Similarly, dequeing
288      * involves only updating the "head". However, it takes a bit
289      * more work for nodes to determine who their successors are,
290      * in part to deal with possible cancellation due to timeouts
291      * and interrupts.
292      *
293      * <p>The "prev" links (not used in original CLH locks), are mainly
294      * needed to handle cancellation. If a node is cancelled, its
295      * successor is (normally) relinked to a non-cancelled
296      * predecessor. For explanation of similar mechanics in the case
297      * of spin locks, see the papers by Scott and Scherer at
298      * http://www.cs.rochester.edu/u/scott/synchronization/
299      *
300      * <p>We also use "next" links to implement blocking mechanics.
301      * The thread id for each node is kept in its own node, so a
302      * predecessor signals the next node to wake up by traversing
303      * next link to determine which thread it is. Determination of
304      * successor must avoid races with newly queued nodes to set
305      * the "next" fields of their predecessors. This is solved
306      * when necessary by checking backwards from the atomically
307      * updated "tail" when a node's successor appears to be null.
308      * (Or, said differently, the next-links are an optimization
309      * so that we don't usually need a backward scan.)
310      *
311      * <p>Cancellation introduces some conservatism to the basic
312      * algorithms. Since we must poll for cancellation of other
313      * nodes, we can miss noticing whether a cancelled node is
314      * ahead or behind us. This is dealt with by always unparking
315      * successors upon cancellation, allowing them to stabilize on
316      * a new predecessor.
317      *
318      * <p>CLH queues need a dummy header node to get started. But
319      * we don't create them on construction, because it would be wasted
320      * effort if there is never contention. Instead, the node
321      * is constructed and head and tail pointers are set upon first
322      * contention.
323      *
324      * <p>Threads waiting on Conditions use the same nodes, but
325      * use an additional link. Conditions only need to link nodes
326      * in simple (non-concurrent) linked queues because they are
327      * only accessed when exclusively held. Upon await, a node is
328      * inserted into a condition queue. Upon signal, the node is
329      * transferred to the main queue. A special value of status
330      * field is used to mark which queue a node is on.
331      *
332      * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
333      * Scherer and Michael Scott, along with members of JSR-166
334      * expert group, for helpful ideas, discussions, and critiques
335      * on the design of this class.
336      */

337     static final class Node {
338         /** waitStatus value to indicate thread has cancelled */
339         static final int CANCELLED = 1;
340         /** waitStatus value to indicate thread needs unparking */
341         static final int SIGNAL = -1;
342         /** waitStatus value to indicate thread is waiting on condition */
343         static final int CONDITION = -2;
344         /** Marker to indicate a node is waiting in shared mode */
345         static final Node SHARED = new Node();
346         /** Marker to indicate a node is waiting in exclusive mode */
347         static final Node EXCLUSIVE = null;
348
349         /**
350          * Status field, taking on only the values:
351          * SIGNAL: The successor of this node is (or will soon be)
352          * blocked (via park), so the current node must
353          * unpark its successor when it releases or
354          * cancels. To avoid races, acquire methods must
355          * first indicate they need a signal,
356          * then retry the atomic acquire, and then,
357          * on failure, block.
358          * CANCELLED: Node is cancelled due to timeout or interrupt
359          * Nodes never leave this state. In particular,
360          * a thread with cancelled node never again blocks.
361          * CONDITION: Node is currently on a condition queue
362          * It will not be used as a sync queue node until
363          * transferred. (Use of this value here
364          * has nothing to do with the other uses
365          * of the field, but simplifies mechanics.)
366          * 0: None of the above
367          *
368          * The values are arranged numerically to simplify use.
369          * Non-negative values mean that a node doesn't need to
370          * signal. So, most code doesn't need to check for particular
371          * values, just for sign.
372          *
373          * The field is initialized to 0 for normal sync nodes, and
374          * CONDITION for condition nodes. It is modified only using
375          * CAS.
376          */

377         volatile int waitStatus;
378
379         /**
380          * Link to predecessor node that current node/thread relies on
381          * for checking waitStatus. Assigned during enqueing, and nulled
382          * out (for sake of GC) only upon dequeuing. Also, upon
383          * cancellation of a predecessor, we short-circuit while
384          * finding a non-cancelled one, which will always exist
385          * because the head node is never cancelled: A node becomes
386          * head only as a result of successful acquire. A
387          * cancelled thread never succeeds in acquiring, and a thread only
388          * cancels itself, not any other node.
389          */

390         volatile Node prev;
391
392         /**
393          * Link to the successor node that the current node/thread
394          * unparks upon release. Assigned once during enqueuing, and
395          * nulled out (for sake of GC) when no longer needed. Upon
396          * cancellation, we cannot adjust this field, but can notice
397          * status and bypass the node if cancelled. The enq operation
398          * does not assign next field of a predecessor until after
399          * attachment, so seeing a null next field does not
400          * necessarily mean that node is at end of queue. However, if
401          * a next field appears to be null, we can scan prev's from
402          * the tail to double-check.
403          */

404         volatile Node next;
405
406         /**
407          * The thread that enqueued this node. Initialized on
408          * construction and nulled out after use.
409          */

410         volatile Thread JavaDoc thread;
411
412         /**
413          * Link to next node waiting on condition, or the special
414          * value SHARED. Because condition queues are accessed only
415          * when holding in exclusive mode, we just need a simple
416          * linked queue to hold nodes while they are waiting on
417          * conditions. They are then transferred to the queue to
418          * re-acquire. And because conditions can only be exclusive,
419          * we save a field by using special value to indicate shared
420          * mode.
421          */

422         Node nextWaiter;
423
424         /**
425          * Returns true if node is waiting in shared mode
426          */

427         final boolean isShared() {
428             return nextWaiter == SHARED;
429         }
430
431         /**
432          * Returns previous node, or throws NullPointerException if
433          * null. Use when predecessor cannot be null.
434          * @return the predecessor of this node
435          */

436         final Node predecessor() throws NullPointerException JavaDoc {
437             Node p = prev;
438             if (p == null)
439                 throw new NullPointerException JavaDoc();
440             else
441                 return p;
442         }
443
444         Node() { // Used to establish initial head or SHARED marker
445
}
446
447         Node(Thread JavaDoc thread, Node mode) { // Used by addWaiter
448
this.nextWaiter = mode;
449             this.thread = thread;
450         }
451
452         Node(Thread JavaDoc thread, int waitStatus) { // Used by Condition
453
this.waitStatus = waitStatus;
454             this.thread = thread;
455         }
456     }
457
458     /**
459      * Head of the wait queue, lazily initialized. Except for
460      * initialization, it is modified only via method setHead. Note:
461      * If head exists, its waitStatus is guaranteed not to be
462      * CANCELLED.
463      */

464     private transient volatile Node head;
465
466     /**
467      * Tail of the wait queue, lazily initialized. Modified only via
468      * method enq to add new wait node.
469      */

470     private transient volatile Node tail;
471
472     /**
473      * The synchronization state.
474      */

475     private volatile int state;
476
477     /**
478      * Returns the current value of synchronization state.
479      * This operation has memory semantics of a <tt>volatile</tt> read.
480      * @return current state value
481      */

482     protected final int getState() {
483         return state;
484     }
485
486     /**
487      * Sets the value of synchronization state.
488      * This operation has memory semantics of a <tt>volatile</tt> write.
489      * @param newState the new state value
490      */

491     protected final void setState(int newState) {
492         state = newState;
493     }
494
495     /**
496      * Atomically sets synchronization state to the given updated
497      * value if the current state value equals the expected value.
498      * This operation has memory semantics of a <tt>volatile</tt> read
499      * and write.
500      * @param expect the expected value
501      * @param update the new value
502      * @return true if successful. False return indicates that
503      * the actual value was not equal to the expected value.
504      */

505     protected final boolean compareAndSetState(int expect, int update) {
506         // See below for intrinsics setup to support this
507
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
508     }
509
510     // Queuing utilities
511

512     /**
513      * Insert node into queue, initializing if necessary. See picture above.
514      * @param node the node to insert
515      * @return node's predecessor
516      */

517     private Node enq(final Node node) {
518         for (;;) {
519             Node t = tail;
520             if (t == null) { // Must initialize
521
Node h = new Node(); // Dummy header
522
h.next = node;
523                 node.prev = h;
524                 if (compareAndSetHead(h)) {
525                     tail = node;
526                     return h;
527                 }
528             }
529             else {
530                 node.prev = t;
531                 if (compareAndSetTail(t, node)) {
532                     t.next = node;
533                     return t;
534                 }
535             }
536         }
537     }
538
539     /**
540      * Create and enq node for given thread and mode
541      * @param current the thread
542      * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
543      * @return the new node
544      */

545     private Node addWaiter(Node mode) {
546         Node node = new Node(Thread.currentThread(), mode);
547         // Try the fast path of enq; backup to full enq on failure
548
Node pred = tail;
549         if (pred != null) {
550             node.prev = pred;
551             if (compareAndSetTail(pred, node)) {
552                 pred.next = node;
553                 return node;
554             }
555         }
556         enq(node);
557         return node;
558     }
559
560     /**
561      * Set head of queue to be node, thus dequeuing. Called only by
562      * acquire methods. Also nulls out unused fields for sake of GC
563      * and to suppress unnecessary signals and traversals.
564      * @param node the node
565      */

566     private void setHead(Node node) {
567         head = node;
568         node.thread = null;
569         node.prev = null;
570     }
571
572     /**
573      * Wake up node's successor, if one exists.
574      * @param node the node
575      */

576     private void unparkSuccessor(Node node) {
577         /*
578          * Try to clear status in anticipation of signalling. It is
579          * OK if this fails or if status is changed by waiting thread.
580          */

581         compareAndSetWaitStatus(node, Node.SIGNAL, 0);
582         
583         /*
584          * Thread to unpark is held in successor, which is normally
585          * just the next node. But if cancelled or apparently null,
586          * traverse backwards from tail to find the actual
587          * non-cancelled successor.
588          */

589         Thread JavaDoc thread;
590         Node s = node.next;
591         if (s != null && s.waitStatus <= 0)
592             thread = s.thread;
593         else {
594             thread = null;
595             for (s = tail; s != null && s != node; s = s.prev)
596                 if (s.waitStatus <= 0)
597                     thread = s.thread;
598         }
599         LockSupport.unpark(thread);
600     }
601
602     /**
603      * Set head of queue, and check if successor may be waiting
604      * in shared mode, if so propagating if propagate > 0.
605      * @param pred the node holding waitStatus for node
606      * @param node the node
607      * @param propagate the return value from a tryAcquireShared
608      */

609     private void setHeadAndPropagate(Node node, int propagate) {
610         setHead(node);
611         if (propagate > 0 && node.waitStatus != 0) {
612             /*
613              * Don't bother fully figuring out successor. If it
614              * looks null, call unparkSuccessor anyway to be safe.
615              */

616             Node s = node.next;
617             if (s == null || s.isShared())
618                 unparkSuccessor(node);
619         }
620     }
621
622     // Utilities for various versions of acquire
623

624     /**
625      * Cancel an ongoing attempt to acquire.
626      * @param node the node
627      */

628     private void cancelAcquire(Node node) {
629     // Ignore if node doesn't exist
630
if (node == null)
631         return;
632
633     node.thread = null;
634
635     // Skip cancelled predecessors
636
Node pred = node.prev;
637     while (pred.waitStatus > 0)
638         node.prev = pred = pred.prev;
639
640     // Getting this before setting waitStatus ensures staleness
641
Node predNext = pred.next;
642
643     // Can use unconditional write instead of CAS here
644
node.waitStatus = Node.CANCELLED;
645
646     // If we are the tail, remove ourselves
647
if (node == tail && compareAndSetTail(node, pred)) {
648         compareAndSetNext(pred, predNext, null);
649     } else {
650         // If "active" predecessor found...
651
if (pred != head
652         && (pred.waitStatus == Node.SIGNAL
653             || compareAndSetWaitStatus(pred, 0, Node.SIGNAL))
654         && pred.thread != null) {
655
656         // If successor is active, set predecessor's next link
657
Node next = node.next;
658         if (next != null && next.waitStatus <= 0)
659             compareAndSetNext(pred, predNext, next);
660         } else {
661         unparkSuccessor(node);
662         }
663
664         node.next = node; // help GC
665
}
666     }
667
668     /**
669      * Checks and updates status for a node that failed to acquire.
670      * Returns true if thread should block. This is the main signal
671      * control in all acquire loops. Requires that pred == node.prev
672      * @param pred node's predecessor holding status
673      * @param node the node
674      * @return true if thread should block
675      */

676     private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
677         int s = pred.waitStatus;
678         if (s < 0)
679             /*
680              * This node has already set status asking a release
681              * to signal it, so it can safely park
682              */

683             return true;
684         if (s > 0) {
685             /*
686              * Predecessor was cancelled. Skip over predecessors and
687              * indicate retry.
688              */

689         do {
690         node.prev = pred = pred.prev;
691         } while (pred.waitStatus > 0);
692         pred.next = node;
693     }
694         else
695             /*
696              * Indicate that we need a signal, but don't park yet. Caller
697              * will need to retry to make sure it cannot acquire before
698              * parking.
699              */

700             compareAndSetWaitStatus(pred, 0, Node.SIGNAL);
701         return false;
702     }
703
704     /**
705      * Convenience method to interrupt current thread.
706      */

707     private static void selfInterrupt() {
708         Thread.currentThread().interrupt();
709     }
710
711     /**
712      * Convenience method to park and then check if interrupted
713      * @return true if interrupted
714      */

715     private static boolean parkAndCheckInterrupt() {
716         LockSupport.park();
717         return Thread.interrupted();
718     }
719
720     /*
721      * Various flavors of acquire, varying in exclusive/shared and
722      * control modes. Each is mostly the same, but annoyingly
723      * different. Only a little bit of factoring is possible due to
724      * interactions of exception mechanics (including ensuring that we
725      * cancel if tryAcquire throws exception) and other control, at
726      * least not without hurting performance too much.
727      */

728
729     /**
730      * Acquire in exclusive uninterruptible mode for thread already in
731      * queue. Used by condition wait methods as well as acquire.
732      * @param node the node
733      * @param arg the acquire argument
734      * @return true if interrupted while waiting
735      */

736     final boolean acquireQueued(final Node node, int arg) {
737         try {
738             boolean interrupted = false;
739             for (;;) {
740                 final Node p = node.predecessor();
741                 if (p == head && tryAcquire(arg)) {
742                     setHead(node);
743                     p.next = null; // help GC
744
return interrupted;
745                 }
746                 if (shouldParkAfterFailedAcquire(p, node) &&
747                     parkAndCheckInterrupt())
748                     interrupted = true;
749             }
750         } catch (RuntimeException JavaDoc ex) {
751             cancelAcquire(node);
752             throw ex;
753         }
754     }
755
756     /**
757      * Acquire in exclusive interruptible mode
758      * @param arg the acquire argument
759      */

760     private void doAcquireInterruptibly(int arg)
761         throws InterruptedException JavaDoc {
762         final Node node = addWaiter(Node.EXCLUSIVE);
763         try {
764             for (;;) {
765                 final Node p = node.predecessor();
766                 if (p == head && tryAcquire(arg)) {
767                     setHead(node);
768                     p.next = null; // help GC
769
return;
770                 }
771                 if (shouldParkAfterFailedAcquire(p, node) &&
772                     parkAndCheckInterrupt())
773                     break;
774             }
775         } catch (RuntimeException JavaDoc ex) {
776             cancelAcquire(node);
777             throw ex;
778         }
779         // Arrive here only if interrupted
780
cancelAcquire(node);
781         throw new InterruptedException JavaDoc();
782     }
783
784     /**
785      * Acquire in exclusive timed mode
786      * @param arg the acquire argument
787      * @param nanosTimeout max wait time
788      * @return true if acquired
789      */

790     private boolean doAcquireNanos(int arg, long nanosTimeout)
791         throws InterruptedException JavaDoc {
792         long lastTime = System.nanoTime();
793         final Node node = addWaiter(Node.EXCLUSIVE);
794         try {
795             for (;;) {
796                 final Node p = node.predecessor();
797                 if (p == head && tryAcquire(arg)) {
798                     setHead(node);
799                     p.next = null; // help GC
800
return true;
801                 }
802                 if (nanosTimeout <= 0) {
803                     cancelAcquire(node);
804                     return false;
805                 }
806                 if (shouldParkAfterFailedAcquire(p, node)) {
807                     LockSupport.parkNanos(nanosTimeout);
808                     if (Thread.interrupted())
809                         break;
810                     long now = System.nanoTime();
811                     nanosTimeout -= now - lastTime;
812                     lastTime = now;
813                 }
814             }
815         } catch (RuntimeException JavaDoc ex) {
816             cancelAcquire(node);
817             throw ex;
818         }
819         // Arrive here only if interrupted
820
cancelAcquire(node);
821         throw new InterruptedException JavaDoc();
822     }
823
824     /**
825      * Acquire in shared uninterruptible mode
826      * @param arg the acquire argument
827      */

828     private void doAcquireShared(int arg) {
829         final Node node = addWaiter(Node.SHARED);
830         try {
831             boolean interrupted = false;
832             for (;;) {
833                 final Node p = node.predecessor();
834                 if (p == head) {
835                     int r = tryAcquireShared(arg);
836                     if (r >= 0) {
837                         setHeadAndPropagate(node, r);
838                         p.next = null; // help GC
839
if (interrupted)
840                             selfInterrupt();
841                         return;
842                     }
843                 }
844                 if (shouldParkAfterFailedAcquire(p, node) &&
845                     parkAndCheckInterrupt())
846                     interrupted = true;
847             }
848         } catch (RuntimeException JavaDoc ex) {
849             cancelAcquire(node);
850             throw ex;
851         }
852     }
853
854     /**
855      * Acquire in shared interruptible mode
856      * @param arg the acquire argument
857      */

858     private void doAcquireSharedInterruptibly(int arg)
859         throws InterruptedException JavaDoc {
860         final Node node = addWaiter(Node.SHARED);
861         try {
862             for (;;) {
863                 final Node p = node.predecessor();
864                 if (p == head) {
865                     int r = tryAcquireShared(arg);
866                     if (r >= 0) {
867                         setHeadAndPropagate(node, r);
868                         p.next = null; // help GC
869
return;
870                     }
871                 }
872                 if (shouldParkAfterFailedAcquire(p, node) &&
873                     parkAndCheckInterrupt())
874                     break;
875             }
876         } catch (RuntimeException JavaDoc ex) {
877             cancelAcquire(node);
878             throw ex;
879         }
880         // Arrive here only if interrupted
881
cancelAcquire(node);
882         throw new InterruptedException JavaDoc();
883     }
884
885     /**
886      * Acquire in shared timed mode
887      * @param arg the acquire argument
888      * @param nanosTimeout max wait time
889      * @return true if acquired
890      */

891     private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
892         throws InterruptedException JavaDoc {
893
894         long lastTime = System.nanoTime();
895         final Node node = addWaiter(Node.SHARED);
896         try {
897             for (;;) {
898                 final Node p = node.predecessor();
899                 if (p == head) {
900                     int r = tryAcquireShared(arg);
901                     if (r >= 0) {
902                         setHeadAndPropagate(node, r);
903                         p.next = null; // help GC
904
return true;
905                     }
906                 }
907                 if (nanosTimeout <= 0) {
908                     cancelAcquire(node);
909                     return false;
910                 }
911                 if (shouldParkAfterFailedAcquire(p, node)) {
912                     LockSupport.parkNanos(nanosTimeout);
913                     if (Thread.interrupted())
914                         break;
915                     long now = System.nanoTime();
916                     nanosTimeout -= now - lastTime;
917                     lastTime = now;
918                 }
919             }
920         } catch (RuntimeException JavaDoc ex) {
921             cancelAcquire(node);
922             throw ex;
923         }
924         // Arrive here only if interrupted
925
cancelAcquire(node);
926         throw new InterruptedException JavaDoc();
927     }
928
929     // Main exported methods
930

931     /**
932      * Attempts to acquire in exclusive mode. This method should query
933      * if the state of the object permits it to be acquired in the
934      * exclusive mode, and if so to acquire it.
935      *
936      * <p>This method is always invoked by the thread performing
937      * acquire. If this method reports failure, the acquire method
938      * may queue the thread, if it is not already queued, until it is
939      * signalled by a release from some other thread. This can be used
940      * to implement method {@link Lock#tryLock()}.
941      *
942      * <p>The default
943      * implementation throws {@link UnsupportedOperationException}
944      *
945      * @param arg the acquire argument. This value
946      * is always the one passed to an acquire method,
947      * or is the value saved on entry to a condition wait.
948      * The value is otherwise uninterpreted and can represent anything
949      * you like.
950      * @return true if successful. Upon success, this object has been
951      * acquired.
952      * @throws IllegalMonitorStateException if acquiring would place
953      * this synchronizer in an illegal state. This exception must be
954      * thrown in a consistent fashion for synchronization to work
955      * correctly.
956      * @throws UnsupportedOperationException if exclusive mode is not supported
957      */

958     protected boolean tryAcquire(int arg) {
959         throw new UnsupportedOperationException JavaDoc();
960     }
961
962     /**
963      * Attempts to set the state to reflect a release in exclusive
964      * mode. <p>This method is always invoked by the thread
965      * performing release.
966      *
967      * <p>The default implementation throws
968      * {@link UnsupportedOperationException}
969      * @param arg the release argument. This value
970      * is always the one passed to a release method,
971      * or the current state value upon entry to a condition wait.
972      * The value is otherwise uninterpreted and can represent anything
973      * you like.
974      * @return <tt>true</tt> if this object is now in a fully released state,
975      * so that any waiting threads may attempt to acquire; and <tt>false</tt>
976      * otherwise.
977      * @throws IllegalMonitorStateException if releasing would place
978      * this synchronizer in an illegal state. This exception must be
979      * thrown in a consistent fashion for synchronization to work
980      * correctly.
981      * @throws UnsupportedOperationException if exclusive mode is not supported
982      */

983     protected boolean tryRelease(int arg) {
984         throw new UnsupportedOperationException JavaDoc();
985     }
986
987     /**
988      * Attempts to acquire in shared mode. This method should query if
989      * the state of the object permits it to be acquired in the shared
990      * mode, and if so to acquire it.
991      *
992      * <p>This method is always invoked by the thread performing
993      * acquire. If this method reports failure, the acquire method
994      * may queue the thread, if it is not already queued, until it is
995      * signalled by a release from some other thread.
996      *
997      * <p>The default implementation throws {@link
998      * UnsupportedOperationException}
999      *
1000     * @param arg the acquire argument. This value
1001     * is always the one passed to an acquire method,
1002     * or is the value saved on entry to a condition wait.
1003     * The value is otherwise uninterpreted and can represent anything
1004     * you like.
1005     * @return a negative value on failure, zero on exclusive success,
1006     * and a positive value if non-exclusively successful, in which
1007     * case a subsequent waiting thread must check
1008     * availability. (Support for three different return values
1009     * enables this method to be used in contexts where acquires only
1010     * sometimes act exclusively.) Upon success, this object has been
1011     * acquired.
1012     * @throws IllegalMonitorStateException if acquiring would place
1013     * this synchronizer in an illegal state. This exception must be
1014     * thrown in a consistent fashion for synchronization to work
1015     * correctly.
1016     * @throws UnsupportedOperationException if shared mode is not supported
1017     */

1018    protected int tryAcquireShared(int arg) {
1019        throw new UnsupportedOperationException JavaDoc();
1020    }
1021
1022    /**
1023     * Attempts to set the state to reflect a release in shared mode.
1024     * <p>This method is always invoked by the thread performing release.
1025     * <p> The default implementation throws
1026     * {@link UnsupportedOperationException}
1027     * @param arg the release argument. This value
1028     * is always the one passed to a release method,
1029     * or the current state value upon entry to a condition wait.
1030     * The value is otherwise uninterpreted and can represent anything
1031     * you like.
1032     * @return <tt>true</tt> if this object is now in a fully released state,
1033     * so that any waiting threads may attempt to acquire; and <tt>false</tt>
1034     * otherwise.
1035     * @throws IllegalMonitorStateException if releasing would place
1036     * this synchronizer in an illegal state. This exception must be
1037     * thrown in a consistent fashion for synchronization to work
1038     * correctly.
1039     * @throws UnsupportedOperationException if shared mode is not supported
1040     */

1041    protected boolean tryReleaseShared(int arg) {
1042        throw new UnsupportedOperationException JavaDoc();
1043    }
1044
1045    /**
1046     * Returns true if synchronization is held exclusively with respect
1047     * to the current (calling) thread. This method is invoked
1048     * upon each call to a non-waiting {@link ConditionObject} method.
1049     * (Waiting methods instead invoke {@link #release}.)
1050     * <p>The default implementation throws {@link
1051     * UnsupportedOperationException}. This method is invoked
1052     * internally only within {@link ConditionObject} methods, so need
1053     * not be defined if conditions are not used.
1054     *
1055     * @return true if synchronization is held exclusively;
1056     * else false
1057     * @throws UnsupportedOperationException if conditions are not supported
1058     */

1059    protected boolean isHeldExclusively() {
1060        throw new UnsupportedOperationException JavaDoc();
1061    }
1062
1063    /**
1064     * Acquires in exclusive mode, ignoring interrupts. Implemented
1065     * by invoking at least once {@link #tryAcquire},
1066     * returning on success. Otherwise the thread is queued, possibly
1067     * repeatedly blocking and unblocking, invoking {@link
1068     * #tryAcquire} until success. This method can be used
1069     * to implement method {@link Lock#lock}
1070     * @param arg the acquire argument.
1071     * This value is conveyed to {@link #tryAcquire} but is
1072     * otherwise uninterpreted and can represent anything
1073     * you like.
1074     */

1075    public final void acquire(int arg) {
1076        if (!tryAcquire(arg) &&
1077            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
1078            selfInterrupt();
1079    }
1080
1081    /**
1082     * Acquires in exclusive mode, aborting if interrupted.
1083     * Implemented by first checking interrupt status, then invoking
1084     * at least once {@link #tryAcquire}, returning on
1085     * success. Otherwise the thread is queued, possibly repeatedly
1086     * blocking and unblocking, invoking {@link #tryAcquire}
1087     * until success or the thread is interrupted. This method can be
1088     * used to implement method {@link Lock#lockInterruptibly}
1089     * @param arg the acquire argument.
1090     * This value is conveyed to {@link #tryAcquire} but is
1091     * otherwise uninterpreted and can represent anything
1092     * you like.
1093     * @throws InterruptedException if the current thread is interrupted
1094     */

1095    public final void acquireInterruptibly(int arg) throws InterruptedException JavaDoc {
1096        if (Thread.interrupted())
1097            throw new InterruptedException JavaDoc();
1098        if (!tryAcquire(arg))
1099            doAcquireInterruptibly(arg);
1100    }
1101
1102    /**
1103     * Attempts to acquire in exclusive mode, aborting if interrupted,
1104     * and failing if the given timeout elapses. Implemented by first
1105     * checking interrupt status, then invoking at least once {@link
1106     * #tryAcquire}, returning on success. Otherwise, the thread is
1107     * queued, possibly repeatedly blocking and unblocking, invoking
1108     * {@link #tryAcquire} until success or the thread is interrupted
1109     * or the timeout elapses. This method can be used to implement
1110     * method {@link Lock#tryLock(long, TimeUnit)}.
1111     * @param arg the acquire argument.
1112     * This value is conveyed to {@link #tryAcquire} but is
1113     * otherwise uninterpreted and can represent anything
1114     * you like.
1115     * @param nanosTimeout the maximum number of nanoseconds to wait
1116     * @return true if acquired; false if timed out
1117     * @throws InterruptedException if the current thread is interrupted
1118     */

1119   public final boolean tryAcquireNanos(int arg, long nanosTimeout) throws InterruptedException JavaDoc {
1120       if (Thread.interrupted())
1121           throw new InterruptedException JavaDoc();
1122       return tryAcquire(arg) ||
1123           doAcquireNanos(arg, nanosTimeout);
1124   }
1125
1126    /**
1127     * Releases in exclusive mode. Implemented by unblocking one or
1128     * more threads if {@link #tryRelease} returns true.
1129     * This method can be used to implement method {@link Lock#unlock}
1130     * @param arg the release argument.
1131     * This value is conveyed to {@link #tryRelease} but is
1132     * otherwise uninterpreted and can represent anything
1133     * you like.
1134     * @return the value returned from {@link #tryRelease}
1135     */

1136    public final boolean release(int arg) {
1137        if (tryRelease(arg)) {
1138            Node h = head;
1139            if (h != null && h.waitStatus != 0)
1140                unparkSuccessor(h);
1141            return true;
1142        }
1143        return false;
1144    }
1145
1146    /**
1147     * Acquires in shared mode, ignoring interrupts. Implemented by
1148     * first invoking at least once {@link #tryAcquireShared},
1149     * returning on success. Otherwise the thread is queued, possibly
1150     * repeatedly blocking and unblocking, invoking {@link
1151     * #tryAcquireShared} until success.
1152     * @param arg the acquire argument.
1153     * This value is conveyed to {@link #tryAcquireShared} but is
1154     * otherwise uninterpreted and can represent anything
1155     * you like.
1156     */

1157    public final void acquireShared(int arg) {
1158        if (tryAcquireShared(arg) < 0)
1159            doAcquireShared(arg);
1160    }
1161
1162    /**
1163     * Acquires in shared mode, aborting if interrupted. Implemented
1164     * by first checking interrupt status, then invoking at least once
1165     * {@link #tryAcquireShared}, returning on success. Otherwise the
1166     * thread is queued, possibly repeatedly blocking and unblocking,
1167     * invoking {@link #tryAcquireShared} until success or the thread
1168     * is interrupted.
1169     * @param arg the acquire argument.
1170     * This value is conveyed to {@link #tryAcquireShared} but is
1171     * otherwise uninterpreted and can represent anything
1172     * you like.
1173     * @throws InterruptedException if the current thread is interrupted
1174     */

1175    public final void acquireSharedInterruptibly(int arg) throws InterruptedException JavaDoc {
1176        if (Thread.interrupted())
1177            throw new InterruptedException JavaDoc();
1178        if (tryAcquireShared(arg) < 0)
1179            doAcquireSharedInterruptibly(arg);
1180   }
1181
1182    /**
1183     * Attempts to acquire in shared mode, aborting if interrupted, and
1184     * failing if the given timeout elapses. Implemented by first
1185     * checking interrupt status, then invoking at least once {@link
1186     * #tryAcquireShared}, returning on success. Otherwise, the
1187     * thread is queued, possibly repeatedly blocking and unblocking,
1188     * invoking {@link #tryAcquireShared} until success or the thread
1189     * is interrupted or the timeout elapses.
1190     * @param arg the acquire argument.
1191     * This value is conveyed to {@link #tryAcquireShared} but is
1192     * otherwise uninterpreted and can represent anything
1193     * you like.
1194     * @param nanosTimeout the maximum number of nanoseconds to wait
1195     * @return true if acquired; false if timed out
1196     * @throws InterruptedException if the current thread is interrupted
1197     */

1198   public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) throws InterruptedException JavaDoc {
1199       if (Thread.interrupted())
1200           throw new InterruptedException JavaDoc();
1201       return tryAcquireShared(arg) >= 0 ||
1202           doAcquireSharedNanos(arg, nanosTimeout);
1203   }
1204
1205    /**
1206     * Releases in shared mode. Implemented by unblocking one or more
1207     * threads if {@link #tryReleaseShared} returns true.
1208     * @param arg the release argument.
1209     * This value is conveyed to {@link #tryReleaseShared} but is
1210     * otherwise uninterpreted and can represent anything
1211     * you like.
1212     * @return the value returned from {@link #tryReleaseShared}
1213     */

1214    public final boolean releaseShared(int arg) {
1215        if (tryReleaseShared(arg)) {
1216            Node h = head;
1217            if (h != null && h.waitStatus != 0)
1218                unparkSuccessor(h);
1219            return true;
1220        }
1221        return false;
1222    }
1223
1224    // Queue inspection methods
1225

1226    /**
1227     * Queries whether any threads are waiting to acquire. Note that
1228     * because cancellations due to interrupts and timeouts may occur
1229     * at any time, a <tt>true</tt> return does not guarantee that any
1230     * other thread will ever acquire.
1231     *
1232     * <p> In this implementation, this operation returns in
1233     * constant time.
1234     *
1235     * @return true if there may be other threads waiting to acquire
1236     * the lock.
1237     */

1238    public final boolean hasQueuedThreads() {
1239        return head != tail;
1240    }
1241
1242    /**
1243     * Queries whether any threads have ever contended to acquire this
1244     * synchronizer; that is if an acquire method has ever blocked.
1245     *
1246     * <p> In this implementation, this operation returns in
1247     * constant time.
1248     *
1249     * @return true if there has ever been contention
1250     */

1251    public final boolean hasContended() {
1252        return head != null;
1253    }
1254
1255    /**
1256     * Returns the first (longest-waiting) thread in the queue, or
1257     * <tt>null</tt> if no threads are currently queued.
1258     *
1259     * <p> In this implementation, this operation normally returns in
1260     * constant time, but may iterate upon contention if other threads are
1261     * concurrently modifying the queue.
1262     *
1263     * @return the first (longest-waiting) thread in the queue, or
1264     * <tt>null</tt> if no threads are currently queued.
1265     */

1266    public final Thread JavaDoc getFirstQueuedThread() {
1267        // handle only fast path, else relay
1268
return (head == tail)? null : fullGetFirstQueuedThread();
1269    }
1270
1271    /**
1272     * Version of getFirstQueuedThread called when fastpath fails
1273     */

1274    private Thread JavaDoc fullGetFirstQueuedThread() {
1275            Node h = head;
1276            if (h == null) // No queue
1277
return null;
1278
1279            /*
1280             * The first node is normally h.next. Try to get its
1281             * thread field, ensuring consistent reads: If thread
1282             * field is nulled out or s.prev is no longer head, then
1283             * some other thread(s) concurrently performed setHead in
1284         * between some of our reads.
1285             */

1286            Node s = h.next;
1287            if (s != null) {
1288                Thread JavaDoc st = s.thread;
1289                Node sp = s.prev;
1290                if (st != null && sp == head)
1291                    return st;
1292            }
1293
1294            /*
1295         * Head's next field might not have been set yet, or may have
1296         * been unset after setHead. So we must check to see if tail
1297         * is actually first node. If not, we continue on, safely
1298         * traversing from tail back to head to find first,
1299         * guaranteeing termination.
1300             */

1301
1302        Node t = tail;
1303        Thread JavaDoc firstThread = null;
1304        while (t != null && t != head) {
1305                Thread JavaDoc tt = t.thread;
1306            if (tt != null)
1307                firstThread = tt;
1308            t = t.prev;
1309        }
1310        return firstThread;
1311    }
1312
1313    /**
1314     * Returns true if the given thread is currently queued.
1315     *
1316     * <p> This implementation traverses the queue to determine
1317     * presence of the given thread.
1318     *
1319     * @param thread the thread
1320     * @return true if the given thread in on the queue
1321     * @throws NullPointerException if thread null
1322     */

1323    public final boolean isQueued(Thread JavaDoc thread) {
1324        if (thread == null)
1325            throw new NullPointerException JavaDoc();
1326        for (Node p = tail; p != null; p = p.prev)
1327            if (p.thread == thread)
1328                return true;
1329        return false;
1330    }
1331
1332    // Instrumentation and monitoring methods
1333

1334    /**
1335     * Returns an estimate of the number of threads waiting to
1336     * acquire. The value is only an estimate because the number of
1337     * threads may change dynamically while this method traverses
1338     * internal data structures. This method is designed for use in
1339     * monitoring system state, not for synchronization
1340     * control.
1341     *
1342     * @return the estimated number of threads waiting for this lock
1343     */

1344    public final int getQueueLength() {
1345        int n = 0;
1346        for (Node p = tail; p != null; p = p.prev) {
1347            if (p.thread != null)
1348                ++n;
1349        }
1350        return n;
1351    }
1352
1353    /**
1354     * Returns a collection containing threads that may be waiting to
1355     * acquire. Because the actual set of threads may change
1356     * dynamically while constructing this result, the returned
1357     * collection is only a best-effort estimate. The elements of the
1358     * returned collection are in no particular order. This method is
1359     * designed to facilitate construction of subclasses that provide
1360     * more extensive monitoring facilities.
1361     * @return the collection of threads
1362     */

1363    public final Collection<Thread JavaDoc> getQueuedThreads() {
1364        ArrayList<Thread JavaDoc> list = new ArrayList<Thread JavaDoc>();
1365        for (Node p = tail; p != null; p = p.prev) {
1366            Thread JavaDoc t = p.thread;
1367            if (t != null)
1368                list.add(t);
1369        }
1370        return list;
1371    }
1372
1373    /**
1374     * Returns a collection containing threads that may be waiting to
1375     * acquire in exclusive mode. This has the same properties
1376     * as {@link #getQueuedThreads} except that it only returns
1377     * those threads waiting due to an exclusive acquire.
1378     * @return the collection of threads
1379     */

1380    public final Collection<Thread JavaDoc> getExclusiveQueuedThreads() {
1381        ArrayList<Thread JavaDoc> list = new ArrayList<Thread JavaDoc>();
1382        for (Node p = tail; p != null; p = p.prev) {
1383            if (!p.isShared()) {
1384                Thread JavaDoc t = p.thread;
1385                if (t != null)
1386                    list.add(t);
1387            }
1388        }
1389        return list;
1390    }
1391
1392    /**
1393     * Returns a collection containing threads that may be waiting to
1394     * acquire in shared mode. This has the same properties
1395     * as {@link #getQueuedThreads} except that it only returns
1396     * those threads waiting due to a shared acquire.
1397     * @return the collection of threads
1398     */

1399    public final Collection<Thread JavaDoc> getSharedQueuedThreads() {
1400        ArrayList<Thread JavaDoc> list = new ArrayList<Thread JavaDoc>();
1401        for (Node p = tail; p != null; p = p.prev) {
1402            if (p.isShared()) {
1403                Thread JavaDoc t = p.thread;
1404                if (t != null)
1405                    list.add(t);
1406            }
1407        }
1408        return list;
1409    }
1410
1411    /**
1412     * Returns a string identifying this synchronizer, as well as its
1413     * state. The state, in brackets, includes the String &quot;State
1414     * =&quot; followed by the current value of {@link #getState}, and
1415     * either &quot;nonempty&quot; or &quot;empty&quot; depending on
1416     * whether the queue is empty.
1417     *
1418     * @return a string identifying this synchronizer, as well as its state.
1419     */

1420    public String JavaDoc toString() {
1421        int s = getState();
1422        String JavaDoc q = hasQueuedThreads()? "non" : "";
1423        return super.toString() +
1424            "[State = " + s + ", " + q + "empty queue]";
1425    }
1426
1427
1428    // Internal support methods for Conditions
1429

1430    /**
1431     * Returns true if a node, always one that was initially placed on
1432     * a condition queue, is now waiting to reacquire on sync queue.
1433     * @param node the node
1434     * @return true if is reacquiring
1435     */

1436    final boolean isOnSyncQueue(Node node) {
1437        if (node.waitStatus == Node.CONDITION || node.prev == null)
1438            return false;
1439        if (node.next != null) // If has successor, it must be on queue
1440
return true;
1441        /*
1442         * node.prev can be non-null, but not yet on queue because
1443         * the CAS to place it on queue can fail. So we have to
1444         * traverse from tail to make sure it actually made it. It
1445         * will always be near the tail in calls to this method, and
1446         * unless the CAS failed (which is unlikely), it will be
1447         * there, so we hardly ever traverse much.
1448         */

1449        return findNodeFromTail(node);
1450    }
1451
1452    /**
1453     * Returns true if node is on sync queue by searching backwards from tail.
1454     * Called only when needed by isOnSyncQueue.
1455     * @return true if present
1456     */

1457    private boolean findNodeFromTail(Node node) {
1458        Node t = tail;
1459        for (;;) {
1460            if (t == node)
1461                return true;
1462            if (t == null)
1463                return false;
1464            t = t.prev;
1465        }
1466    }
1467
1468    /**
1469     * Transfers a node from a condition queue onto sync queue.
1470     * Returns true if successful.
1471     * @param node the node
1472     * @return true if successfully transferred (else the node was
1473     * cancelled before signal).
1474     */

1475    final boolean transferForSignal(Node node) {
1476        /*
1477         * If cannot change waitStatus, the node has been cancelled.
1478         */

1479        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
1480            return false;
1481
1482        /*
1483         * Splice onto queue and try to set waitStatus of predecessor to
1484         * indicate that thread is (probably) waiting. If cancelled or
1485         * attempt to set waitStatus fails, wake up to resync (in which
1486         * case the waitStatus can be transiently and harmlessly wrong).
1487         */

1488        Node p = enq(node);
1489        int c = p.waitStatus;
1490        if (c > 0 || !compareAndSetWaitStatus(p, c, Node.SIGNAL))
1491            LockSupport.unpark(node.thread);
1492        return true;
1493    }
1494
1495    /**
1496     * Transfers node, if necessary, to sync queue after a cancelled
1497     * wait. Returns true if thread was cancelled before being
1498     * signalled.
1499     * @param current the waiting thread
1500     * @param node its node
1501     * @return true if cancelled before the node was signalled.
1502     */

1503    final boolean transferAfterCancelledWait(Node node) {
1504        if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
1505            enq(node);
1506            return true;
1507        }
1508        /*
1509         * If we lost out to a signal(), then we can't proceed
1510         * until it finishes its enq(). Cancelling during an
1511         * incomplete transfer is both rare and transient, so just
1512         * spin.
1513         */

1514        while (!isOnSyncQueue(node))
1515            Thread.yield();
1516        return false;
1517    }
1518
1519    /**
1520     * Invoke release with current state value; return saved state.
1521     * Cancel node and throw exception on failure.
1522     * @param node the condition node for this wait
1523     * @return previous sync state
1524     */

1525    final int fullyRelease(Node node) {
1526        try {
1527            int savedState = getState();
1528            if (release(savedState))
1529                return savedState;
1530        } catch(RuntimeException JavaDoc ex) {
1531            node.waitStatus = Node.CANCELLED;
1532            throw ex;
1533        }
1534        // reach here if release fails
1535
node.waitStatus = Node.CANCELLED;
1536        throw new IllegalMonitorStateException JavaDoc();
1537    }
1538
1539    // Instrumentation methods for conditions
1540

1541    /**
1542     * Queries whether the given ConditionObject
1543     * uses this synchronizer as its lock.
1544     * @param condition the condition
1545     * @return <tt>true</tt> if owned
1546     * @throws NullPointerException if condition null
1547     */

1548    public final boolean owns(ConditionObject condition) {
1549        if (condition == null)
1550            throw new NullPointerException JavaDoc();
1551        return condition.isOwnedBy(this);
1552    }
1553
1554    /**
1555     * Queries whether any threads are waiting on the given condition
1556     * associated with this synchronizer. Note that because timeouts
1557     * and interrupts may occur at any time, a <tt>true</tt> return
1558     * does not guarantee that a future <tt>signal</tt> will awaken
1559     * any threads. This method is designed primarily for use in
1560     * monitoring of the system state.
1561     * @param condition the condition
1562     * @return <tt>true</tt> if there are any waiting threads.
1563     * @throws IllegalMonitorStateException if exclusive synchronization
1564     * is not held
1565     * @throws IllegalArgumentException if the given condition is
1566     * not associated with this synchronizer
1567     * @throws NullPointerException if condition null
1568     */

1569    public final boolean hasWaiters(ConditionObject condition) {
1570        if (!owns(condition))
1571            throw new IllegalArgumentException JavaDoc("Not owner");
1572        return condition.hasWaiters();
1573    }
1574
1575    /**
1576     * Returns an estimate of the number of threads waiting on the
1577     * given condition associated with this synchronizer. Note that
1578     * because timeouts and interrupts may occur at any time, the
1579     * estimate serves only as an upper bound on the actual number of
1580     * waiters. This method is designed for use in monitoring of the
1581     * system state, not for synchronization control.
1582     * @param condition the condition
1583     * @return the estimated number of waiting threads.
1584     * @throws IllegalMonitorStateException if exclusive synchronization
1585     * is not held
1586     * @throws IllegalArgumentException if the given condition is
1587     * not associated with this synchronizer
1588     * @throws NullPointerException if condition null
1589     */

1590    public final int getWaitQueueLength(ConditionObject condition) {
1591        if (!owns(condition))
1592            throw new IllegalArgumentException JavaDoc("Not owner");
1593        return condition.getWaitQueueLength();
1594    }
1595
1596    /**
1597     * Returns a collection containing those threads that may be
1598     * waiting on the given condition associated with this
1599     * synchronizer. Because the actual set of threads may change
1600     * dynamically while constructing this result, the returned
1601     * collection is only a best-effort estimate. The elements of the
1602     * returned collection are in no particular order.
1603     * @param condition the condition
1604     * @return the collection of threads
1605     * @throws IllegalMonitorStateException if exclusive synchronization
1606     * is not held
1607     * @throws IllegalArgumentException if the given condition is
1608     * not associated with this synchronizer
1609     * @throws NullPointerException if condition null
1610     */

1611    public final Collection<Thread JavaDoc> getWaitingThreads(ConditionObject condition) {
1612        if (!owns(condition))
1613            throw new IllegalArgumentException JavaDoc("Not owner");
1614        return condition.getWaitingThreads();
1615    }
1616
1617    /**
1618     * Condition implementation for a {@link
1619     * AbstractQueuedSynchronizer} serving as the basis of a {@link
1620     * Lock} implementation.
1621     *
1622     * <p> Method documentation for this class describes mechanics,
1623     * not behavioral specifications from the point of view of Lock
1624     * and Condition users. Exported versions of this class will in
1625     * general need to be accompanied by documentation describing
1626     * condition semantics that rely on those of the associated
1627     * <tt>AbstractQueuedSynchronizer</tt>.
1628     *
1629     * <p> This class is Serializable, but all fields are transient,
1630     * so deserialized conditions have no waiters.
1631     */

1632    public class ConditionObject implements Condition JavaDoc, java.io.Serializable JavaDoc {
1633        private static final long serialVersionUID = 1173984872572414699L;
1634        /** First node of condition queue. */
1635        private transient Node firstWaiter;
1636        /** Last node of condition queue. */
1637        private transient Node lastWaiter;
1638
1639        /**
1640         * Creates a new <tt>ConditionObject</tt> instance.
1641         */

1642        public ConditionObject() { }
1643
1644        // Internal methods
1645

1646        /**
1647         * Add a new waiter to wait queue
1648         * @return its new wait node
1649         */

1650        private Node addConditionWaiter() {
1651            Node t = lastWaiter;
1652            // If lastWaiter is cancelled, clean out.
1653
if (t != null && t.waitStatus != Node.CONDITION) {
1654                unlinkCancelledWaiters();
1655                t = lastWaiter;
1656            }
1657            Node node = new Node(Thread.currentThread(), Node.CONDITION);
1658            if (t == null)
1659                firstWaiter = node;
1660            else
1661                t.nextWaiter = node;
1662            lastWaiter = node;
1663            return node;
1664        }
1665
1666        /**
1667         * Remove and transfer nodes until hit non-cancelled one or
1668         * null. Split out from signal in part to encourage compilers
1669         * to inline the case of no waiters.
1670         * @param first (non-null) the first node on condition queue
1671         */

1672        private void doSignal(Node first) {
1673            do {
1674                if ( (firstWaiter = first.nextWaiter) == null)
1675                    lastWaiter = null;
1676                first.nextWaiter = null;
1677            } while (!transferForSignal(first) &&
1678                     (first = firstWaiter) != null);
1679        }
1680
1681        /**
1682         * Remove and transfer all nodes.
1683         * @param first (non-null) the first node on condition queue
1684         */

1685        private void doSignalAll(Node first) {
1686            lastWaiter = firstWaiter = null;
1687            do {
1688                Node next = first.nextWaiter;
1689                first.nextWaiter = null;
1690                transferForSignal(first);
1691                first = next;
1692            } while (first != null);
1693        }
1694
1695        // public methods
1696

1697        /**
1698         * Moves the longest-waiting thread, if one exists, from the
1699         * wait queue for this condition to the wait queue for the
1700         * owning lock.
1701         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1702         * returns false
1703         */

1704        public final void signal() {
1705            if (!isHeldExclusively())
1706                throw new IllegalMonitorStateException JavaDoc();
1707            Node first = firstWaiter;
1708            if (first != null)
1709                doSignal(first);
1710        }
1711         
1712        /**
1713         * Moves all threads from the wait queue for this condition to
1714         * the wait queue for the owning lock.
1715         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1716         * returns false
1717         */

1718        public final void signalAll() {
1719            if (!isHeldExclusively())
1720                throw new IllegalMonitorStateException JavaDoc();
1721            Node first = firstWaiter;
1722            if (first != null)
1723                doSignalAll(first);
1724        }
1725
1726        /**
1727         * Unlinks cancelled waiter nodes from condition queue.
1728         * Called only while holding lock. This is called when
1729         * cancellation occurred during condition wait, and upon
1730         * insertion of a new waiter when lastWaiter is seen to have
1731         * been cancelled. This method is needed to avoid garbage
1732         * retention in the absence of signals. So even though it may
1733         * require a full traversal, it comes into play only when
1734         * timeouts or cancellations occur in the absence of
1735         * signals. It traverses all nodes rather than stopping at a
1736         * particular target to unlink all pointers to garbage nodes
1737         * without requiring many re-traversals during cancellation
1738         * storms.
1739         */

1740        private void unlinkCancelledWaiters() {
1741            Node t = firstWaiter;
1742            Node trail = null;
1743            while (t != null) {
1744                Node next = t.nextWaiter;
1745                if (t.waitStatus != Node.CONDITION) {
1746                    t.nextWaiter = null;
1747                    if (trail == null)
1748                        firstWaiter = next;
1749                    else
1750                        trail.nextWaiter = next;
1751                    if (next == null)
1752                        lastWaiter = trail;
1753                }
1754                else
1755                    trail = t;
1756                t = next;
1757            }
1758        }
1759
1760        /**
1761         * Implements uninterruptible condition wait.
1762         * <ol>
1763         * <li> Save lock state returned by {@link #getState}
1764         * <li> Invoke {@link #release} with
1765         * saved state as argument, throwing
1766         * IllegalMonitorStateException if it fails.
1767         * <li> Block until signalled
1768         * <li> Reacquire by invoking specialized version of
1769         * {@link #acquire} with saved state as argument.
1770         * </ol>
1771         */

1772        public final void awaitUninterruptibly() {
1773            Node node = addConditionWaiter();
1774            int savedState = fullyRelease(node);
1775            boolean interrupted = false;
1776            while (!isOnSyncQueue(node)) {
1777                LockSupport.park();
1778                if (Thread.interrupted())
1779                    interrupted = true;
1780            }
1781            if (acquireQueued(node, savedState) || interrupted)
1782                selfInterrupt();
1783        }
1784
1785        /*
1786         * For interruptible waits, we need to track whether to throw
1787         * InterruptedException, if interrupted while blocked on
1788         * condition, versus reinterrupt current thread, if
1789         * interrupted while blocked waiting to re-acquire.
1790         */

1791
1792        /** Mode meaning to reinterrupt on exit from wait */
1793        private static final int REINTERRUPT = 1;
1794        /** Mode meaning to throw InterruptedException on exit from wait */
1795        private static final int THROW_IE = -1;
1796
1797        /**
1798         * Check for interrupt, returning THROW_IE if interrupted
1799         * before signalled, REINTERRUPT if after signalled, or
1800         * 0 if not interrupted.
1801         */

1802        private int checkInterruptWhileWaiting(Node node) {
1803            return (Thread.interrupted()) ?
1804                ((transferAfterCancelledWait(node))? THROW_IE : REINTERRUPT) :
1805                0;
1806        }
1807
1808        /**
1809         * Throw InterruptedException, reinterrupt current thread, or
1810         * do nothing, depending on mode.
1811         */

1812        private void reportInterruptAfterWait(int interruptMode)
1813            throws InterruptedException JavaDoc {
1814            if (interruptMode == THROW_IE)
1815                throw new InterruptedException JavaDoc();
1816            else if (interruptMode == REINTERRUPT)
1817                Thread.currentThread().interrupt();
1818        }
1819
1820        /**
1821         * Implements interruptible condition wait.
1822         * <ol>
1823         * <li> If current thread is interrupted, throw InterruptedException
1824         * <li> Save lock state returned by {@link #getState}
1825         * <li> Invoke {@link #release} with
1826         * saved state as argument, throwing
1827         * IllegalMonitorStateException if it fails.
1828         * <li> Block until signalled or interrupted
1829         * <li> Reacquire by invoking specialized version of
1830         * {@link #acquire} with saved state as argument.
1831         * <li> If interrupted while blocked in step 4, throw exception
1832         * </ol>
1833         */

1834        public final void await() throws InterruptedException JavaDoc {
1835            if (Thread.interrupted())
1836                throw new InterruptedException JavaDoc();
1837            Node node = addConditionWaiter();
1838            int savedState = fullyRelease(node);
1839            int interruptMode = 0;
1840            while (!isOnSyncQueue(node)) {
1841                LockSupport.park();
1842                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
1843                    break;
1844            }
1845            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
1846                interruptMode = REINTERRUPT;
1847            if (node.nextWaiter != null)
1848                unlinkCancelledWaiters();
1849            if (interruptMode != 0)
1850                reportInterruptAfterWait(interruptMode);
1851        }
1852
1853        /**
1854         * Implements timed condition wait.
1855         * <ol>
1856         * <li> If current thread is interrupted, throw InterruptedException
1857         * <li> Save lock state returned by {@link #getState}
1858         * <li> Invoke {@link #release} with
1859         * saved state as argument, throwing
1860         * IllegalMonitorStateException if it fails.
1861         * <li> Block until signalled, interrupted, or timed out
1862         * <li> Reacquire by invoking specialized version of
1863         * {@link #acquire} with saved state as argument.
1864         * <li> If interrupted while blocked in step 4, throw InterruptedException
1865         * </ol>
1866         */

1867        public final long awaitNanos(long nanosTimeout) throws InterruptedException JavaDoc {
1868            if (Thread.interrupted())
1869                throw new InterruptedException JavaDoc();
1870            Node node = addConditionWaiter();
1871            int savedState = fullyRelease(node);
1872            long lastTime = System.nanoTime();
1873            int interruptMode = 0;
1874            while (!isOnSyncQueue(node)) {
1875                if (nanosTimeout <= 0L) {
1876                    transferAfterCancelledWait(node);
1877                    break;
1878                }
1879                LockSupport.parkNanos(nanosTimeout);
1880                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
1881                    break;
1882                long now = System.nanoTime();
1883                nanosTimeout -= now - lastTime;
1884                lastTime = now;
1885            }
1886            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
1887                interruptMode = REINTERRUPT;
1888            if (node.nextWaiter != null)
1889                unlinkCancelledWaiters();
1890            if (interruptMode != 0)
1891                reportInterruptAfterWait(interruptMode);
1892            return nanosTimeout - (System.nanoTime() - lastTime);
1893        }
1894
1895        /**
1896         * Implements absolute timed condition wait.
1897         * <ol>
1898         * <li> If current thread is interrupted, throw InterruptedException
1899         * <li> Save lock state returned by {@link #getState}
1900         * <li> Invoke {@link #release} with
1901         * saved state as argument, throwing
1902         * IllegalMonitorStateException if it fails.
1903         * <li> Block until signalled, interrupted, or timed out
1904         * <li> Reacquire by invoking specialized version of
1905         * {@link #acquire} with saved state as argument.
1906         * <li> If interrupted while blocked in step 4, throw InterruptedException
1907         * <li> If timed out while blocked in step 4, return false, else true
1908         * </ol>
1909         */

1910        public final boolean awaitUntil(Date deadline) throws InterruptedException JavaDoc {
1911            if (deadline == null)
1912                throw new NullPointerException JavaDoc();
1913            long abstime = deadline.getTime();
1914            if (Thread.interrupted())
1915                throw new InterruptedException JavaDoc();
1916            Node node = addConditionWaiter();
1917            int savedState = fullyRelease(node);
1918            boolean timedout = false;
1919            int interruptMode = 0;
1920            while (!isOnSyncQueue(node)) {
1921                if (System.currentTimeMillis() > abstime) {
1922                    timedout = transferAfterCancelledWait(node);
1923                    break;
1924                }
1925                LockSupport.parkUntil(abstime);
1926                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
1927                    break;
1928            }
1929            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
1930                interruptMode = REINTERRUPT;
1931            if (node.nextWaiter != null)
1932                unlinkCancelledWaiters();
1933            if (interruptMode != 0)
1934                reportInterruptAfterWait(interruptMode);
1935            return !timedout;
1936        }
1937        
1938        /**
1939         * Implements timed condition wait.
1940         * <ol>
1941         * <li> If current thread is interrupted, throw InterruptedException
1942         * <li> Save lock state returned by {@link #getState}
1943         * <li> Invoke {@link #release} with
1944         * saved state as argument, throwing
1945         * IllegalMonitorStateException if it fails.
1946         * <li> Block until signalled, interrupted, or timed out
1947         * <li> Reacquire by invoking specialized version of
1948         * {@link #acquire} with saved state as argument.
1949         * <li> If interrupted while blocked in step 4, throw InterruptedException
1950         * <li> If timed out while blocked in step 4, return false, else true
1951         * </ol>
1952         */

1953        public final boolean await(long time, TimeUnit unit) throws InterruptedException JavaDoc {
1954            if (unit == null)
1955                throw new NullPointerException JavaDoc();
1956            long nanosTimeout = unit.toNanos(time);
1957            if (Thread.interrupted())
1958                throw new InterruptedException JavaDoc();
1959            Node node = addConditionWaiter();
1960            int savedState = fullyRelease(node);
1961            long lastTime = System.nanoTime();
1962            boolean timedout = false;
1963            int interruptMode = 0;
1964            while (!isOnSyncQueue(node)) {
1965                if (nanosTimeout <= 0L) {
1966                    timedout = transferAfterCancelledWait(node);
1967                    break;
1968                }
1969                LockSupport.parkNanos(nanosTimeout);
1970                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
1971                    break;
1972                long now = System.nanoTime();
1973                nanosTimeout -= now - lastTime;
1974                lastTime = now;
1975            }
1976            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
1977                interruptMode = REINTERRUPT;
1978            if (node.nextWaiter != null)
1979                unlinkCancelledWaiters();
1980            if (interruptMode != 0)
1981                reportInterruptAfterWait(interruptMode);
1982            return !timedout;
1983        }
1984
1985        // support for instrumentation
1986

1987        /**
1988         * Returns true if this condition was created by the given
1989         * synchronization object
1990         * @return true if owned
1991         */

1992        final boolean isOwnedBy(AbstractQueuedSynchronizer JavaDoc sync) {
1993            return sync == AbstractQueuedSynchronizer.this;
1994        }
1995
1996        /**
1997         * Queries whether any threads are waiting on this condition.
1998         * Implements {@link AbstractQueuedSynchronizer#hasWaiters}
1999         * @return <tt>true</tt> if there are any waiting threads.
2000         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2001         * returns false
2002         */

2003        protected final boolean hasWaiters() {
2004            if (!isHeldExclusively())
2005                throw new IllegalMonitorStateException JavaDoc();
2006            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2007                if (w.waitStatus == Node.CONDITION)
2008                    return true;
2009            }
2010            return false;
2011        }
2012
2013        /**
2014         * Returns an estimate of the number of threads waiting on
2015         * this condition.
2016         * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}
2017         * @return the estimated number of waiting threads.
2018         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2019         * returns false
2020         */

2021        protected final int getWaitQueueLength() {
2022            if (!isHeldExclusively())
2023                throw new IllegalMonitorStateException JavaDoc();
2024            int n = 0;
2025            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2026                if (w.waitStatus == Node.CONDITION)
2027                    ++n;
2028            }
2029            return n;
2030        }
2031
2032        /**
2033         * Returns a collection containing those threads that may be
2034         * waiting on this Condition.
2035         * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}
2036         * @return the collection of threads
2037         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2038         * returns false
2039         */

2040        protected final Collection<Thread JavaDoc> getWaitingThreads() {
2041            if (!isHeldExclusively())
2042                throw new IllegalMonitorStateException JavaDoc();
2043            ArrayList<Thread JavaDoc> list = new ArrayList<Thread JavaDoc>();
2044            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2045                if (w.waitStatus == Node.CONDITION) {
2046                    Thread JavaDoc t = w.thread;
2047                    if (t != null)
2048                        list.add(t);
2049                }
2050            }
2051            return list;
2052        }
2053    }
2054
2055    /**
2056     * Setup to support compareAndSet. We need to natively implement
2057     * this here: For the sake of permitting future enhancements, we
2058     * cannot explicitly subclass AtomicInteger, which would be
2059     * efficient and useful otherwise. So, as the lesser of evils, we
2060     * natively implement using hotspot intrinsics API. And while we
2061     * are at it, we do the same for other CASable fields (which could
2062     * otherwise be done with atomic field updaters).
2063     */

2064    private static final Unsafe unsafe = Unsafe.getUnsafe();
2065    private static final long stateOffset;
2066    private static final long headOffset;
2067    private static final long tailOffset;
2068    private static final long waitStatusOffset;
2069    private static final long nextOffset;
2070
2071    static {
2072        try {
2073            stateOffset = unsafe.objectFieldOffset
2074                (AbstractQueuedSynchronizer JavaDoc.class.getDeclaredField("state"));
2075            headOffset = unsafe.objectFieldOffset
2076                (AbstractQueuedSynchronizer JavaDoc.class.getDeclaredField("head"));
2077            tailOffset = unsafe.objectFieldOffset
2078                (AbstractQueuedSynchronizer JavaDoc.class.getDeclaredField("tail"));
2079            waitStatusOffset = unsafe.objectFieldOffset
2080                (Node.class.getDeclaredField("waitStatus"));
2081            nextOffset = unsafe.objectFieldOffset
2082                (Node.class.getDeclaredField("next"));
2083            
2084        } catch(Exception JavaDoc ex) { throw new Error JavaDoc(ex); }
2085    }
2086
2087    /**
2088     * CAS head field. Used only by enq
2089     */

2090    private final boolean compareAndSetHead(Node update) {
2091        return unsafe.compareAndSwapObject(this, headOffset, null, update);
2092    }
2093    
2094    /**
2095     * CAS tail field. Used only by enq
2096     */

2097    private final boolean compareAndSetTail(Node expect, Node update) {
2098        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
2099    }
2100
2101    /**
2102     * CAS waitStatus field of a node.
2103     */

2104    private final static boolean compareAndSetWaitStatus(Node node,
2105                                                         int expect,
2106                                                         int update) {
2107        return unsafe.compareAndSwapInt(node, waitStatusOffset,
2108                                        expect, update);
2109    }
2110
2111    /**
2112     * CAS next field of a node.
2113     */

2114    private final static boolean compareAndSetNext(Node node,
2115                                                   Node expect,
2116                                                   Node update) {
2117        return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
2118    }
2119
2120}
2121
Popular Tags