2
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
* This code is free software; you can redistribute it and/or modify it
5
* under the terms of the GNU General Public License version 2 only, as
6
* published by the Free Software Foundation. Oracle designates this
7
* particular file as subject to the "Classpath" exception as provided
8
* by Oracle in the LICENSE file that accompanied this code.
10
* This code is distributed in the hope that it will be useful, but WITHOUT
11
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13
* version 2 for more details (a copy is included in the LICENSE file that
14
* accompanied this code).
16
* You should have received a copy of the GNU General Public License version
17
* 2 along with this work; if not, write to the Free Software Foundation,
18
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21
* or visit www.oracle.com if you need additional information or have any
26
* This file is available under and governed by the GNU General Public
27
* License version 2 only, as published by the Free Software Foundation.
28
* However, the following notice accompanied the original version of this
31
* Written by Doug Lea with assistance from members of JCP JSR-166
32
* Expert Group and released to the public domain, as explained at
33
* http://creativecommons.org/publicdomain/zero/1.0/
36
package java.util.concurrent.locks;
38
import java.util.concurrent.*;
39
import java.util.concurrent.atomic.*;
42
* Provides a framework for implementing blocking locks and related
43
* synchronizers (semaphores, events, etc) that rely on
44
* first-in-first-out (FIFO) wait queues. This class is designed to
45
* be a useful basis for most kinds of synchronizers that rely on a
46
* single atomic <tt>int</tt> value to represent state. Subclasses
47
* must define the protected methods that change this state, and which
48
* define what that state means in terms of this object being acquired
49
* or released. Given these, the other methods in this class carry
50
* out all queuing and blocking mechanics. Subclasses can maintain
51
* other state fields, but only the atomically updated <tt>int</tt>
52
* value manipulated using methods {@link #getState}, {@link
53
* #setState} and {@link #compareAndSetState} is tracked with respect
56
* <p>Subclasses should be defined as non-public internal helper
57
* classes that are used to implement the synchronization properties
58
* of their enclosing class. Class
59
* <tt>AbstractQueuedSynchronizer</tt> does not implement any
60
* synchronization interface. Instead it defines methods such as
61
* {@link #acquireInterruptibly} that can be invoked as
62
* appropriate by concrete locks and related synchronizers to
63
* implement their public methods.
65
* <p>This class supports either or both a default <em>exclusive</em>
66
* mode and a <em>shared</em> mode. When acquired in exclusive mode,
67
* attempted acquires by other threads cannot succeed. Shared mode
68
* acquires by multiple threads may (but need not) succeed. This class
69
* does not "understand" these differences except in the
70
* mechanical sense that when a shared mode acquire succeeds, the next
71
* waiting thread (if one exists) must also determine whether it can
72
* acquire as well. Threads waiting in the different modes share the
73
* same FIFO queue. Usually, implementation subclasses support only
74
* one of these modes, but both can come into play for example in a
75
* {@link ReadWriteLock}. Subclasses that support only exclusive or
76
* only shared modes need not define the methods supporting the unused mode.
78
* <p>This class defines a nested {@link ConditionObject} class that
79
* can be used as a {@link Condition} implementation by subclasses
80
* supporting exclusive mode for which method {@link
81
* #isHeldExclusively} reports whether synchronization is exclusively
82
* held with respect to the current thread, method {@link #release}
83
* invoked with the current {@link #getState} value fully releases
84
* this object, and {@link #acquire}, given this saved state value,
85
* eventually restores this object to its previous acquired state. No
86
* <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
87
* condition, so if this constraint cannot be met, do not use it. The
88
* behavior of {@link ConditionObject} depends of course on the
89
* semantics of its synchronizer implementation.
91
* <p>This class provides inspection, instrumentation, and monitoring
92
* methods for the internal queue, as well as similar methods for
93
* condition objects. These can be exported as desired into classes
94
* using an <tt>AbstractQueuedSynchronizer</tt> for their
95
* synchronization mechanics.
97
* <p>Serialization of this class stores only the underlying atomic
98
* integer maintaining state, so deserialized objects have empty
99
* thread queues. Typical subclasses requiring serializability will
100
* define a <tt>readObject</tt> method that restores this to a known
101
* initial state upon deserialization.
105
* <p>To use this class as the basis of a synchronizer, redefine the
106
* following methods, as applicable, by inspecting and/or modifying
107
* the synchronization state using {@link #getState}, {@link
108
* #setState} and/or {@link #compareAndSetState}:
111
* <li> {@link #tryAcquire}
112
* <li> {@link #tryRelease}
113
* <li> {@link #tryAcquireShared}
114
* <li> {@link #tryReleaseShared}
115
* <li> {@link #isHeldExclusively}
118
* Each of these methods by default throws {@link
119
* UnsupportedOperationException}. Implementations of these methods
120
* must be internally thread-safe, and should in general be short and
121
* not block. Defining these methods is the <em>only</em> supported
122
* means of using this class. All other methods are declared
123
* <tt>final</tt> because they cannot be independently varied.
125
* <p>You may also find the inherited methods from {@link
126
* AbstractOwnableSynchronizer} useful to keep track of the thread
127
* owning an exclusive synchronizer. You are encouraged to use them
128
* -- this enables monitoring and diagnostic tools to assist users in
129
* determining which threads hold locks.
131
* <p>Even though this class is based on an internal FIFO queue, it
132
* does not automatically enforce FIFO acquisition policies. The core
133
* of exclusive synchronization takes the form:
137
* while (!tryAcquire(arg)) {
138
* <em>enqueue thread if it is not already queued</em>;
139
* <em>possibly block current thread</em>;
143
* if (tryRelease(arg))
144
* <em>unblock the first queued thread</em>;
147
* (Shared mode is similar but may involve cascading signals.)
149
* <p><a name="barging">Because checks in acquire are invoked before
150
* enqueuing, a newly acquiring thread may <em>barge</em> ahead of
151
* others that are blocked and queued. However, you can, if desired,
152
* define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to
153
* disable barging by internally invoking one or more of the inspection
154
* methods, thereby providing a <em>fair</em> FIFO acquisition order.
155
* In particular, most fair synchronizers can define <tt>tryAcquire</tt>
156
* to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method
157
* specifically designed to be used by fair synchronizers) returns
158
* <tt>true</tt>. Other variations are possible.
160
* <p>Throughput and scalability are generally highest for the
161
* default barging (also known as <em>greedy</em>,
162
* <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
163
* While this is not guaranteed to be fair or starvation-free, earlier
164
* queued threads are allowed to recontend before later queued
165
* threads, and each recontention has an unbiased chance to succeed
166
* against incoming threads. Also, while acquires do not
167
* "spin" in the usual sense, they may perform multiple
168
* invocations of <tt>tryAcquire</tt> interspersed with other
169
* computations before blocking. This gives most of the benefits of
170
* spins when exclusive synchronization is only briefly held, without
171
* most of the liabilities when it isn't. If so desired, you can
172
* augment this by preceding calls to acquire methods with
173
* "fast-path" checks, possibly prechecking {@link #hasContended}
174
* and/or {@link #hasQueuedThreads} to only do so if the synchronizer
175
* is likely not to be contended.
177
* <p>This class provides an efficient and scalable basis for
178
* synchronization in part by specializing its range of use to
179
* synchronizers that can rely on <tt>int</tt> state, acquire, and
180
* release parameters, and an internal FIFO wait queue. When this does
181
* not suffice, you can build synchronizers from a lower level using
182
* {@link java.util.concurrent.atomic atomic} classes, your own custom
183
* {@link java.util.Queue} classes, and {@link LockSupport} blocking
186
* <h3>Usage Examples</h3>
188
* <p>Here is a non-reentrant mutual exclusion lock class that uses
189
* the value zero to represent the unlocked state, and one to
190
* represent the locked state. While a non-reentrant lock
191
* does not strictly require recording of the current owner
192
* thread, this class does so anyway to make usage easier to monitor.
193
* It also supports conditions and exposes
194
* one of the instrumentation methods:
197
* class Mutex implements Lock, java.io.Serializable {
199
* // Our internal helper class
200
* private static class Sync extends AbstractQueuedSynchronizer {
201
* // Report whether in locked state
202
* protected boolean isHeldExclusively() {
203
* return getState() == 1;
206
* // Acquire the lock if state is zero
207
* public boolean tryAcquire(int acquires) {
208
* assert acquires == 1; // Otherwise unused
209
* if (compareAndSetState(0, 1)) {
210
* setExclusiveOwnerThread(Thread.currentThread());
216
* // Release the lock by setting state to zero
217
* protected boolean tryRelease(int releases) {
218
* assert releases == 1; // Otherwise unused
219
* if (getState() == 0) throw new IllegalMonitorStateException();
220
* setExclusiveOwnerThread(null);
225
* // Provide a Condition
226
* Condition newCondition() { return new ConditionObject(); }
228
* // Deserialize properly
229
* private void readObject(ObjectInputStream s)
230
* throws IOException, ClassNotFoundException {
231
* s.defaultReadObject();
232
* setState(0); // reset to unlocked state
236
* // The sync object does all the hard work. We just forward to it.
237
* private final Sync sync = new Sync();
239
* public void lock() { sync.acquire(1); }
240
* public boolean tryLock() { return sync.tryAcquire(1); }
241
* public void unlock() { sync.release(1); }
242
* public Condition newCondition() { return sync.newCondition(); }
243
* public boolean isLocked() { return sync.isHeldExclusively(); }
244
* public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
245
* public void lockInterruptibly() throws InterruptedException {
246
* sync.acquireInterruptibly(1);
248
* public boolean tryLock(long timeout, TimeUnit unit)
249
* throws InterruptedException {
250
* return sync.tryAcquireNanos(1, unit.toNanos(timeout));
255
* <p>Here is a latch class that is like a {@link CountDownLatch}
256
* except that it only requires a single <tt>signal</tt> to
257
* fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
258
* acquire and release methods.
261
* class BooleanLatch {
263
* private static class Sync extends AbstractQueuedSynchronizer {
264
* boolean isSignalled() { return getState() != 0; }
266
* protected int tryAcquireShared(int ignore) {
267
* return isSignalled() ? 1 : -1;
270
* protected boolean tryReleaseShared(int ignore) {
276
* private final Sync sync = new Sync();
277
* public boolean isSignalled() { return sync.isSignalled(); }
278
* public void signal() { sync.releaseShared(1); }
279
* public void await() throws InterruptedException {
280
* sync.acquireSharedInterruptibly(1);
288
public abstract class AbstractQueuedSynchronizer
289
extends AbstractOwnableSynchronizer
290
implements java.io.Serializable {
292
private static final long serialVersionUID = 7373984972572414691L;
295
* Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
296
* with initial synchronization state of zero.
298
protected AbstractQueuedSynchronizer() { }
301
* Wait queue node class.
303
* <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
304
* Hagersten) lock queue. CLH locks are normally used for
305
* spinlocks. We instead use them for blocking synchronizers, but
306
* use the same basic tactic of holding some of the control
307
* information about a thread in the predecessor of its node. A
308
* "status" field in each node keeps track of whether a thread
309
* should block. A node is signalled when its predecessor
310
* releases. Each node of the queue otherwise serves as a
311
* specific-notification-style monitor holding a single waiting
312
* thread. The status field does NOT control whether threads are
313
* granted locks etc though. A thread may try to acquire if it is
314
* first in the queue. But being first does not guarantee success;
315
* it only gives the right to contend. So the currently released
316
* contender thread may need to rewait.
318
* <p>To enqueue into a CLH lock, you atomically splice it in as new
319
* tail. To dequeue, you just set the head field.
321
* +------+ prev +-----+ +-----+
322
* head | | <---- | | <---- | | tail
323
* +------+ +-----+ +-----+
326
* <p>Insertion into a CLH queue requires only a single atomic
327
* operation on "tail", so there is a simple atomic point of
328
* demarcation from unqueued to queued. Similarly, dequeing
329
* involves only updating the "head". However, it takes a bit
330
* more work for nodes to determine who their successors are,
331
* in part to deal with possible cancellation due to timeouts
334
* <p>The "prev" links (not used in original CLH locks), are mainly
335
* needed to handle cancellation. If a node is cancelled, its
336
* successor is (normally) relinked to a non-cancelled
337
* predecessor. For explanation of similar mechanics in the case
338
* of spin locks, see the papers by Scott and Scherer at
339
* http://www.cs.rochester.edu/u/scott/synchronization/
341
* <p>We also use "next" links to implement blocking mechanics.
342
* The thread id for each node is kept in its own node, so a
343
* predecessor signals the next node to wake up by traversing
344
* next link to determine which thread it is. Determination of
345
* successor must avoid races with newly queued nodes to set
346
* the "next" fields of their predecessors. This is solved
347
* when necessary by checking backwards from the atomically
348
* updated "tail" when a node's successor appears to be null.
349
* (Or, said differently, the next-links are an optimization
350
* so that we don't usually need a backward scan.)
352
* <p>Cancellation introduces some conservatism to the basic
353
* algorithms. Since we must poll for cancellation of other
354
* nodes, we can miss noticing whether a cancelled node is
355
* ahead or behind us. This is dealt with by always unparking
356
* successors upon cancellation, allowing them to stabilize on
357
* a new predecessor, unless we can identify an uncancelled
358
* predecessor who will carry this responsibility.
360
* <p>CLH queues need a dummy header node to get started. But
361
* we don't create them on construction, because it would be wasted
362
* effort if there is never contention. Instead, the node
363
* is constructed and head and tail pointers are set upon first
366
* <p>Threads waiting on Conditions use the same nodes, but
367
* use an additional link. Conditions only need to link nodes
368
* in simple (non-concurrent) linked queues because they are
369
* only accessed when exclusively held. Upon await, a node is
370
* inserted into a condition queue. Upon signal, the node is
371
* transferred to the main queue. A special value of status
372
* field is used to mark which queue a node is on.
374
* <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
375
* Scherer and Michael Scott, along with members of JSR-166
376
* expert group, for helpful ideas, discussions, and critiques
377
* on the design of this class.
379
static final class Node {
380
static final AtomicReferenceFieldUpdater<Node, Node> nextUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "next");
381
/** Marker to indicate a node is waiting in shared mode */
382
static final Node SHARED = new Node();
383
/** Marker to indicate a node is waiting in exclusive mode */
384
static final Node EXCLUSIVE = null;
386
/** waitStatus value to indicate thread has cancelled */
387
static final int CANCELLED = 1;
388
/** waitStatus value to indicate successor's thread needs unparking */
389
static final int SIGNAL = -1;
390
/** waitStatus value to indicate thread is waiting on condition */
391
static final int CONDITION = -2;
393
* waitStatus value to indicate the next acquireShared should
394
* unconditionally propagate
396
static final int PROPAGATE = -3;
399
* Status field, taking on only the values:
400
* SIGNAL: The successor of this node is (or will soon be)
401
* blocked (via park), so the current node must
402
* unpark its successor when it releases or
403
* cancels. To avoid races, acquire methods must
404
* first indicate they need a signal,
405
* then retry the atomic acquire, and then,
407
* CANCELLED: This node is cancelled due to timeout or interrupt.
408
* Nodes never leave this state. In particular,
409
* a thread with cancelled node never again blocks.
410
* CONDITION: This node is currently on a condition queue.
411
* It will not be used as a sync queue node
412
* until transferred, at which time the status
413
* will be set to 0. (Use of this value here has
414
* nothing to do with the other uses of the
415
* field, but simplifies mechanics.)
416
* PROPAGATE: A releaseShared should be propagated to other
417
* nodes. This is set (for head node only) in
418
* doReleaseShared to ensure propagation
419
* continues, even if other operations have
421
* 0: None of the above
423
* The values are arranged numerically to simplify use.
424
* Non-negative values mean that a node doesn't need to
425
* signal. So, most code doesn't need to check for particular
426
* values, just for sign.
428
* The field is initialized to 0 for normal sync nodes, and
429
* CONDITION for condition nodes. It is modified using CAS
430
* (or when possible, unconditional volatile writes).
432
volatile int waitStatus;
435
* Link to predecessor node that current node/thread relies on
436
* for checking waitStatus. Assigned during enqueing, and nulled
437
* out (for sake of GC) only upon dequeuing. Also, upon
438
* cancellation of a predecessor, we short-circuit while
439
* finding a non-cancelled one, which will always exist
440
* because the head node is never cancelled: A node becomes
441
* head only as a result of successful acquire. A
442
* cancelled thread never succeeds in acquiring, and a thread only
443
* cancels itself, not any other node.
448
* Link to the successor node that the current node/thread
449
* unparks upon release. Assigned during enqueuing, adjusted
450
* when bypassing cancelled predecessors, and nulled out (for
451
* sake of GC) when dequeued. The enq operation does not
452
* assign next field of a predecessor until after attachment,
453
* so seeing a null next field does not necessarily mean that
454
* node is at end of queue. However, if a next field appears
455
* to be null, we can scan prev's from the tail to
456
* double-check. The next field of cancelled nodes is set to
457
* point to the node itself instead of null, to make life
458
* easier for isOnSyncQueue.
463
* The thread that enqueued this node. Initialized on
464
* construction and nulled out after use.
466
volatile Thread thread;
469
* Link to next node waiting on condition, or the special
470
* value SHARED. Because condition queues are accessed only
471
* when holding in exclusive mode, we just need a simple
472
* linked queue to hold nodes while they are waiting on
473
* conditions. They are then transferred to the queue to
474
* re-acquire. And because conditions can only be exclusive,
475
* we save a field by using special value to indicate shared
481
* Returns true if node is waiting in shared mode
483
final boolean isShared() {
484
return nextWaiter == SHARED;
488
* Returns previous node, or throws NullPointerException if null.
489
* Use when predecessor cannot be null. The null check could
490
* be elided, but is present to help the VM.
492
* @return the predecessor of this node
494
final Node predecessor() throws NullPointerException {
497
throw new NullPointerException();
502
Node() { // Used to establish initial head or SHARED marker
505
Node(Thread thread, Node mode) { // Used by addWaiter
506
this.nextWaiter = mode;
507
this.thread = thread;
510
Node(Thread thread, int waitStatus) { // Used by Condition
511
this.waitStatus = waitStatus;
512
this.thread = thread;
517
* Head of the wait queue, lazily initialized. Except for
518
* initialization, it is modified only via method setHead. Note:
519
* If head exists, its waitStatus is guaranteed not to be
522
private transient volatile Node head;
525
* Tail of the wait queue, lazily initialized. Modified only via
526
* method enq to add new wait node.
528
private transient volatile Node tail;
531
* The synchronization state.
533
private volatile int state;
536
* Returns the current value of synchronization state.
537
* This operation has memory semantics of a <tt>volatile</tt> read.
538
* @return current state value
540
protected final int getState() {
545
* Sets the value of synchronization state.
546
* This operation has memory semantics of a <tt>volatile</tt> write.
547
* @param newState the new state value
549
protected final void setState(int newState) {
554
* Atomically sets synchronization state to the given updated
555
* value if the current state value equals the expected value.
556
* This operation has memory semantics of a <tt>volatile</tt> read
559
* @param expect the expected value
560
* @param update the new value
561
* @return true if successful. False return indicates that the actual
562
* value was not equal to the expected value.
564
protected final native boolean compareAndSetState(int expect, int update); // implemented in map.xml
569
* The number of nanoseconds for which it is faster to spin
570
* rather than to use timed park. A rough estimate suffices
571
* to improve responsiveness with very short timeouts.
573
static final long spinForTimeoutThreshold = 1000L;
576
* Inserts node into queue, initializing if necessary. See picture above.
577
* @param node the node to insert
578
* @return node's predecessor
580
private Node enq(final Node node) {
583
if (t == null) { // Must initialize
584
if (compareAndSetHead(new Node()))
588
if (compareAndSetTail(t, node)) {
597
* Creates and enqueues node for current thread and given mode.
599
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
600
* @return the new node
602
private Node addWaiter(Node mode) {
603
Node node = new Node(Thread.currentThread(), mode);
604
// Try the fast path of enq; backup to full enq on failure
608
if (compareAndSetTail(pred, node)) {
618
* Sets head of queue to be node, thus dequeuing. Called only by
619
* acquire methods. Also nulls out unused fields for sake of GC
620
* and to suppress unnecessary signals and traversals.
622
* @param node the node
624
private void setHead(Node node) {
631
* Wakes up node's successor, if one exists.
633
* @param node the node
635
private void unparkSuccessor(Node node) {
637
* If status is negative (i.e., possibly needing signal) try
638
* to clear in anticipation of signalling. It is OK if this
639
* fails or if status is changed by waiting thread.
641
int ws = node.waitStatus;
643
compareAndSetWaitStatus(node, ws, 0);
646
* Thread to unpark is held in successor, which is normally
647
* just the next node. But if cancelled or apparently null,
648
* traverse backwards from tail to find the actual
649
* non-cancelled successor.
652
if (s == null || s.waitStatus > 0) {
654
for (Node t = tail; t != null && t != node; t = t.prev)
655
if (t.waitStatus <= 0)
659
LockSupport.unpark(s.thread);
663
* Release action for shared mode -- signal successor and ensure
664
* propagation. (Note: For exclusive mode, release just amounts
665
* to calling unparkSuccessor of head if it needs signal.)
667
private void doReleaseShared() {
669
* Ensure that a release propagates, even if there are other
670
* in-progress acquires/releases. This proceeds in the usual
671
* way of trying to unparkSuccessor of head if it needs
672
* signal. But if it does not, status is set to PROPAGATE to
673
* ensure that upon release, propagation continues.
674
* Additionally, we must loop in case a new node is added
675
* while we are doing this. Also, unlike other uses of
676
* unparkSuccessor, we need to know if CAS to reset status
677
* fails, if so rechecking.
681
if (h != null && h != tail) {
682
int ws = h.waitStatus;
683
if (ws == Node.SIGNAL) {
684
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
685
continue; // loop to recheck cases
689
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
690
continue; // loop on failed CAS
692
if (h == head) // loop if head changed
698
* Sets head of queue, and checks if successor may be waiting
699
* in shared mode, if so propagating if either propagate > 0 or
700
* PROPAGATE status was set.
702
* @param node the node
703
* @param propagate the return value from a tryAcquireShared
705
private void setHeadAndPropagate(Node node, int propagate) {
706
Node h = head; // Record old head for check below
709
* Try to signal next queued node if:
710
* Propagation was indicated by caller,
711
* or was recorded (as h.waitStatus) by a previous operation
712
* (note: this uses sign-check of waitStatus because
713
* PROPAGATE status may transition to SIGNAL.)
715
* The next node is waiting in shared mode,
716
* or we don't know, because it appears null
718
* The conservatism in both of these checks may cause
719
* unnecessary wake-ups, but only when there are multiple
720
* racing acquires/releases, so most need signals now or soon
723
if (propagate > 0 || h == null || h.waitStatus < 0) {
725
if (s == null || s.isShared())
730
// Utilities for various versions of acquire
733
* Cancels an ongoing attempt to acquire.
735
* @param node the node
737
private void cancelAcquire(Node node) {
738
// Ignore if node doesn't exist
744
// Skip cancelled predecessors
745
Node pred = node.prev;
746
while (pred.waitStatus > 0)
747
node.prev = pred = pred.prev;
749
// predNext is the apparent node to unsplice. CASes below will
750
// fail if not, in which case, we lost race vs another cancel
751
// or signal, so no further action is necessary.
752
Node predNext = pred.next;
754
// Can use unconditional write instead of CAS here.
755
// After this atomic step, other Nodes can skip past us.
756
// Before, we are free of interference from other threads.
757
node.waitStatus = Node.CANCELLED;
759
// If we are the tail, remove ourselves.
760
if (node == tail && compareAndSetTail(node, pred)) {
761
compareAndSetNext(pred, predNext, null);
763
// If successor needs signal, try to set pred's next-link
764
// so it will get one. Otherwise wake it up to propagate.
767
((ws = pred.waitStatus) == Node.SIGNAL ||
768
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
769
pred.thread != null) {
770
Node next = node.next;
771
if (next != null && next.waitStatus <= 0)
772
compareAndSetNext(pred, predNext, next);
774
unparkSuccessor(node);
777
node.next = node; // help GC
782
* Checks and updates status for a node that failed to acquire.
783
* Returns true if thread should block. This is the main signal
784
* control in all acquire loops. Requires that pred == node.prev
786
* @param pred node's predecessor holding status
787
* @param node the node
788
* @return {@code true} if thread should block
790
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
791
int ws = pred.waitStatus;
792
if (ws == Node.SIGNAL)
794
* This node has already set status asking a release
795
* to signal it, so it can safely park.
800
* Predecessor was cancelled. Skip over predecessors and
804
node.prev = pred = pred.prev;
805
} while (pred.waitStatus > 0);
809
* waitStatus must be 0 or PROPAGATE. Indicate that we
810
* need a signal, but don't park yet. Caller will need to
811
* retry to make sure it cannot acquire before parking.
813
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
819
* Convenience method to interrupt current thread.
821
private static void selfInterrupt() {
822
Thread.currentThread().interrupt();
826
* Convenience method to park and then check if interrupted
828
* @return {@code true} if interrupted
830
private final boolean parkAndCheckInterrupt() {
831
LockSupport.park(this);
832
return Thread.interrupted();
836
* Various flavors of acquire, varying in exclusive/shared and
837
* control modes. Each is mostly the same, but annoyingly
838
* different. Only a little bit of factoring is possible due to
839
* interactions of exception mechanics (including ensuring that we
840
* cancel if tryAcquire throws exception) and other control, at
841
* least not without hurting performance too much.
845
* Acquires in exclusive uninterruptible mode for thread already in
846
* queue. Used by condition wait methods as well as acquire.
848
* @param node the node
849
* @param arg the acquire argument
850
* @return {@code true} if interrupted while waiting
852
final boolean acquireQueued(final Node node, int arg) {
853
boolean failed = true;
855
boolean interrupted = false;
857
final Node p = node.predecessor();
858
if (p == head && tryAcquire(arg)) {
860
p.next = null; // help GC
864
if (shouldParkAfterFailedAcquire(p, node) &&
865
parkAndCheckInterrupt())
875
* Acquires in exclusive interruptible mode.
876
* @param arg the acquire argument
878
private void doAcquireInterruptibly(int arg)
879
throws InterruptedException {
880
final Node node = addWaiter(Node.EXCLUSIVE);
881
boolean failed = true;
884
final Node p = node.predecessor();
885
if (p == head && tryAcquire(arg)) {
887
p.next = null; // help GC
891
if (shouldParkAfterFailedAcquire(p, node) &&
892
parkAndCheckInterrupt())
893
throw new InterruptedException();
902
* Acquires in exclusive timed mode.
904
* @param arg the acquire argument
905
* @param nanosTimeout max wait time
906
* @return {@code true} if acquired
908
private boolean doAcquireNanos(int arg, long nanosTimeout)
909
throws InterruptedException {
910
long lastTime = System.nanoTime();
911
final Node node = addWaiter(Node.EXCLUSIVE);
912
boolean failed = true;
915
final Node p = node.predecessor();
916
if (p == head && tryAcquire(arg)) {
918
p.next = null; // help GC
922
if (nanosTimeout <= 0)
924
if (shouldParkAfterFailedAcquire(p, node) &&
925
nanosTimeout > spinForTimeoutThreshold)
926
LockSupport.parkNanos(this, nanosTimeout);
927
long now = System.nanoTime();
928
nanosTimeout -= now - lastTime;
930
if (Thread.interrupted())
931
throw new InterruptedException();
940
* Acquires in shared uninterruptible mode.
941
* @param arg the acquire argument
943
private void doAcquireShared(int arg) {
944
final Node node = addWaiter(Node.SHARED);
945
boolean failed = true;
947
boolean interrupted = false;
949
final Node p = node.predecessor();
951
int r = tryAcquireShared(arg);
953
setHeadAndPropagate(node, r);
954
p.next = null; // help GC
961
if (shouldParkAfterFailedAcquire(p, node) &&
962
parkAndCheckInterrupt())
972
* Acquires in shared interruptible mode.
973
* @param arg the acquire argument
975
private void doAcquireSharedInterruptibly(int arg)
976
throws InterruptedException {
977
final Node node = addWaiter(Node.SHARED);
978
boolean failed = true;
981
final Node p = node.predecessor();
983
int r = tryAcquireShared(arg);
985
setHeadAndPropagate(node, r);
986
p.next = null; // help GC
991
if (shouldParkAfterFailedAcquire(p, node) &&
992
parkAndCheckInterrupt())
993
throw new InterruptedException();
1002
* Acquires in shared timed mode.
1004
* @param arg the acquire argument
1005
* @param nanosTimeout max wait time
1006
* @return {@code true} if acquired
1008
private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
1009
throws InterruptedException {
1011
long lastTime = System.nanoTime();
1012
final Node node = addWaiter(Node.SHARED);
1013
boolean failed = true;
1016
final Node p = node.predecessor();
1018
int r = tryAcquireShared(arg);
1020
setHeadAndPropagate(node, r);
1021
p.next = null; // help GC
1026
if (nanosTimeout <= 0)
1028
if (shouldParkAfterFailedAcquire(p, node) &&
1029
nanosTimeout > spinForTimeoutThreshold)
1030
LockSupport.parkNanos(this, nanosTimeout);
1031
long now = System.nanoTime();
1032
nanosTimeout -= now - lastTime;
1034
if (Thread.interrupted())
1035
throw new InterruptedException();
1039
cancelAcquire(node);
1043
// Main exported methods
1046
* Attempts to acquire in exclusive mode. This method should query
1047
* if the state of the object permits it to be acquired in the
1048
* exclusive mode, and if so to acquire it.
1050
* <p>This method is always invoked by the thread performing
1051
* acquire. If this method reports failure, the acquire method
1052
* may queue the thread, if it is not already queued, until it is
1053
* signalled by a release from some other thread. This can be used
1054
* to implement method {@link Lock#tryLock()}.
1057
* implementation throws {@link UnsupportedOperationException}.
1059
* @param arg the acquire argument. This value is always the one
1060
* passed to an acquire method, or is the value saved on entry
1061
* to a condition wait. The value is otherwise uninterpreted
1062
* and can represent anything you like.
1063
* @return {@code true} if successful. Upon success, this object has
1065
* @throws IllegalMonitorStateException if acquiring would place this
1066
* synchronizer in an illegal state. This exception must be
1067
* thrown in a consistent fashion for synchronization to work
1069
* @throws UnsupportedOperationException if exclusive mode is not supported
1071
protected boolean tryAcquire(int arg) {
1072
throw new UnsupportedOperationException();
1076
* Attempts to set the state to reflect a release in exclusive
1079
* <p>This method is always invoked by the thread performing release.
1081
* <p>The default implementation throws
1082
* {@link UnsupportedOperationException}.
1084
* @param arg the release argument. This value is always the one
1085
* passed to a release method, or the current state value upon
1086
* entry to a condition wait. The value is otherwise
1087
* uninterpreted and can represent anything you like.
1088
* @return {@code true} if this object is now in a fully released
1089
* state, so that any waiting threads may attempt to acquire;
1090
* and {@code false} otherwise.
1091
* @throws IllegalMonitorStateException if releasing would place this
1092
* synchronizer in an illegal state. This exception must be
1093
* thrown in a consistent fashion for synchronization to work
1095
* @throws UnsupportedOperationException if exclusive mode is not supported
1097
protected boolean tryRelease(int arg) {
1098
throw new UnsupportedOperationException();
1102
* Attempts to acquire in shared mode. This method should query if
1103
* the state of the object permits it to be acquired in the shared
1104
* mode, and if so to acquire it.
1106
* <p>This method is always invoked by the thread performing
1107
* acquire. If this method reports failure, the acquire method
1108
* may queue the thread, if it is not already queued, until it is
1109
* signalled by a release from some other thread.
1111
* <p>The default implementation throws {@link
1112
* UnsupportedOperationException}.
1114
* @param arg the acquire argument. This value is always the one
1115
* passed to an acquire method, or is the value saved on entry
1116
* to a condition wait. The value is otherwise uninterpreted
1117
* and can represent anything you like.
1118
* @return a negative value on failure; zero if acquisition in shared
1119
* mode succeeded but no subsequent shared-mode acquire can
1120
* succeed; and a positive value if acquisition in shared
1121
* mode succeeded and subsequent shared-mode acquires might
1122
* also succeed, in which case a subsequent waiting thread
1123
* must check availability. (Support for three different
1124
* return values enables this method to be used in contexts
1125
* where acquires only sometimes act exclusively.) Upon
1126
* success, this object has been acquired.
1127
* @throws IllegalMonitorStateException if acquiring would place this
1128
* synchronizer in an illegal state. This exception must be
1129
* thrown in a consistent fashion for synchronization to work
1131
* @throws UnsupportedOperationException if shared mode is not supported
1133
protected int tryAcquireShared(int arg) {
1134
throw new UnsupportedOperationException();
1138
* Attempts to set the state to reflect a release in shared mode.
1140
* <p>This method is always invoked by the thread performing release.
1142
* <p>The default implementation throws
1143
* {@link UnsupportedOperationException}.
1145
* @param arg the release argument. This value is always the one
1146
* passed to a release method, or the current state value upon
1147
* entry to a condition wait. The value is otherwise
1148
* uninterpreted and can represent anything you like.
1149
* @return {@code true} if this release of shared mode may permit a
1150
* waiting acquire (shared or exclusive) to succeed; and
1151
* {@code false} otherwise
1152
* @throws IllegalMonitorStateException if releasing would place this
1153
* synchronizer in an illegal state. This exception must be
1154
* thrown in a consistent fashion for synchronization to work
1156
* @throws UnsupportedOperationException if shared mode is not supported
1158
protected boolean tryReleaseShared(int arg) {
1159
throw new UnsupportedOperationException();
1163
* Returns {@code true} if synchronization is held exclusively with
1164
* respect to the current (calling) thread. This method is invoked
1165
* upon each call to a non-waiting {@link ConditionObject} method.
1166
* (Waiting methods instead invoke {@link #release}.)
1168
* <p>The default implementation throws {@link
1169
* UnsupportedOperationException}. This method is invoked
1170
* internally only within {@link ConditionObject} methods, so need
1171
* not be defined if conditions are not used.
1173
* @return {@code true} if synchronization is held exclusively;
1174
* {@code false} otherwise
1175
* @throws UnsupportedOperationException if conditions are not supported
1177
protected boolean isHeldExclusively() {
1178
throw new UnsupportedOperationException();
1182
* Acquires in exclusive mode, ignoring interrupts. Implemented
1183
* by invoking at least once {@link #tryAcquire},
1184
* returning on success. Otherwise the thread is queued, possibly
1185
* repeatedly blocking and unblocking, invoking {@link
1186
* #tryAcquire} until success. This method can be used
1187
* to implement method {@link Lock#lock}.
1189
* @param arg the acquire argument. This value is conveyed to
1190
* {@link #tryAcquire} but is otherwise uninterpreted and
1191
* can represent anything you like.
1193
public final void acquire(int arg) {
1194
if (!tryAcquire(arg) &&
1195
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
1200
* Acquires in exclusive mode, aborting if interrupted.
1201
* Implemented by first checking interrupt status, then invoking
1202
* at least once {@link #tryAcquire}, returning on
1203
* success. Otherwise the thread is queued, possibly repeatedly
1204
* blocking and unblocking, invoking {@link #tryAcquire}
1205
* until success or the thread is interrupted. This method can be
1206
* used to implement method {@link Lock#lockInterruptibly}.
1208
* @param arg the acquire argument. This value is conveyed to
1209
* {@link #tryAcquire} but is otherwise uninterpreted and
1210
* can represent anything you like.
1211
* @throws InterruptedException if the current thread is interrupted
1213
public final void acquireInterruptibly(int arg)
1214
throws InterruptedException {
1215
if (Thread.interrupted())
1216
throw new InterruptedException();
1217
if (!tryAcquire(arg))
1218
doAcquireInterruptibly(arg);
1222
* Attempts to acquire in exclusive mode, aborting if interrupted,
1223
* and failing if the given timeout elapses. Implemented by first
1224
* checking interrupt status, then invoking at least once {@link
1225
* #tryAcquire}, returning on success. Otherwise, the thread is
1226
* queued, possibly repeatedly blocking and unblocking, invoking
1227
* {@link #tryAcquire} until success or the thread is interrupted
1228
* or the timeout elapses. This method can be used to implement
1229
* method {@link Lock#tryLock(long, TimeUnit)}.
1231
* @param arg the acquire argument. This value is conveyed to
1232
* {@link #tryAcquire} but is otherwise uninterpreted and
1233
* can represent anything you like.
1234
* @param nanosTimeout the maximum number of nanoseconds to wait
1235
* @return {@code true} if acquired; {@code false} if timed out
1236
* @throws InterruptedException if the current thread is interrupted
1238
public final boolean tryAcquireNanos(int arg, long nanosTimeout)
1239
throws InterruptedException {
1240
if (Thread.interrupted())
1241
throw new InterruptedException();
1242
return tryAcquire(arg) ||
1243
doAcquireNanos(arg, nanosTimeout);
1247
* Releases in exclusive mode. Implemented by unblocking one or
1248
* more threads if {@link #tryRelease} returns true.
1249
* This method can be used to implement method {@link Lock#unlock}.
1251
* @param arg the release argument. This value is conveyed to
1252
* {@link #tryRelease} but is otherwise uninterpreted and
1253
* can represent anything you like.
1254
* @return the value returned from {@link #tryRelease}
1256
public final boolean release(int arg) {
1257
if (tryRelease(arg)) {
1259
if (h != null && h.waitStatus != 0)
1267
* Acquires in shared mode, ignoring interrupts. Implemented by
1268
* first invoking at least once {@link #tryAcquireShared},
1269
* returning on success. Otherwise the thread is queued, possibly
1270
* repeatedly blocking and unblocking, invoking {@link
1271
* #tryAcquireShared} until success.
1273
* @param arg the acquire argument. This value is conveyed to
1274
* {@link #tryAcquireShared} but is otherwise uninterpreted
1275
* and can represent anything you like.
1277
public final void acquireShared(int arg) {
1278
if (tryAcquireShared(arg) < 0)
1279
doAcquireShared(arg);
1283
* Acquires in shared mode, aborting if interrupted. Implemented
1284
* by first checking interrupt status, then invoking at least once
1285
* {@link #tryAcquireShared}, returning on success. Otherwise the
1286
* thread is queued, possibly repeatedly blocking and unblocking,
1287
* invoking {@link #tryAcquireShared} until success or the thread
1289
* @param arg the acquire argument
1290
* This value is conveyed to {@link #tryAcquireShared} but is
1291
* otherwise uninterpreted and can represent anything
1293
* @throws InterruptedException if the current thread is interrupted
1295
public final void acquireSharedInterruptibly(int arg)
1296
throws InterruptedException {
1297
if (Thread.interrupted())
1298
throw new InterruptedException();
1299
if (tryAcquireShared(arg) < 0)
1300
doAcquireSharedInterruptibly(arg);
1304
* Attempts to acquire in shared mode, aborting if interrupted, and
1305
* failing if the given timeout elapses. Implemented by first
1306
* checking interrupt status, then invoking at least once {@link
1307
* #tryAcquireShared}, returning on success. Otherwise, the
1308
* thread is queued, possibly repeatedly blocking and unblocking,
1309
* invoking {@link #tryAcquireShared} until success or the thread
1310
* is interrupted or the timeout elapses.
1312
* @param arg the acquire argument. This value is conveyed to
1313
* {@link #tryAcquireShared} but is otherwise uninterpreted
1314
* and can represent anything you like.
1315
* @param nanosTimeout the maximum number of nanoseconds to wait
1316
* @return {@code true} if acquired; {@code false} if timed out
1317
* @throws InterruptedException if the current thread is interrupted
1319
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
1320
throws InterruptedException {
1321
if (Thread.interrupted())
1322
throw new InterruptedException();
1323
return tryAcquireShared(arg) >= 0 ||
1324
doAcquireSharedNanos(arg, nanosTimeout);
1328
* Releases in shared mode. Implemented by unblocking one or more
1329
* threads if {@link #tryReleaseShared} returns true.
1331
* @param arg the release argument. This value is conveyed to
1332
* {@link #tryReleaseShared} but is otherwise uninterpreted
1333
* and can represent anything you like.
1334
* @return the value returned from {@link #tryReleaseShared}
1336
public final boolean releaseShared(int arg) {
1337
if (tryReleaseShared(arg)) {
1344
// Queue inspection methods
1347
* Queries whether any threads are waiting to acquire. Note that
1348
* because cancellations due to interrupts and timeouts may occur
1349
* at any time, a {@code true} return does not guarantee that any
1350
* other thread will ever acquire.
1352
* <p>In this implementation, this operation returns in
1355
* @return {@code true} if there may be other threads waiting to acquire
1357
public final boolean hasQueuedThreads() {
1358
return head != tail;
1362
* Queries whether any threads have ever contended to acquire this
1363
* synchronizer; that is if an acquire method has ever blocked.
1365
* <p>In this implementation, this operation returns in
1368
* @return {@code true} if there has ever been contention
1370
public final boolean hasContended() {
1371
return head != null;
1375
* Returns the first (longest-waiting) thread in the queue, or
1376
* {@code null} if no threads are currently queued.
1378
* <p>In this implementation, this operation normally returns in
1379
* constant time, but may iterate upon contention if other threads are
1380
* concurrently modifying the queue.
1382
* @return the first (longest-waiting) thread in the queue, or
1383
* {@code null} if no threads are currently queued
1385
public final Thread getFirstQueuedThread() {
1386
// handle only fast path, else relay
1387
return (head == tail) ? null : fullGetFirstQueuedThread();
1391
* Version of getFirstQueuedThread called when fastpath fails
1393
private Thread fullGetFirstQueuedThread() {
1395
* The first node is normally head.next. Try to get its
1396
* thread field, ensuring consistent reads: If thread
1397
* field is nulled out or s.prev is no longer head, then
1398
* some other thread(s) concurrently performed setHead in
1399
* between some of our reads. We try this twice before
1400
* resorting to traversal.
1404
if (((h = head) != null && (s = h.next) != null &&
1405
s.prev == head && (st = s.thread) != null) ||
1406
((h = head) != null && (s = h.next) != null &&
1407
s.prev == head && (st = s.thread) != null))
1411
* Head's next field might not have been set yet, or may have
1412
* been unset after setHead. So we must check to see if tail
1413
* is actually first node. If not, we continue on, safely
1414
* traversing from tail back to head to find first,
1415
* guaranteeing termination.
1419
Thread firstThread = null;
1420
while (t != null && t != head) {
1421
Thread tt = t.thread;
1430
* Returns true if the given thread is currently queued.
1432
* <p>This implementation traverses the queue to determine
1433
* presence of the given thread.
1435
* @param thread the thread
1436
* @return {@code true} if the given thread is on the queue
1437
* @throws NullPointerException if the thread is null
1439
public final boolean isQueued(Thread thread) {
1441
throw new NullPointerException();
1442
for (Node p = tail; p != null; p = p.prev)
1443
if (p.thread == thread)
1449
* Returns {@code true} if the apparent first queued thread, if one
1450
* exists, is waiting in exclusive mode. If this method returns
1451
* {@code true}, and the current thread is attempting to acquire in
1452
* shared mode (that is, this method is invoked from {@link
1453
* #tryAcquireShared}) then it is guaranteed that the current thread
1454
* is not the first queued thread. Used only as a heuristic in
1455
* ReentrantReadWriteLock.
1457
final boolean apparentlyFirstQueuedIsExclusive() {
1459
return (h = head) != null &&
1460
(s = h.next) != null &&
1466
* Queries whether any threads have been waiting to acquire longer
1467
* than the current thread.
1469
* <p>An invocation of this method is equivalent to (but may be
1470
* more efficient than):
1472
* getFirstQueuedThread() != Thread.currentThread() &&
1473
* hasQueuedThreads()}</pre>
1475
* <p>Note that because cancellations due to interrupts and
1476
* timeouts may occur at any time, a {@code true} return does not
1477
* guarantee that some other thread will acquire before the current
1478
* thread. Likewise, it is possible for another thread to win a
1479
* race to enqueue after this method has returned {@code false},
1480
* due to the queue being empty.
1482
* <p>This method is designed to be used by a fair synchronizer to
1483
* avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
1484
* Such a synchronizer's {@link #tryAcquire} method should return
1485
* {@code false}, and its {@link #tryAcquireShared} method should
1486
* return a negative value, if this method returns {@code true}
1487
* (unless this is a reentrant acquire). For example, the {@code
1488
* tryAcquire} method for a fair, reentrant, exclusive mode
1489
* synchronizer might look like this:
1492
* protected boolean tryAcquire(int arg) {
1493
* if (isHeldExclusively()) {
1494
* // A reentrant acquire; increment hold count
1496
* } else if (hasQueuedPredecessors()) {
1499
* // try to acquire normally
1503
* @return {@code true} if there is a queued thread preceding the
1504
* current thread, and {@code false} if the current thread
1505
* is at the head of the queue or the queue is empty
1508
public final boolean hasQueuedPredecessors() {
1509
// The correctness of this depends on head being initialized
1510
// before tail and on head.next being accurate if the current
1511
// thread is first in queue.
1512
Node t = tail; // Read fields in reverse initialization order
1516
((s = h.next) == null || s.thread != Thread.currentThread());
1520
// Instrumentation and monitoring methods
1523
* Returns an estimate of the number of threads waiting to
1524
* acquire. The value is only an estimate because the number of
1525
* threads may change dynamically while this method traverses
1526
* internal data structures. This method is designed for use in
1527
* monitoring system state, not for synchronization
1530
* @return the estimated number of threads waiting to acquire
1532
public final int getQueueLength() {
1534
for (Node p = tail; p != null; p = p.prev) {
1535
if (p.thread != null)
1542
* Returns a collection containing threads that may be waiting to
1543
* acquire. Because the actual set of threads may change
1544
* dynamically while constructing this result, the returned
1545
* collection is only a best-effort estimate. The elements of the
1546
* returned collection are in no particular order. This method is
1547
* designed to facilitate construction of subclasses that provide
1548
* more extensive monitoring facilities.
1550
* @return the collection of threads
1552
public final Collection<Thread> getQueuedThreads() {
1553
ArrayList<Thread> list = new ArrayList<Thread>();
1554
for (Node p = tail; p != null; p = p.prev) {
1555
Thread t = p.thread;
1563
* Returns a collection containing threads that may be waiting to
1564
* acquire in exclusive mode. This has the same properties
1565
* as {@link #getQueuedThreads} except that it only returns
1566
* those threads waiting due to an exclusive acquire.
1568
* @return the collection of threads
1570
public final Collection<Thread> getExclusiveQueuedThreads() {
1571
ArrayList<Thread> list = new ArrayList<Thread>();
1572
for (Node p = tail; p != null; p = p.prev) {
1573
if (!p.isShared()) {
1574
Thread t = p.thread;
1583
* Returns a collection containing threads that may be waiting to
1584
* acquire in shared mode. This has the same properties
1585
* as {@link #getQueuedThreads} except that it only returns
1586
* those threads waiting due to a shared acquire.
1588
* @return the collection of threads
1590
public final Collection<Thread> getSharedQueuedThreads() {
1591
ArrayList<Thread> list = new ArrayList<Thread>();
1592
for (Node p = tail; p != null; p = p.prev) {
1594
Thread t = p.thread;
1603
* Returns a string identifying this synchronizer, as well as its state.
1604
* The state, in brackets, includes the String {@code "State ="}
1605
* followed by the current value of {@link #getState}, and either
1606
* {@code "nonempty"} or {@code "empty"} depending on whether the
1609
* @return a string identifying this synchronizer, as well as its state
1611
public String toString() {
1613
String q = hasQueuedThreads() ? "non" : "";
1614
return super.toString() +
1615
"[State = " + s + ", " + q + "empty queue]";
1619
// Internal support methods for Conditions
1622
* Returns true if a node, always one that was initially placed on
1623
* a condition queue, is now waiting to reacquire on sync queue.
1624
* @param node the node
1625
* @return true if is reacquiring
1627
final boolean isOnSyncQueue(Node node) {
1628
if (node.waitStatus == Node.CONDITION || node.prev == null)
1630
if (node.next != null) // If has successor, it must be on queue
1633
* node.prev can be non-null, but not yet on queue because
1634
* the CAS to place it on queue can fail. So we have to
1635
* traverse from tail to make sure it actually made it. It
1636
* will always be near the tail in calls to this method, and
1637
* unless the CAS failed (which is unlikely), it will be
1638
* there, so we hardly ever traverse much.
1640
return findNodeFromTail(node);
1644
* Returns true if node is on sync queue by searching backwards from tail.
1645
* Called only when needed by isOnSyncQueue.
1646
* @return true if present
1648
private boolean findNodeFromTail(Node node) {
1660
* Transfers a node from a condition queue onto sync queue.
1661
* Returns true if successful.
1662
* @param node the node
1663
* @return true if successfully transferred (else the node was
1664
* cancelled before signal).
1666
final boolean transferForSignal(Node node) {
1668
* If cannot change waitStatus, the node has been cancelled.
1670
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
1674
* Splice onto queue and try to set waitStatus of predecessor to
1675
* indicate that thread is (probably) waiting. If cancelled or
1676
* attempt to set waitStatus fails, wake up to resync (in which
1677
* case the waitStatus can be transiently and harmlessly wrong).
1680
int ws = p.waitStatus;
1681
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
1682
LockSupport.unpark(node.thread);
1687
* Transfers node, if necessary, to sync queue after a cancelled
1688
* wait. Returns true if thread was cancelled before being
1690
* @param current the waiting thread
1691
* @param node its node
1692
* @return true if cancelled before the node was signalled
1694
final boolean transferAfterCancelledWait(Node node) {
1695
if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
1700
* If we lost out to a signal(), then we can't proceed
1701
* until it finishes its enq(). Cancelling during an
1702
* incomplete transfer is both rare and transient, so just
1705
while (!isOnSyncQueue(node))
1711
* Invokes release with current state value; returns saved state.
1712
* Cancels node and throws exception on failure.
1713
* @param node the condition node for this wait
1714
* @return previous sync state
1716
final int fullyRelease(Node node) {
1717
boolean failed = true;
1719
int savedState = getState();
1720
if (release(savedState)) {
1724
throw new IllegalMonitorStateException();
1728
node.waitStatus = Node.CANCELLED;
1732
// Instrumentation methods for conditions
1735
* Queries whether the given ConditionObject
1736
* uses this synchronizer as its lock.
1738
* @param condition the condition
1739
* @return <tt>true</tt> if owned
1740
* @throws NullPointerException if the condition is null
1742
public final boolean owns(ConditionObject condition) {
1743
if (condition == null)
1744
throw new NullPointerException();
1745
return condition.isOwnedBy(this);
1749
* Queries whether any threads are waiting on the given condition
1750
* associated with this synchronizer. Note that because timeouts
1751
* and interrupts may occur at any time, a <tt>true</tt> return
1752
* does not guarantee that a future <tt>signal</tt> will awaken
1753
* any threads. This method is designed primarily for use in
1754
* monitoring of the system state.
1756
* @param condition the condition
1757
* @return <tt>true</tt> if there are any waiting threads
1758
* @throws IllegalMonitorStateException if exclusive synchronization
1760
* @throws IllegalArgumentException if the given condition is
1761
* not associated with this synchronizer
1762
* @throws NullPointerException if the condition is null
1764
public final boolean hasWaiters(ConditionObject condition) {
1765
if (!owns(condition))
1766
throw new IllegalArgumentException("Not owner");
1767
return condition.hasWaiters();
1771
* Returns an estimate of the number of threads waiting on the
1772
* given condition associated with this synchronizer. Note that
1773
* because timeouts and interrupts may occur at any time, the
1774
* estimate serves only as an upper bound on the actual number of
1775
* waiters. This method is designed for use in monitoring of the
1776
* system state, not for synchronization control.
1778
* @param condition the condition
1779
* @return the estimated number of waiting threads
1780
* @throws IllegalMonitorStateException if exclusive synchronization
1782
* @throws IllegalArgumentException if the given condition is
1783
* not associated with this synchronizer
1784
* @throws NullPointerException if the condition is null
1786
public final int getWaitQueueLength(ConditionObject condition) {
1787
if (!owns(condition))
1788
throw new IllegalArgumentException("Not owner");
1789
return condition.getWaitQueueLength();
1793
* Returns a collection containing those threads that may be
1794
* waiting on the given condition associated with this
1795
* synchronizer. Because the actual set of threads may change
1796
* dynamically while constructing this result, the returned
1797
* collection is only a best-effort estimate. The elements of the
1798
* returned collection are in no particular order.
1800
* @param condition the condition
1801
* @return the collection of threads
1802
* @throws IllegalMonitorStateException if exclusive synchronization
1804
* @throws IllegalArgumentException if the given condition is
1805
* not associated with this synchronizer
1806
* @throws NullPointerException if the condition is null
1808
public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
1809
if (!owns(condition))
1810
throw new IllegalArgumentException("Not owner");
1811
return condition.getWaitingThreads();
1815
* Condition implementation for a {@link
1816
* AbstractQueuedSynchronizer} serving as the basis of a {@link
1817
* Lock} implementation.
1819
* <p>Method documentation for this class describes mechanics,
1820
* not behavioral specifications from the point of view of Lock
1821
* and Condition users. Exported versions of this class will in
1822
* general need to be accompanied by documentation describing
1823
* condition semantics that rely on those of the associated
1824
* <tt>AbstractQueuedSynchronizer</tt>.
1826
* <p>This class is Serializable, but all fields are transient,
1827
* so deserialized conditions have no waiters.
1829
public class ConditionObject implements Condition, java.io.Serializable {
1830
private static final long serialVersionUID = 1173984872572414699L;
1831
/** First node of condition queue. */
1832
private transient Node firstWaiter;
1833
/** Last node of condition queue. */
1834
private transient Node lastWaiter;
1837
* Creates a new <tt>ConditionObject</tt> instance.
1839
public ConditionObject() { }
1844
* Adds a new waiter to wait queue.
1845
* @return its new wait node
1847
private Node addConditionWaiter() {
1848
Node t = lastWaiter;
1849
// If lastWaiter is cancelled, clean out.
1850
if (t != null && t.waitStatus != Node.CONDITION) {
1851
unlinkCancelledWaiters();
1854
Node node = new Node(Thread.currentThread(), Node.CONDITION);
1858
t.nextWaiter = node;
1864
* Removes and transfers nodes until hit non-cancelled one or
1865
* null. Split out from signal in part to encourage compilers
1866
* to inline the case of no waiters.
1867
* @param first (non-null) the first node on condition queue
1869
private void doSignal(Node first) {
1871
if ( (firstWaiter = first.nextWaiter) == null)
1873
first.nextWaiter = null;
1874
} while (!transferForSignal(first) &&
1875
(first = firstWaiter) != null);
1879
* Removes and transfers all nodes.
1880
* @param first (non-null) the first node on condition queue
1882
private void doSignalAll(Node first) {
1883
lastWaiter = firstWaiter = null;
1885
Node next = first.nextWaiter;
1886
first.nextWaiter = null;
1887
transferForSignal(first);
1889
} while (first != null);
1893
* Unlinks cancelled waiter nodes from condition queue.
1894
* Called only while holding lock. This is called when
1895
* cancellation occurred during condition wait, and upon
1896
* insertion of a new waiter when lastWaiter is seen to have
1897
* been cancelled. This method is needed to avoid garbage
1898
* retention in the absence of signals. So even though it may
1899
* require a full traversal, it comes into play only when
1900
* timeouts or cancellations occur in the absence of
1901
* signals. It traverses all nodes rather than stopping at a
1902
* particular target to unlink all pointers to garbage nodes
1903
* without requiring many re-traversals during cancellation
1906
private void unlinkCancelledWaiters() {
1907
Node t = firstWaiter;
1910
Node next = t.nextWaiter;
1911
if (t.waitStatus != Node.CONDITION) {
1912
t.nextWaiter = null;
1916
trail.nextWaiter = next;
1929
* Moves the longest-waiting thread, if one exists, from the
1930
* wait queue for this condition to the wait queue for the
1933
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1934
* returns {@code false}
1936
public final void signal() {
1937
if (!isHeldExclusively())
1938
throw new IllegalMonitorStateException();
1939
Node first = firstWaiter;
1945
* Moves all threads from the wait queue for this condition to
1946
* the wait queue for the owning lock.
1948
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1949
* returns {@code false}
1951
public final void signalAll() {
1952
if (!isHeldExclusively())
1953
throw new IllegalMonitorStateException();
1954
Node first = firstWaiter;
1960
* Implements uninterruptible condition wait.
1962
* <li> Save lock state returned by {@link #getState}.
1963
* <li> Invoke {@link #release} with
1964
* saved state as argument, throwing
1965
* IllegalMonitorStateException if it fails.
1966
* <li> Block until signalled.
1967
* <li> Reacquire by invoking specialized version of
1968
* {@link #acquire} with saved state as argument.
1971
public final void awaitUninterruptibly() {
1972
Node node = addConditionWaiter();
1973
int savedState = fullyRelease(node);
1974
boolean interrupted = false;
1975
while (!isOnSyncQueue(node)) {
1976
LockSupport.park(this);
1977
if (Thread.interrupted())
1980
if (acquireQueued(node, savedState) || interrupted)
1985
* For interruptible waits, we need to track whether to throw
1986
* InterruptedException, if interrupted while blocked on
1987
* condition, versus reinterrupt current thread, if
1988
* interrupted while blocked waiting to re-acquire.
1991
/** Mode meaning to reinterrupt on exit from wait */
1992
private static final int REINTERRUPT = 1;
1993
/** Mode meaning to throw InterruptedException on exit from wait */
1994
private static final int THROW_IE = -1;
1997
* Checks for interrupt, returning THROW_IE if interrupted
1998
* before signalled, REINTERRUPT if after signalled, or
1999
* 0 if not interrupted.
2001
private int checkInterruptWhileWaiting(Node node) {
2002
return Thread.interrupted() ?
2003
(transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
2008
* Throws InterruptedException, reinterrupts current thread, or
2009
* does nothing, depending on mode.
2011
private void reportInterruptAfterWait(int interruptMode)
2012
throws InterruptedException {
2013
if (interruptMode == THROW_IE)
2014
throw new InterruptedException();
2015
else if (interruptMode == REINTERRUPT)
2020
* Implements interruptible condition wait.
2022
* <li> If current thread is interrupted, throw InterruptedException.
2023
* <li> Save lock state returned by {@link #getState}.
2024
* <li> Invoke {@link #release} with
2025
* saved state as argument, throwing
2026
* IllegalMonitorStateException if it fails.
2027
* <li> Block until signalled or interrupted.
2028
* <li> Reacquire by invoking specialized version of
2029
* {@link #acquire} with saved state as argument.
2030
* <li> If interrupted while blocked in step 4, throw InterruptedException.
2033
public final void await() throws InterruptedException {
2034
if (Thread.interrupted())
2035
throw new InterruptedException();
2036
Node node = addConditionWaiter();
2037
int savedState = fullyRelease(node);
2038
int interruptMode = 0;
2039
while (!isOnSyncQueue(node)) {
2040
LockSupport.park(this);
2041
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2044
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2045
interruptMode = REINTERRUPT;
2046
if (node.nextWaiter != null) // clean up if cancelled
2047
unlinkCancelledWaiters();
2048
if (interruptMode != 0)
2049
reportInterruptAfterWait(interruptMode);
2053
* Implements timed condition wait.
2055
* <li> If current thread is interrupted, throw InterruptedException.
2056
* <li> Save lock state returned by {@link #getState}.
2057
* <li> Invoke {@link #release} with
2058
* saved state as argument, throwing
2059
* IllegalMonitorStateException if it fails.
2060
* <li> Block until signalled, interrupted, or timed out.
2061
* <li> Reacquire by invoking specialized version of
2062
* {@link #acquire} with saved state as argument.
2063
* <li> If interrupted while blocked in step 4, throw InterruptedException.
2066
public final long awaitNanos(long nanosTimeout)
2067
throws InterruptedException {
2068
if (Thread.interrupted())
2069
throw new InterruptedException();
2070
Node node = addConditionWaiter();
2071
int savedState = fullyRelease(node);
2072
long lastTime = System.nanoTime();
2073
int interruptMode = 0;
2074
while (!isOnSyncQueue(node)) {
2075
if (nanosTimeout <= 0L) {
2076
transferAfterCancelledWait(node);
2079
LockSupport.parkNanos(this, nanosTimeout);
2080
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2083
long now = System.nanoTime();
2084
nanosTimeout -= now - lastTime;
2087
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2088
interruptMode = REINTERRUPT;
2089
if (node.nextWaiter != null)
2090
unlinkCancelledWaiters();
2091
if (interruptMode != 0)
2092
reportInterruptAfterWait(interruptMode);
2093
return nanosTimeout - (System.nanoTime() - lastTime);
2097
* Implements absolute timed condition wait.
2099
* <li> If current thread is interrupted, throw InterruptedException.
2100
* <li> Save lock state returned by {@link #getState}.
2101
* <li> Invoke {@link #release} with
2102
* saved state as argument, throwing
2103
* IllegalMonitorStateException if it fails.
2104
* <li> Block until signalled, interrupted, or timed out.
2105
* <li> Reacquire by invoking specialized version of
2106
* {@link #acquire} with saved state as argument.
2107
* <li> If interrupted while blocked in step 4, throw InterruptedException.
2108
* <li> If timed out while blocked in step 4, return false, else true.
2111
public final boolean awaitUntil(Date deadline)
2112
throws InterruptedException {
2113
if (deadline == null)
2114
throw new NullPointerException();
2115
long abstime = deadline.getTime();
2116
if (Thread.interrupted())
2117
throw new InterruptedException();
2118
Node node = addConditionWaiter();
2119
int savedState = fullyRelease(node);
2120
boolean timedout = false;
2121
int interruptMode = 0;
2122
while (!isOnSyncQueue(node)) {
2123
if (System.currentTimeMillis() > abstime) {
2124
timedout = transferAfterCancelledWait(node);
2127
LockSupport.parkUntil(this, abstime);
2128
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2131
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2132
interruptMode = REINTERRUPT;
2133
if (node.nextWaiter != null)
2134
unlinkCancelledWaiters();
2135
if (interruptMode != 0)
2136
reportInterruptAfterWait(interruptMode);
2141
* Implements timed condition wait.
2143
* <li> If current thread is interrupted, throw InterruptedException.
2144
* <li> Save lock state returned by {@link #getState}.
2145
* <li> Invoke {@link #release} with
2146
* saved state as argument, throwing
2147
* IllegalMonitorStateException if it fails.
2148
* <li> Block until signalled, interrupted, or timed out.
2149
* <li> Reacquire by invoking specialized version of
2150
* {@link #acquire} with saved state as argument.
2151
* <li> If interrupted while blocked in step 4, throw InterruptedException.
2152
* <li> If timed out while blocked in step 4, return false, else true.
2155
public final boolean await(long time, TimeUnit unit)
2156
throws InterruptedException {
2158
throw new NullPointerException();
2159
long nanosTimeout = unit.toNanos(time);
2160
if (Thread.interrupted())
2161
throw new InterruptedException();
2162
Node node = addConditionWaiter();
2163
int savedState = fullyRelease(node);
2164
long lastTime = System.nanoTime();
2165
boolean timedout = false;
2166
int interruptMode = 0;
2167
while (!isOnSyncQueue(node)) {
2168
if (nanosTimeout <= 0L) {
2169
timedout = transferAfterCancelledWait(node);
2172
if (nanosTimeout >= spinForTimeoutThreshold)
2173
LockSupport.parkNanos(this, nanosTimeout);
2174
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2176
long now = System.nanoTime();
2177
nanosTimeout -= now - lastTime;
2180
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2181
interruptMode = REINTERRUPT;
2182
if (node.nextWaiter != null)
2183
unlinkCancelledWaiters();
2184
if (interruptMode != 0)
2185
reportInterruptAfterWait(interruptMode);
2189
// support for instrumentation
2192
* Returns true if this condition was created by the given
2193
* synchronization object.
2195
* @return {@code true} if owned
2197
final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
2198
return sync == AbstractQueuedSynchronizer.this;
2202
* Queries whether any threads are waiting on this condition.
2203
* Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
2205
* @return {@code true} if there are any waiting threads
2206
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2207
* returns {@code false}
2209
protected final boolean hasWaiters() {
2210
if (!isHeldExclusively())
2211
throw new IllegalMonitorStateException();
2212
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2213
if (w.waitStatus == Node.CONDITION)
2220
* Returns an estimate of the number of threads waiting on
2222
* Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
2224
* @return the estimated number of waiting threads
2225
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2226
* returns {@code false}
2228
protected final int getWaitQueueLength() {
2229
if (!isHeldExclusively())
2230
throw new IllegalMonitorStateException();
2232
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2233
if (w.waitStatus == Node.CONDITION)
2240
* Returns a collection containing those threads that may be
2241
* waiting on this Condition.
2242
* Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
2244
* @return the collection of threads
2245
* @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2246
* returns {@code false}
2248
protected final Collection<Thread> getWaitingThreads() {
2249
if (!isHeldExclusively())
2250
throw new IllegalMonitorStateException();
2251
ArrayList<Thread> list = new ArrayList<Thread>();
2252
for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2253
if (w.waitStatus == Node.CONDITION) {
2254
Thread t = w.thread;
2264
* IKVM specific. We use AtomicReferenceFieldUpdater instead of Unsafe primitives.
2266
private static final AtomicReferenceFieldUpdater<AbstractQueuedSynchronizer, Node> headUpdater =
2267
AtomicReferenceFieldUpdater.newUpdater(AbstractQueuedSynchronizer.class, Node.class, "head");
2268
private static final AtomicReferenceFieldUpdater<AbstractQueuedSynchronizer, Node> tailUpdater =
2269
AtomicReferenceFieldUpdater.newUpdater(AbstractQueuedSynchronizer.class, Node.class, "tail");
2272
* CAS head field. Used only by enq.
2274
private final boolean compareAndSetHead(Node update) {
2275
return headUpdater.compareAndSet(this, null, update);
2279
* CAS tail field. Used only by enq.
2281
private final boolean compareAndSetTail(Node expect, Node update) {
2282
return tailUpdater.compareAndSet(this, expect, update);
2286
* CAS waitStatus field of a node.
2288
private static final native boolean compareAndSetWaitStatus(Node node,
2290
int update); // implemented in map.xml
2292
* CAS next field of a node.
2294
private static final boolean compareAndSetNext(Node node,
2297
return Node.nextUpdater.compareAndSet(node, expect, update);