1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent.locks; |
8 |
|
9 |
import java.util.ArrayList; |
10 |
import java.util.Collection; |
11 |
import java.util.Date; |
12 |
import java.util.concurrent.TimeUnit; |
13 |
import java.util.concurrent.ForkJoinPool; |
14 |
import java.util.concurrent.RejectedExecutionException; |
15 |
import jdk.internal.misc.Unsafe; |
16 |
|
17 |
/** |
18 |
* Provides a framework for implementing blocking locks and related |
19 |
* synchronizers (semaphores, events, etc) that rely on |
20 |
* first-in-first-out (FIFO) wait queues. This class is designed to |
21 |
* be a useful basis for most kinds of synchronizers that rely on a |
22 |
* single atomic {@code int} value to represent state. Subclasses |
23 |
* must define the protected methods that change this state, and which |
24 |
* define what that state means in terms of this object being acquired |
25 |
* or released. Given these, the other methods in this class carry |
26 |
* out all queuing and blocking mechanics. Subclasses can maintain |
27 |
* other state fields, but only the atomically updated {@code int} |
28 |
* value manipulated using methods {@link #getState}, {@link |
29 |
* #setState} and {@link #compareAndSetState} is tracked with respect |
30 |
* to synchronization. |
31 |
* |
32 |
* <p>Subclasses should be defined as non-public internal helper |
33 |
* classes that are used to implement the synchronization properties |
34 |
* of their enclosing class. Class |
35 |
* {@code AbstractQueuedSynchronizer} does not implement any |
36 |
* synchronization interface. Instead it defines methods such as |
37 |
* {@link #acquireInterruptibly} that can be invoked as |
38 |
* appropriate by concrete locks and related synchronizers to |
39 |
* implement their public methods. |
40 |
* |
41 |
* <p>This class supports either or both a default <em>exclusive</em> |
42 |
* mode and a <em>shared</em> mode. When acquired in exclusive mode, |
43 |
* attempted acquires by other threads cannot succeed. Shared mode |
44 |
* acquires by multiple threads may (but need not) succeed. This class |
45 |
* does not "understand" these differences except in the |
46 |
* mechanical sense that when a shared mode acquire succeeds, the next |
47 |
* waiting thread (if one exists) must also determine whether it can |
48 |
* acquire as well. Threads waiting in the different modes share the |
49 |
* same FIFO queue. Usually, implementation subclasses support only |
50 |
* one of these modes, but both can come into play for example in a |
51 |
* {@link ReadWriteLock}. Subclasses that support only exclusive or |
52 |
* only shared modes need not define the methods supporting the unused mode. |
53 |
* |
54 |
* <p>This class defines a nested {@link ConditionObject} class that |
55 |
* can be used as a {@link Condition} implementation by subclasses |
56 |
* supporting exclusive mode for which method {@link |
57 |
* #isHeldExclusively} reports whether synchronization is exclusively |
58 |
* held with respect to the current thread, method {@link #release} |
59 |
* invoked with the current {@link #getState} value fully releases |
60 |
* this object, and {@link #acquire}, given this saved state value, |
61 |
* eventually restores this object to its previous acquired state. No |
62 |
* {@code AbstractQueuedSynchronizer} method otherwise creates such a |
63 |
* condition, so if this constraint cannot be met, do not use it. The |
64 |
* behavior of {@link ConditionObject} depends of course on the |
65 |
* semantics of its synchronizer implementation. |
66 |
* |
67 |
* <p>This class provides inspection, instrumentation, and monitoring |
68 |
* methods for the internal queue, as well as similar methods for |
69 |
* condition objects. These can be exported as desired into classes |
70 |
* using an {@code AbstractQueuedSynchronizer} for their |
71 |
* synchronization mechanics. |
72 |
* |
73 |
* <p>Serialization of this class stores only the underlying atomic |
74 |
* integer maintaining state, so deserialized objects have empty |
75 |
* thread queues. Typical subclasses requiring serializability will |
76 |
* define a {@code readObject} method that restores this to a known |
77 |
* initial state upon deserialization. |
78 |
* |
79 |
* <h2>Usage</h2> |
80 |
* |
81 |
* <p>To use this class as the basis of a synchronizer, redefine the |
82 |
* following methods, as applicable, by inspecting and/or modifying |
83 |
* the synchronization state using {@link #getState}, {@link |
84 |
* #setState} and/or {@link #compareAndSetState}: |
85 |
* |
86 |
* <ul> |
87 |
* <li>{@link #tryAcquire} |
88 |
* <li>{@link #tryRelease} |
89 |
* <li>{@link #tryAcquireShared} |
90 |
* <li>{@link #tryReleaseShared} |
91 |
* <li>{@link #isHeldExclusively} |
92 |
* </ul> |
93 |
* |
94 |
* Each of these methods by default throws {@link |
95 |
* UnsupportedOperationException}. Implementations of these methods |
96 |
* must be internally thread-safe, and should in general be short and |
97 |
* not block. Defining these methods is the <em>only</em> supported |
98 |
* means of using this class. All other methods are declared |
99 |
* {@code final} because they cannot be independently varied. |
100 |
* |
101 |
* <p>You may also find the inherited methods from {@link |
102 |
* AbstractOwnableSynchronizer} useful to keep track of the thread |
103 |
* owning an exclusive synchronizer. You are encouraged to use them |
104 |
* -- this enables monitoring and diagnostic tools to assist users in |
105 |
* determining which threads hold locks. |
106 |
* |
107 |
* <p>Even though this class is based on an internal FIFO queue, it |
108 |
* does not automatically enforce FIFO acquisition policies. The core |
109 |
* of exclusive synchronization takes the form: |
110 |
* |
111 |
* <pre> |
112 |
* <em>Acquire:</em> |
113 |
* while (!tryAcquire(arg)) { |
114 |
* <em>enqueue thread if it is not already queued</em>; |
115 |
* <em>possibly block current thread</em>; |
116 |
* } |
117 |
* |
118 |
* <em>Release:</em> |
119 |
* if (tryRelease(arg)) |
120 |
* <em>unblock the first queued thread</em>; |
121 |
* </pre> |
122 |
* |
123 |
* (Shared mode is similar but may involve cascading signals.) |
124 |
* |
125 |
* <p id="barging">Because checks in acquire are invoked before |
126 |
* enqueuing, a newly acquiring thread may <em>barge</em> ahead of |
127 |
* others that are blocked and queued. However, you can, if desired, |
128 |
* define {@code tryAcquire} and/or {@code tryAcquireShared} to |
129 |
* disable barging by internally invoking one or more of the inspection |
130 |
* methods, thereby providing a <em>fair</em> FIFO acquisition order. |
131 |
* In particular, most fair synchronizers can define {@code tryAcquire} |
132 |
* to return {@code false} if {@link #hasQueuedPredecessors} (a method |
133 |
* specifically designed to be used by fair synchronizers) returns |
134 |
* {@code true}. Other variations are possible. |
135 |
* |
136 |
* <p>Throughput and scalability are generally highest for the |
137 |
* default barging (also known as <em>greedy</em>, |
138 |
* <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy. |
139 |
* While this is not guaranteed to be fair or starvation-free, earlier |
140 |
* queued threads are allowed to recontend before later queued |
141 |
* threads, and each recontention has an unbiased chance to succeed |
142 |
* against incoming threads. Also, while acquires do not |
143 |
* "spin" in the usual sense, they may perform multiple |
144 |
* invocations of {@code tryAcquire} interspersed with other |
145 |
* computations before blocking. This gives most of the benefits of |
146 |
* spins when exclusive synchronization is only briefly held, without |
147 |
* most of the liabilities when it isn't. If so desired, you can |
148 |
* augment this by preceding calls to acquire methods with |
149 |
* "fast-path" checks, possibly prechecking {@link #hasContended} |
150 |
* and/or {@link #hasQueuedThreads} to only do so if the synchronizer |
151 |
* is likely not to be contended. |
152 |
* |
153 |
* <p>This class provides an efficient and scalable basis for |
154 |
* synchronization in part by specializing its range of use to |
155 |
* synchronizers that can rely on {@code int} state, acquire, and |
156 |
* release parameters, and an internal FIFO wait queue. When this does |
157 |
* not suffice, you can build synchronizers from a lower level using |
158 |
* {@link java.util.concurrent.atomic atomic} classes, your own custom |
159 |
* {@link java.util.Queue} classes, and {@link LockSupport} blocking |
160 |
* support. |
161 |
* |
162 |
* <h2>Usage Examples</h2> |
163 |
* |
164 |
* <p>Here is a non-reentrant mutual exclusion lock class that uses |
165 |
* the value zero to represent the unlocked state, and one to |
166 |
* represent the locked state. While a non-reentrant lock |
167 |
* does not strictly require recording of the current owner |
168 |
* thread, this class does so anyway to make usage easier to monitor. |
169 |
* It also supports conditions and exposes some instrumentation methods: |
170 |
* |
171 |
* <pre> {@code |
172 |
* class Mutex implements Lock, java.io.Serializable { |
173 |
* |
174 |
* // Our internal helper class |
175 |
* private static class Sync extends AbstractQueuedSynchronizer { |
176 |
* // Acquires the lock if state is zero |
177 |
* public boolean tryAcquire(int acquires) { |
178 |
* assert acquires == 1; // Otherwise unused |
179 |
* if (compareAndSetState(0, 1)) { |
180 |
* setExclusiveOwnerThread(Thread.currentThread()); |
181 |
* return true; |
182 |
* } |
183 |
* return false; |
184 |
* } |
185 |
* |
186 |
* // Releases the lock by setting state to zero |
187 |
* protected boolean tryRelease(int releases) { |
188 |
* assert releases == 1; // Otherwise unused |
189 |
* if (!isHeldExclusively()) |
190 |
* throw new IllegalMonitorStateException(); |
191 |
* setExclusiveOwnerThread(null); |
192 |
* setState(0); |
193 |
* return true; |
194 |
* } |
195 |
* |
196 |
* // Reports whether in locked state |
197 |
* public boolean isLocked() { |
198 |
* return getState() != 0; |
199 |
* } |
200 |
* |
201 |
* public boolean isHeldExclusively() { |
202 |
* // a data race, but safe due to out-of-thin-air guarantees |
203 |
* return getExclusiveOwnerThread() == Thread.currentThread(); |
204 |
* } |
205 |
* |
206 |
* // Provides a Condition |
207 |
* public Condition newCondition() { |
208 |
* return new ConditionObject(); |
209 |
* } |
210 |
* |
211 |
* // Deserializes properly |
212 |
* private void readObject(ObjectInputStream s) |
213 |
* throws IOException, ClassNotFoundException { |
214 |
* s.defaultReadObject(); |
215 |
* setState(0); // reset to unlocked state |
216 |
* } |
217 |
* } |
218 |
* |
219 |
* // The sync object does all the hard work. We just forward to it. |
220 |
* private final Sync sync = new Sync(); |
221 |
* |
222 |
* public void lock() { sync.acquire(1); } |
223 |
* public boolean tryLock() { return sync.tryAcquire(1); } |
224 |
* public void unlock() { sync.release(1); } |
225 |
* public Condition newCondition() { return sync.newCondition(); } |
226 |
* public boolean isLocked() { return sync.isLocked(); } |
227 |
* public boolean isHeldByCurrentThread() { |
228 |
* return sync.isHeldExclusively(); |
229 |
* } |
230 |
* public boolean hasQueuedThreads() { |
231 |
* return sync.hasQueuedThreads(); |
232 |
* } |
233 |
* public void lockInterruptibly() throws InterruptedException { |
234 |
* sync.acquireInterruptibly(1); |
235 |
* } |
236 |
* public boolean tryLock(long timeout, TimeUnit unit) |
237 |
* throws InterruptedException { |
238 |
* return sync.tryAcquireNanos(1, unit.toNanos(timeout)); |
239 |
* } |
240 |
* }}</pre> |
241 |
* |
242 |
* <p>Here is a latch class that is like a |
243 |
* {@link java.util.concurrent.CountDownLatch CountDownLatch} |
244 |
* except that it only requires a single {@code signal} to |
245 |
* fire. Because a latch is non-exclusive, it uses the {@code shared} |
246 |
* acquire and release methods. |
247 |
* |
248 |
* <pre> {@code |
249 |
* class BooleanLatch { |
250 |
* |
251 |
* private static class Sync extends AbstractQueuedSynchronizer { |
252 |
* boolean isSignalled() { return getState() != 0; } |
253 |
* |
254 |
* protected int tryAcquireShared(int ignore) { |
255 |
* return isSignalled() ? 1 : -1; |
256 |
* } |
257 |
* |
258 |
* protected boolean tryReleaseShared(int ignore) { |
259 |
* setState(1); |
260 |
* return true; |
261 |
* } |
262 |
* } |
263 |
* |
264 |
* private final Sync sync = new Sync(); |
265 |
* public boolean isSignalled() { return sync.isSignalled(); } |
266 |
* public void signal() { sync.releaseShared(1); } |
267 |
* public void await() throws InterruptedException { |
268 |
* sync.acquireSharedInterruptibly(1); |
269 |
* } |
270 |
* }}</pre> |
271 |
* |
272 |
* @since 1.5 |
273 |
* @author Doug Lea |
274 |
*/ |
275 |
public abstract class AbstractQueuedSynchronizer |
276 |
extends AbstractOwnableSynchronizer |
277 |
implements java.io.Serializable { |
278 |
|
279 |
private static final long serialVersionUID = 7373984972572414691L; |
280 |
|
281 |
/** |
282 |
* Creates a new {@code AbstractQueuedSynchronizer} instance |
283 |
* with initial synchronization state of zero. |
284 |
*/ |
285 |
protected AbstractQueuedSynchronizer() { } |
286 |
|
287 |
/* |
288 |
* Overview. |
289 |
* |
290 |
* The wait queue is a variant of a "CLH" (Craig, Landin, and |
291 |
* Hagersten) lock queue. CLH locks are normally used for |
292 |
* spinlocks. We instead use them for blocking synchronizers by |
293 |
* including explicit ("prev" and "next") links plus a "status" |
294 |
* field that allow nodes to signal successors when releasing |
295 |
* locks, and handle cancellation due to interrupts and timeouts. |
296 |
* The status field includes bits that track whether a thread |
297 |
* needs a signal (using LockSupport.unpark). Despite these |
298 |
* additions, we maintain most CLH locality properties. |
299 |
* |
300 |
* To enqueue into a CLH lock, you atomically splice it in as new |
301 |
* tail. To dequeue, you set the head field, so the next eligible |
302 |
* waiter becomes first. |
303 |
* |
304 |
* +------+ prev +-------+ +------+ |
305 |
* | head | <---- | first | <---- | tail | |
306 |
* +------+ +-------+ +------+ |
307 |
* |
308 |
* Insertion into a CLH queue requires only a single atomic |
309 |
* operation on "tail", so there is a simple point of demarcation |
310 |
* from unqueued to queued. The "next" link of the predecessor is |
311 |
* set by the enqueuing thread after successful CAS. Even though |
312 |
* non-atomic, this suffices to ensure that any blocked thread is |
313 |
* signalled by a predecessor when eligible (although in the case |
314 |
* of cancellation, possibly with the assistance of a signal in |
315 |
* method cleanQueue). Signalling is based in part on a |
316 |
* Dekker-like scheme in which the to-be waiting thread indicates |
317 |
* WAITING status, then retries acquiring, and then rechecks |
318 |
* status before blocking. The signaller atomically clears WAITING |
319 |
* status when unparking. |
320 |
* |
321 |
* Dequeuing on acquire involves detaching (nulling) a node's |
322 |
* "prev" node and then updating the "head". Other threads check |
323 |
* if a node is or was dequeued by checking "prev" rather than |
324 |
* head. We enforce the nulling then setting order by spin-waiting |
325 |
* if necessary. Because of this, the lock algorithm is not itself |
326 |
* strictly "lock-free" because an acquiring thread may need to |
327 |
* wait for a previous acquire to make progress. When used with |
328 |
* exclusive locks, such progress is required anyway. However |
329 |
* Shared mode may (uncommonly) require a spin-wait before |
330 |
* setting head field to ensure proper propagation. (Historical |
331 |
* note: This allows some simplifications and efficiencies |
332 |
* compared to previous versions of this class.) |
333 |
* |
334 |
* A node's predecessor can change due to cancellation while it is |
335 |
* waiting, until the node is first in queue, at which point it |
336 |
* cannot change. The acquire methods cope with this by rechecking |
337 |
* "prev" before waiting. The prev and next fields are modified |
338 |
* only via CAS by cancelled nodes in method cleanQueue. The |
339 |
* unsplice strategy is reminiscent of Michael-Scott queues in |
340 |
* that after a successful CAS to prev field, other threads help |
341 |
* fix next fields. Because cancellation often occurs in bunches |
342 |
* that complicate decisions about necessary signals, each call to |
343 |
* cleanQueue traverses the queue until a clean sweep. Nodes that |
344 |
* become relinked as first are unconditionally unparked |
345 |
* (sometimes unnecessarily, but those cases are not worth |
346 |
* avoiding). |
347 |
* |
348 |
* A thread may try to acquire if it is first (frontmost) in the |
349 |
* queue, and sometimes before. Being first does not guarantee |
350 |
* success; it only gives the right to contend. We balance |
351 |
* throughput, overhead, and fairness by allowing incoming threads |
352 |
* to "barge" and acquire the synchronizer while in the process of |
353 |
* enqueuing, in which case an awakened first thread may need to |
354 |
* rewait. To counteract possible repeated unlucky rewaits, we |
355 |
* exponentially increase retries (up to 256) to acquire each time |
356 |
* a thread is unparked. Except in this case, AQS locks do not |
357 |
* spin; they instead interleave attempts to acquire with |
358 |
* bookkeeping steps. (Users who want spinlocks can use |
359 |
* tryAcquire.) |
360 |
* |
361 |
* To improve garbage collectibility, fields of nodes not yet on |
362 |
* list are null. (It is not rare to create and then throw away a |
363 |
* node without using it.) Fields of nodes coming off the list are |
364 |
* nulled out as soon as possible. This accentuates the challenge |
365 |
* of externally determining the first waiting thread (as in |
366 |
* method getFirstQueuedThread). This sometimes requires the |
367 |
* fallback of traversing backwards from the atomically updated |
368 |
* "tail" when fields appear null. (This is never needed in the |
369 |
* process of signalling though.) |
370 |
* |
371 |
* CLH queues need a dummy header node to get started. But |
372 |
* we don't create them on construction, because it would be wasted |
373 |
* effort if there is never contention. Instead, the node |
374 |
* is constructed and head and tail pointers are set upon first |
375 |
* contention. |
376 |
* |
377 |
* Shared mode operations differ from Exclusive in that an acquire |
378 |
* signals the next waiter to try to acquire if it is also |
379 |
* Shared. The tryAcquireShared API allows users to indicate the |
380 |
* degree of propagation, but in most applications, it is more |
381 |
* efficient to ignore this, allowing the successor to try |
382 |
* acquiring in any case. |
383 |
* |
384 |
* Threads waiting on Conditions use nodes with an additional |
385 |
* link to maintain the (FIFO) list of conditions. Conditions only |
386 |
* need to link nodes in simple (non-concurrent) linked queues |
387 |
* because they are only accessed when exclusively held. Upon |
388 |
* await, a node is inserted into a condition queue. Upon signal, |
389 |
* the node is enqueued on the main queue. A special status field |
390 |
* value is used to track and atomically trigger this. |
391 |
* |
392 |
* Accesses to fields head, tail, and state use full Volatile |
393 |
* mode, along with CAS. Node fields status, prev and next also do |
394 |
* so while threads may be signallable, but sometimes use weaker |
395 |
* modes otherwise. Accesses to field "waiter" (the thread to be |
396 |
* signalled) are always sandwiched between other atomic accesses |
397 |
* so are used in Plain mode. We use jdk.internal Unsafe versions |
398 |
* of atomic access methods rather than VarHandles to avoid |
399 |
* potential VM bootstrap issues. |
400 |
* |
401 |
* Most of the above is performed by primary internal method |
402 |
* acquire, that is invoked in some way by all exported acquire |
403 |
* methods. (It is usually easy for compilers to optimize |
404 |
* call-site specializations when heavily used.) |
405 |
* |
406 |
* There are several arbitrary decisions about when and how to |
407 |
* check interrupts in both acquire and await before and/or after |
408 |
* blocking. The decisions are less arbitrary in implementation |
409 |
* updates because some users appear to rely on original behaviors |
410 |
* in ways that are racy and so (rarely) wrong in general but hard |
411 |
* to justify changing. |
412 |
* |
413 |
* Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill |
414 |
* Scherer and Michael Scott, along with members of JSR-166 |
415 |
* expert group, for helpful ideas, discussions, and critiques |
416 |
* on the design of this class. |
417 |
*/ |
418 |
|
419 |
// Node status bits, also used as argument and return values |
420 |
static final int WAITING = 1; // must be 1 |
421 |
static final int CANCELLED = 0x80000000; // must be negative |
422 |
static final int COND = 2; // in a condition wait |
423 |
|
424 |
/** CLH Nodes */ |
425 |
abstract static class Node { |
426 |
volatile Node prev; // initially attached via casTail |
427 |
volatile Node next; // visibly nonnull when signallable |
428 |
Thread waiter; // visibly nonnull when enqueued |
429 |
volatile int status; // written by owner, atomic bit ops by others |
430 |
|
431 |
// methods for atomic operations |
432 |
final boolean casPrev(Node c, Node v) { // for cleanQueue |
433 |
return U.weakCompareAndSetReference(this, PREV, c, v); |
434 |
} |
435 |
final boolean casNext(Node c, Node v) { // for cleanQueue |
436 |
return U.weakCompareAndSetReference(this, NEXT, c, v); |
437 |
} |
438 |
final int getAndUnsetStatus(int v) { // for signalling |
439 |
return U.getAndBitwiseAndInt(this, STATUS, ~v); |
440 |
} |
441 |
final void setPrevRelaxed(Node p) { // for off-queue assignment |
442 |
U.putReference(this, PREV, p); |
443 |
} |
444 |
final void setStatusRelaxed(int s) { // for off-queue assignment |
445 |
U.putInt(this, STATUS, s); |
446 |
} |
447 |
final void clearStatus() { // for reducing unneeded signals |
448 |
U.putIntOpaque(this, STATUS, 0); |
449 |
} |
450 |
|
451 |
private static final long STATUS |
452 |
= U.objectFieldOffset(Node.class, "status"); |
453 |
private static final long NEXT |
454 |
= U.objectFieldOffset(Node.class, "next"); |
455 |
private static final long PREV |
456 |
= U.objectFieldOffset(Node.class, "prev"); |
457 |
} |
458 |
|
459 |
// Concrete classes tagged by type |
460 |
static final class ExclusiveNode extends Node { } |
461 |
static final class SharedNode extends Node { } |
462 |
|
463 |
static final class ConditionNode extends Node |
464 |
implements ForkJoinPool.ManagedBlocker { |
465 |
ConditionNode nextWaiter; // link to next waiting node |
466 |
|
467 |
/** |
468 |
* Allows Conditions to be used in ForkJoinPools without |
469 |
* risking fixed pool exhaustion. This is usable only for |
470 |
* untimed Condition waits, not timed versions. |
471 |
*/ |
472 |
public final boolean isReleasable() { |
473 |
return status <= 1 || Thread.currentThread().isInterrupted(); |
474 |
} |
475 |
|
476 |
public final boolean block() { |
477 |
while (!isReleasable()) LockSupport.park(); |
478 |
return true; |
479 |
} |
480 |
} |
481 |
|
482 |
/** |
483 |
* Head of the wait queue, lazily initialized. |
484 |
*/ |
485 |
private transient volatile Node head; |
486 |
|
487 |
/** |
488 |
* Tail of the wait queue. After initialization, modified only via casTail. |
489 |
*/ |
490 |
private transient volatile Node tail; |
491 |
|
492 |
/** |
493 |
* The synchronization state. |
494 |
*/ |
495 |
private volatile int state; |
496 |
|
497 |
/** |
498 |
* Returns the current value of synchronization state. |
499 |
* This operation has memory semantics of a {@code volatile} read. |
500 |
* @return current state value |
501 |
*/ |
502 |
protected final int getState() { |
503 |
return state; |
504 |
} |
505 |
|
506 |
/** |
507 |
* Sets the value of synchronization state. |
508 |
* This operation has memory semantics of a {@code volatile} write. |
509 |
* @param newState the new state value |
510 |
*/ |
511 |
protected final void setState(int newState) { |
512 |
state = newState; |
513 |
} |
514 |
|
515 |
/** |
516 |
* Atomically sets synchronization state to the given updated |
517 |
* value if the current state value equals the expected value. |
518 |
* This operation has memory semantics of a {@code volatile} read |
519 |
* and write. |
520 |
* |
521 |
* @param expect the expected value |
522 |
* @param update the new value |
523 |
* @return {@code true} if successful. False return indicates that the actual |
524 |
* value was not equal to the expected value. |
525 |
*/ |
526 |
protected final boolean compareAndSetState(int expect, int update) { |
527 |
return U.compareAndSetInt(this, STATE, expect, update); |
528 |
} |
529 |
|
530 |
// Queuing utilities |
531 |
|
532 |
private boolean casTail(Node c, Node v) { |
533 |
return U.compareAndSetReference(this, TAIL, c, v); |
534 |
} |
535 |
|
536 |
/** tries once to CAS a new dummy node for head */ |
537 |
private void tryInitializeHead() { |
538 |
Node h = new ExclusiveNode(); |
539 |
if (U.compareAndSetReference(this, HEAD, null, h)) |
540 |
tail = h; |
541 |
} |
542 |
|
543 |
/** |
544 |
* Enqueues the node unless null. (Currently used only for |
545 |
* ConditionNodes; other cases are interleaved with acquires.) |
546 |
*/ |
547 |
final void enqueue(Node node) { |
548 |
if (node != null) { |
549 |
for (;;) { |
550 |
Node t = tail; |
551 |
node.setPrevRelaxed(t); // avoid unnecessary fence |
552 |
if (t == null) // initialize |
553 |
tryInitializeHead(); |
554 |
else if (casTail(t, node)) { |
555 |
t.next = node; |
556 |
if (t.status < 0) // wake up to clean link |
557 |
LockSupport.unpark(node.waiter); |
558 |
break; |
559 |
} |
560 |
} |
561 |
} |
562 |
} |
563 |
|
564 |
/** Returns true if node is found in traversal from tail */ |
565 |
final boolean isEnqueued(Node node) { |
566 |
for (Node t = tail; t != null; t = t.prev) |
567 |
if (t == node) |
568 |
return true; |
569 |
return false; |
570 |
} |
571 |
|
572 |
/** |
573 |
* Wakes up the successor of given node, if one exists, and unsets its |
574 |
* WAITING status to avoid park race. This may fail to wake up an |
575 |
* eligible thread when one or more have been cancelled, but |
576 |
* cancelAcquire ensures liveness. |
577 |
*/ |
578 |
private static void signalNext(Node h) { |
579 |
Node s; |
580 |
if (h != null && (s = h.next) != null && s.status != 0) { |
581 |
s.getAndUnsetStatus(WAITING); |
582 |
LockSupport.unpark(s.waiter); |
583 |
} |
584 |
} |
585 |
|
586 |
/** Wakes up the given node if in shared mode */ |
587 |
private static void signalNextIfShared(Node h) { |
588 |
Node s; |
589 |
if (h != null && (s = h.next) != null && |
590 |
(s instanceof SharedNode) && s.status != 0) { |
591 |
s.getAndUnsetStatus(WAITING); |
592 |
LockSupport.unpark(s.waiter); |
593 |
} |
594 |
} |
595 |
|
596 |
/** |
597 |
* Main acquire method, invoked by all exported acquire methods. |
598 |
* |
599 |
* @param node null unless a reacquiring Condition |
600 |
* @param arg the acquire argument |
601 |
* @param shared true if shared mode else exclusive |
602 |
* @param interruptible if abort and return negative on interrupt |
603 |
* @param timed if true use timed waits |
604 |
* @param time if timed, the System.nanoTime value to timeout |
605 |
* @return positive if acquired, 0 if timed out, negative if interrupted |
606 |
*/ |
607 |
final int acquire(Node node, int arg, boolean shared, |
608 |
boolean interruptible, boolean timed, long time) { |
609 |
Thread current = Thread.currentThread(); |
610 |
byte spins = 0, postSpins = 0; // retries upon unpark of first thread |
611 |
boolean interrupted = false, first = false; |
612 |
Node pred = null; // predecessor of node when enqueued |
613 |
|
614 |
/* |
615 |
* Repeatedly: |
616 |
* Check if node now first |
617 |
* if so, ensure head stable, else ensure valid predecessor |
618 |
* if node is first or not yet enqueued, try acquiring |
619 |
* else if node not yet created, create it |
620 |
* else if not yet enqueued, try once to enqueue |
621 |
* else if woken from park, retry (up to postSpins times) |
622 |
* else if WAITING status not set, set and retry |
623 |
* else park and clear WAITING status, and check cancellation |
624 |
*/ |
625 |
|
626 |
for (;;) { |
627 |
if (!first && (pred = (node == null) ? null : node.prev) != null && |
628 |
!(first = (head == pred))) { |
629 |
if (pred.status < 0) { |
630 |
cleanQueue(); // predecessor cancelled |
631 |
continue; |
632 |
} else if (pred.prev == null) { |
633 |
Thread.onSpinWait(); // ensure serialization |
634 |
continue; |
635 |
} |
636 |
} |
637 |
if (first || pred == null) { |
638 |
boolean acquired; |
639 |
try { |
640 |
if (shared) |
641 |
acquired = (tryAcquireShared(arg) >= 0); |
642 |
else |
643 |
acquired = tryAcquire(arg); |
644 |
} catch (Throwable ex) { |
645 |
cancelAcquire(node, interrupted, false); |
646 |
throw ex; |
647 |
} |
648 |
if (acquired) { |
649 |
if (first) { |
650 |
node.prev = null; |
651 |
head = node; |
652 |
pred.next = null; |
653 |
node.waiter = null; |
654 |
if (shared) |
655 |
signalNextIfShared(node); |
656 |
if (interrupted) |
657 |
current.interrupt(); |
658 |
} |
659 |
return 1; |
660 |
} |
661 |
} |
662 |
if (node == null) { // allocate; retry before enqueue |
663 |
if (shared) |
664 |
node = new SharedNode(); |
665 |
else |
666 |
node = new ExclusiveNode(); |
667 |
} else if (pred == null) { // try to enqueue |
668 |
node.waiter = current; |
669 |
Node t = tail; |
670 |
node.setPrevRelaxed(t); // avoid unnecessary fence |
671 |
if (t == null) |
672 |
tryInitializeHead(); |
673 |
else if (!casTail(t, node)) |
674 |
node.setPrevRelaxed(null); // back out |
675 |
else |
676 |
t.next = node; |
677 |
} else if (first && spins != 0) { |
678 |
--spins; // reduce unfairness on rewaits |
679 |
Thread.onSpinWait(); |
680 |
} else if (node.status == 0) { |
681 |
node.status = WAITING; // enable signal and recheck |
682 |
} else { |
683 |
long nanos; |
684 |
spins = postSpins = (byte)((postSpins << 1) | 1); |
685 |
if (!timed) |
686 |
LockSupport.park(this); |
687 |
else if ((nanos = time - System.nanoTime()) > 0L) |
688 |
LockSupport.parkNanos(this, nanos); |
689 |
else |
690 |
break; |
691 |
node.clearStatus(); |
692 |
if ((interrupted |= Thread.interrupted()) && interruptible) |
693 |
break; |
694 |
} |
695 |
} |
696 |
return cancelAcquire(node, interrupted, interruptible); |
697 |
} |
698 |
|
699 |
/** |
700 |
* Possibly repeatedly traverses from tail, unsplicing cancelled |
701 |
* nodes until none are found. Unparks nodes that may have been |
702 |
* relinked to be next eligible acquirer. |
703 |
*/ |
704 |
private void cleanQueue() { |
705 |
for (;;) { // restart point |
706 |
for (Node q = tail, s = null, p, n;;) { // (p, q, s) triples |
707 |
if (q == null || (p = q.prev) == null) |
708 |
return; // end of list |
709 |
if (s == null ? tail != q : (s.prev != q || s.status < 0)) |
710 |
break; // inconsistent |
711 |
if (q.status < 0) { // cancelled |
712 |
if ((s == null ? casTail(q, p) : s.casPrev(q, p)) && |
713 |
q.prev == p) { |
714 |
p.casNext(q, s); // OK if fails |
715 |
if (p.prev == null) |
716 |
signalNext(p); |
717 |
} |
718 |
break; |
719 |
} |
720 |
if ((n = p.next) != q) { // help finish |
721 |
if (n != null && q.prev == p) { |
722 |
p.casNext(n, q); |
723 |
if (p.prev == null) |
724 |
signalNext(p); |
725 |
} |
726 |
break; |
727 |
} |
728 |
s = q; |
729 |
q = q.prev; |
730 |
} |
731 |
} |
732 |
} |
733 |
|
734 |
/** |
735 |
* Cancels an ongoing attempt to acquire. |
736 |
* |
737 |
* @param node the node (may be null if cancelled before enqueuing) |
738 |
* @param interrupted true if thread interrupted |
739 |
* @param interruptible if should report interruption vs reset |
740 |
*/ |
741 |
private int cancelAcquire(Node node, boolean interrupted, |
742 |
boolean interruptible) { |
743 |
if (node != null) { |
744 |
node.waiter = null; |
745 |
node.status = CANCELLED; |
746 |
if (node.prev != null) |
747 |
cleanQueue(); |
748 |
} |
749 |
if (interrupted) { |
750 |
if (interruptible) |
751 |
return CANCELLED; |
752 |
else |
753 |
Thread.currentThread().interrupt(); |
754 |
} |
755 |
return 0; |
756 |
} |
757 |
|
758 |
// Main exported methods |
759 |
|
760 |
/** |
761 |
* Attempts to acquire in exclusive mode. This method should query |
762 |
* if the state of the object permits it to be acquired in the |
763 |
* exclusive mode, and if so to acquire it. |
764 |
* |
765 |
* <p>This method is always invoked by the thread performing |
766 |
* acquire. If this method reports failure, the acquire method |
767 |
* may queue the thread, if it is not already queued, until it is |
768 |
* signalled by a release from some other thread. This can be used |
769 |
* to implement method {@link Lock#tryLock()}. |
770 |
* |
771 |
* <p>The default |
772 |
* implementation throws {@link UnsupportedOperationException}. |
773 |
* |
774 |
* @param arg the acquire argument. This value is always the one |
775 |
* passed to an acquire method, or is the value saved on entry |
776 |
* to a condition wait. The value is otherwise uninterpreted |
777 |
* and can represent anything you like. |
778 |
* @return {@code true} if successful. Upon success, this object has |
779 |
* been acquired. |
780 |
* @throws IllegalMonitorStateException if acquiring would place this |
781 |
* synchronizer in an illegal state. This exception must be |
782 |
* thrown in a consistent fashion for synchronization to work |
783 |
* correctly. |
784 |
* @throws UnsupportedOperationException if exclusive mode is not supported |
785 |
*/ |
786 |
protected boolean tryAcquire(int arg) { |
787 |
throw new UnsupportedOperationException(); |
788 |
} |
789 |
|
790 |
/** |
791 |
* Attempts to set the state to reflect a release in exclusive |
792 |
* mode. |
793 |
* |
794 |
* <p>This method is always invoked by the thread performing release. |
795 |
* |
796 |
* <p>The default implementation throws |
797 |
* {@link UnsupportedOperationException}. |
798 |
* |
799 |
* @param arg the release argument. This value is always the one |
800 |
* passed to a release method, or the current state value upon |
801 |
* entry to a condition wait. The value is otherwise |
802 |
* uninterpreted and can represent anything you like. |
803 |
* @return {@code true} if this object is now in a fully released |
804 |
* state, so that any waiting threads may attempt to acquire; |
805 |
* and {@code false} otherwise. |
806 |
* @throws IllegalMonitorStateException if releasing would place this |
807 |
* synchronizer in an illegal state. This exception must be |
808 |
* thrown in a consistent fashion for synchronization to work |
809 |
* correctly. |
810 |
* @throws UnsupportedOperationException if exclusive mode is not supported |
811 |
*/ |
812 |
protected boolean tryRelease(int arg) { |
813 |
throw new UnsupportedOperationException(); |
814 |
} |
815 |
|
816 |
/** |
817 |
* Attempts to acquire in shared mode. This method should query if |
818 |
* the state of the object permits it to be acquired in the shared |
819 |
* mode, and if so to acquire it. |
820 |
* |
821 |
* <p>This method is always invoked by the thread performing |
822 |
* acquire. If this method reports failure, the acquire method |
823 |
* may queue the thread, if it is not already queued, until it is |
824 |
* signalled by a release from some other thread. |
825 |
* |
826 |
* <p>The default implementation throws {@link |
827 |
* UnsupportedOperationException}. |
828 |
* |
829 |
* @param arg the acquire argument. This value is always the one |
830 |
* passed to an acquire method, or is the value saved on entry |
831 |
* to a condition wait. The value is otherwise uninterpreted |
832 |
* and can represent anything you like. |
833 |
* @return a negative value on failure; zero if acquisition in shared |
834 |
* mode succeeded but no subsequent shared-mode acquire can |
835 |
* succeed; and a positive value if acquisition in shared |
836 |
* mode succeeded and subsequent shared-mode acquires might |
837 |
* also succeed, in which case a subsequent waiting thread |
838 |
* must check availability. (Support for three different |
839 |
* return values enables this method to be used in contexts |
840 |
* where acquires only sometimes act exclusively.) Upon |
841 |
* success, this object has been acquired. |
842 |
* @throws IllegalMonitorStateException if acquiring would place this |
843 |
* synchronizer in an illegal state. This exception must be |
844 |
* thrown in a consistent fashion for synchronization to work |
845 |
* correctly. |
846 |
* @throws UnsupportedOperationException if shared mode is not supported |
847 |
*/ |
848 |
protected int tryAcquireShared(int arg) { |
849 |
throw new UnsupportedOperationException(); |
850 |
} |
851 |
|
852 |
/** |
853 |
* Attempts to set the state to reflect a release in shared mode. |
854 |
* |
855 |
* <p>This method is always invoked by the thread performing release. |
856 |
* |
857 |
* <p>The default implementation throws |
858 |
* {@link UnsupportedOperationException}. |
859 |
* |
860 |
* @param arg the release argument. This value is always the one |
861 |
* passed to a release method, or the current state value upon |
862 |
* entry to a condition wait. The value is otherwise |
863 |
* uninterpreted and can represent anything you like. |
864 |
* @return {@code true} if this release of shared mode may permit a |
865 |
* waiting acquire (shared or exclusive) to succeed; and |
866 |
* {@code false} otherwise |
867 |
* @throws IllegalMonitorStateException if releasing would place this |
868 |
* synchronizer in an illegal state. This exception must be |
869 |
* thrown in a consistent fashion for synchronization to work |
870 |
* correctly. |
871 |
* @throws UnsupportedOperationException if shared mode is not supported |
872 |
*/ |
873 |
protected boolean tryReleaseShared(int arg) { |
874 |
throw new UnsupportedOperationException(); |
875 |
} |
876 |
|
877 |
/** |
878 |
* Returns {@code true} if synchronization is held exclusively with |
879 |
* respect to the current (calling) thread. This method is invoked |
880 |
* upon each call to a {@link ConditionObject} method. |
881 |
* |
882 |
* <p>The default implementation throws {@link |
883 |
* UnsupportedOperationException}. This method is invoked |
884 |
* internally only within {@link ConditionObject} methods, so need |
885 |
* not be defined if conditions are not used. |
886 |
* |
887 |
* @return {@code true} if synchronization is held exclusively; |
888 |
* {@code false} otherwise |
889 |
* @throws UnsupportedOperationException if conditions are not supported |
890 |
*/ |
891 |
protected boolean isHeldExclusively() { |
892 |
throw new UnsupportedOperationException(); |
893 |
} |
894 |
|
895 |
/** |
896 |
* Acquires in exclusive mode, ignoring interrupts. Implemented |
897 |
* by invoking at least once {@link #tryAcquire}, |
898 |
* returning on success. Otherwise the thread is queued, possibly |
899 |
* repeatedly blocking and unblocking, invoking {@link |
900 |
* #tryAcquire} until success. This method can be used |
901 |
* to implement method {@link Lock#lock}. |
902 |
* |
903 |
* @param arg the acquire argument. This value is conveyed to |
904 |
* {@link #tryAcquire} but is otherwise uninterpreted and |
905 |
* can represent anything you like. |
906 |
*/ |
907 |
public final void acquire(int arg) { |
908 |
if (!tryAcquire(arg)) |
909 |
acquire(null, arg, false, false, false, 0L); |
910 |
} |
911 |
|
912 |
/** |
913 |
* Acquires in exclusive mode, aborting if interrupted. |
914 |
* Implemented by first checking interrupt status, then invoking |
915 |
* at least once {@link #tryAcquire}, returning on |
916 |
* success. Otherwise the thread is queued, possibly repeatedly |
917 |
* blocking and unblocking, invoking {@link #tryAcquire} |
918 |
* until success or the thread is interrupted. This method can be |
919 |
* used to implement method {@link Lock#lockInterruptibly}. |
920 |
* |
921 |
* @param arg the acquire argument. This value is conveyed to |
922 |
* {@link #tryAcquire} but is otherwise uninterpreted and |
923 |
* can represent anything you like. |
924 |
* @throws InterruptedException if the current thread is interrupted |
925 |
*/ |
926 |
public final void acquireInterruptibly(int arg) |
927 |
throws InterruptedException { |
928 |
if (Thread.interrupted() || |
929 |
(!tryAcquire(arg) && acquire(null, arg, false, true, false, 0L) < 0)) |
930 |
throw new InterruptedException(); |
931 |
} |
932 |
|
933 |
/** |
934 |
* Attempts to acquire in exclusive mode, aborting if interrupted, |
935 |
* and failing if the given timeout elapses. Implemented by first |
936 |
* checking interrupt status, then invoking at least once {@link |
937 |
* #tryAcquire}, returning on success. Otherwise, the thread is |
938 |
* queued, possibly repeatedly blocking and unblocking, invoking |
939 |
* {@link #tryAcquire} until success or the thread is interrupted |
940 |
* or the timeout elapses. This method can be used to implement |
941 |
* method {@link Lock#tryLock(long, TimeUnit)}. |
942 |
* |
943 |
* @param arg the acquire argument. This value is conveyed to |
944 |
* {@link #tryAcquire} but is otherwise uninterpreted and |
945 |
* can represent anything you like. |
946 |
* @param nanosTimeout the maximum number of nanoseconds to wait |
947 |
* @return {@code true} if acquired; {@code false} if timed out |
948 |
* @throws InterruptedException if the current thread is interrupted |
949 |
*/ |
950 |
public final boolean tryAcquireNanos(int arg, long nanosTimeout) |
951 |
throws InterruptedException { |
952 |
if (!Thread.interrupted()) { |
953 |
if (tryAcquire(arg)) |
954 |
return true; |
955 |
if (nanosTimeout <= 0L) |
956 |
return false; |
957 |
int stat = acquire(null, arg, false, true, true, |
958 |
System.nanoTime() + nanosTimeout); |
959 |
if (stat > 0) |
960 |
return true; |
961 |
if (stat == 0) |
962 |
return false; |
963 |
} |
964 |
throw new InterruptedException(); |
965 |
} |
966 |
|
967 |
/** |
968 |
* Releases in exclusive mode. Implemented by unblocking one or |
969 |
* more threads if {@link #tryRelease} returns true. |
970 |
* This method can be used to implement method {@link Lock#unlock}. |
971 |
* |
972 |
* @param arg the release argument. This value is conveyed to |
973 |
* {@link #tryRelease} but is otherwise uninterpreted and |
974 |
* can represent anything you like. |
975 |
* @return the value returned from {@link #tryRelease} |
976 |
*/ |
977 |
public final boolean release(int arg) { |
978 |
if (tryRelease(arg)) { |
979 |
signalNext(head); |
980 |
return true; |
981 |
} |
982 |
return false; |
983 |
} |
984 |
|
985 |
/** |
986 |
* Acquires in shared mode, ignoring interrupts. Implemented by |
987 |
* first invoking at least once {@link #tryAcquireShared}, |
988 |
* returning on success. Otherwise the thread is queued, possibly |
989 |
* repeatedly blocking and unblocking, invoking {@link |
990 |
* #tryAcquireShared} until success. |
991 |
* |
992 |
* @param arg the acquire argument. This value is conveyed to |
993 |
* {@link #tryAcquireShared} but is otherwise uninterpreted |
994 |
* and can represent anything you like. |
995 |
*/ |
996 |
public final void acquireShared(int arg) { |
997 |
if (tryAcquireShared(arg) < 0) |
998 |
acquire(null, arg, true, false, false, 0L); |
999 |
} |
1000 |
|
1001 |
/** |
1002 |
* Acquires in shared mode, aborting if interrupted. Implemented |
1003 |
* by first checking interrupt status, then invoking at least once |
1004 |
* {@link #tryAcquireShared}, returning on success. Otherwise the |
1005 |
* thread is queued, possibly repeatedly blocking and unblocking, |
1006 |
* invoking {@link #tryAcquireShared} until success or the thread |
1007 |
* is interrupted. |
1008 |
* @param arg the acquire argument. |
1009 |
* This value is conveyed to {@link #tryAcquireShared} but is |
1010 |
* otherwise uninterpreted and can represent anything |
1011 |
* you like. |
1012 |
* @throws InterruptedException if the current thread is interrupted |
1013 |
*/ |
1014 |
public final void acquireSharedInterruptibly(int arg) |
1015 |
throws InterruptedException { |
1016 |
if (Thread.interrupted() || |
1017 |
(tryAcquireShared(arg) < 0 && |
1018 |
acquire(null, arg, true, true, false, 0L) < 0)) |
1019 |
throw new InterruptedException(); |
1020 |
} |
1021 |
|
1022 |
/** |
1023 |
* Attempts to acquire in shared mode, aborting if interrupted, and |
1024 |
* failing if the given timeout elapses. Implemented by first |
1025 |
* checking interrupt status, then invoking at least once {@link |
1026 |
* #tryAcquireShared}, returning on success. Otherwise, the |
1027 |
* thread is queued, possibly repeatedly blocking and unblocking, |
1028 |
* invoking {@link #tryAcquireShared} until success or the thread |
1029 |
* is interrupted or the timeout elapses. |
1030 |
* |
1031 |
* @param arg the acquire argument. This value is conveyed to |
1032 |
* {@link #tryAcquireShared} but is otherwise uninterpreted |
1033 |
* and can represent anything you like. |
1034 |
* @param nanosTimeout the maximum number of nanoseconds to wait |
1035 |
* @return {@code true} if acquired; {@code false} if timed out |
1036 |
* @throws InterruptedException if the current thread is interrupted |
1037 |
*/ |
1038 |
public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout) |
1039 |
throws InterruptedException { |
1040 |
if (!Thread.interrupted()) { |
1041 |
if (tryAcquireShared(arg) >= 0) |
1042 |
return true; |
1043 |
if (nanosTimeout <= 0L) |
1044 |
return false; |
1045 |
int stat = acquire(null, arg, true, true, true, |
1046 |
System.nanoTime() + nanosTimeout); |
1047 |
if (stat > 0) |
1048 |
return true; |
1049 |
if (stat == 0) |
1050 |
return false; |
1051 |
} |
1052 |
throw new InterruptedException(); |
1053 |
} |
1054 |
|
1055 |
/** |
1056 |
* Releases in shared mode. Implemented by unblocking one or more |
1057 |
* threads if {@link #tryReleaseShared} returns true. |
1058 |
* |
1059 |
* @param arg the release argument. This value is conveyed to |
1060 |
* {@link #tryReleaseShared} but is otherwise uninterpreted |
1061 |
* and can represent anything you like. |
1062 |
* @return the value returned from {@link #tryReleaseShared} |
1063 |
*/ |
1064 |
public final boolean releaseShared(int arg) { |
1065 |
if (tryReleaseShared(arg)) { |
1066 |
signalNext(head); |
1067 |
return true; |
1068 |
} |
1069 |
return false; |
1070 |
} |
1071 |
|
1072 |
// Queue inspection methods |
1073 |
|
1074 |
/** |
1075 |
* Queries whether any threads are waiting to acquire. Note that |
1076 |
* because cancellations due to interrupts and timeouts may occur |
1077 |
* at any time, a {@code true} return does not guarantee that any |
1078 |
* other thread will ever acquire. |
1079 |
* |
1080 |
* @return {@code true} if there may be other threads waiting to acquire |
1081 |
*/ |
1082 |
public final boolean hasQueuedThreads() { |
1083 |
for (Node p = tail, h = head; p != h && p != null; p = p.prev) |
1084 |
if (p.status >= 0) |
1085 |
return true; |
1086 |
return false; |
1087 |
} |
1088 |
|
1089 |
/** |
1090 |
* Queries whether any threads have ever contended to acquire this |
1091 |
* synchronizer; that is, if an acquire method has ever blocked. |
1092 |
* |
1093 |
* <p>In this implementation, this operation returns in |
1094 |
* constant time. |
1095 |
* |
1096 |
* @return {@code true} if there has ever been contention |
1097 |
*/ |
1098 |
public final boolean hasContended() { |
1099 |
return head != null; |
1100 |
} |
1101 |
|
1102 |
/** |
1103 |
* Returns the first (longest-waiting) thread in the queue, or |
1104 |
* {@code null} if no threads are currently queued. |
1105 |
* |
1106 |
* <p>In this implementation, this operation normally returns in |
1107 |
* constant time, but may iterate upon contention if other threads are |
1108 |
* concurrently modifying the queue. |
1109 |
* |
1110 |
* @return the first (longest-waiting) thread in the queue, or |
1111 |
* {@code null} if no threads are currently queued |
1112 |
*/ |
1113 |
public final Thread getFirstQueuedThread() { |
1114 |
Thread first = null, w; Node h, s; |
1115 |
if ((h = head) != null && ((s = h.next) == null || |
1116 |
(first = s.waiter) == null || |
1117 |
s.prev == null)) { |
1118 |
// traverse from tail on stale reads |
1119 |
for (Node p = tail, q; p != null && (q = p.prev) != null; p = q) |
1120 |
if ((w = p.waiter) != null) |
1121 |
first = w; |
1122 |
} |
1123 |
return first; |
1124 |
} |
1125 |
|
1126 |
/** |
1127 |
* Returns true if the given thread is currently queued. |
1128 |
* |
1129 |
* <p>This implementation traverses the queue to determine |
1130 |
* presence of the given thread. |
1131 |
* |
1132 |
* @param thread the thread |
1133 |
* @return {@code true} if the given thread is on the queue |
1134 |
* @throws NullPointerException if the thread is null |
1135 |
*/ |
1136 |
public final boolean isQueued(Thread thread) { |
1137 |
if (thread == null) |
1138 |
throw new NullPointerException(); |
1139 |
for (Node p = tail; p != null; p = p.prev) |
1140 |
if (p.waiter == thread) |
1141 |
return true; |
1142 |
return false; |
1143 |
} |
1144 |
|
1145 |
/** |
1146 |
* Returns {@code true} if the apparent first queued thread, if one |
1147 |
* exists, is waiting in exclusive mode. If this method returns |
1148 |
* {@code true}, and the current thread is attempting to acquire in |
1149 |
* shared mode (that is, this method is invoked from {@link |
1150 |
* #tryAcquireShared}) then it is guaranteed that the current thread |
1151 |
* is not the first queued thread. Used only as a heuristic in |
1152 |
* ReentrantReadWriteLock. |
1153 |
*/ |
1154 |
final boolean apparentlyFirstQueuedIsExclusive() { |
1155 |
Node h, s; |
1156 |
return (h = head) != null && (s = h.next) != null && |
1157 |
!(s instanceof SharedNode) && s.waiter != null; |
1158 |
} |
1159 |
|
1160 |
/** |
1161 |
* Queries whether any threads have been waiting to acquire longer |
1162 |
* than the current thread. |
1163 |
* |
1164 |
* <p>An invocation of this method is equivalent to (but may be |
1165 |
* more efficient than): |
1166 |
* <pre> {@code |
1167 |
* getFirstQueuedThread() != Thread.currentThread() |
1168 |
* && hasQueuedThreads()}</pre> |
1169 |
* |
1170 |
* <p>Note that because cancellations due to interrupts and |
1171 |
* timeouts may occur at any time, a {@code true} return does not |
1172 |
* guarantee that some other thread will acquire before the current |
1173 |
* thread. Likewise, it is possible for another thread to win a |
1174 |
* race to enqueue after this method has returned {@code false}, |
1175 |
* due to the queue being empty. |
1176 |
* |
1177 |
* <p>This method is designed to be used by a fair synchronizer to |
1178 |
* avoid <a href="AbstractQueuedSynchronizer.html#barging">barging</a>. |
1179 |
* Such a synchronizer's {@link #tryAcquire} method should return |
1180 |
* {@code false}, and its {@link #tryAcquireShared} method should |
1181 |
* return a negative value, if this method returns {@code true} |
1182 |
* (unless this is a reentrant acquire). For example, the {@code |
1183 |
* tryAcquire} method for a fair, reentrant, exclusive mode |
1184 |
* synchronizer might look like this: |
1185 |
* |
1186 |
* <pre> {@code |
1187 |
* protected boolean tryAcquire(int arg) { |
1188 |
* if (isHeldExclusively()) { |
1189 |
* // A reentrant acquire; increment hold count |
1190 |
* return true; |
1191 |
* } else if (hasQueuedPredecessors()) { |
1192 |
* return false; |
1193 |
* } else { |
1194 |
* // try to acquire normally |
1195 |
* } |
1196 |
* }}</pre> |
1197 |
* |
1198 |
* @return {@code true} if there is a queued thread preceding the |
1199 |
* current thread, and {@code false} if the current thread |
1200 |
* is at the head of the queue or the queue is empty |
1201 |
* @since 1.7 |
1202 |
*/ |
1203 |
public final boolean hasQueuedPredecessors() { |
1204 |
Thread first = null; Node h, s; |
1205 |
if ((h = head) != null && ((s = h.next) == null || |
1206 |
(first = s.waiter) == null || |
1207 |
s.prev == null)) |
1208 |
first = getFirstQueuedThread(); // retry via getFirstQueuedThread |
1209 |
return first != null && first != Thread.currentThread(); |
1210 |
} |
1211 |
|
1212 |
// Instrumentation and monitoring methods |
1213 |
|
1214 |
/** |
1215 |
* Returns an estimate of the number of threads waiting to |
1216 |
* acquire. The value is only an estimate because the number of |
1217 |
* threads may change dynamically while this method traverses |
1218 |
* internal data structures. This method is designed for use in |
1219 |
* monitoring system state, not for synchronization control. |
1220 |
* |
1221 |
* @return the estimated number of threads waiting to acquire |
1222 |
*/ |
1223 |
public final int getQueueLength() { |
1224 |
int n = 0; |
1225 |
for (Node p = tail; p != null; p = p.prev) { |
1226 |
if (p.waiter != null) |
1227 |
++n; |
1228 |
} |
1229 |
return n; |
1230 |
} |
1231 |
|
1232 |
/** |
1233 |
* Returns a collection containing threads that may be waiting to |
1234 |
* acquire. Because the actual set of threads may change |
1235 |
* dynamically while constructing this result, the returned |
1236 |
* collection is only a best-effort estimate. The elements of the |
1237 |
* returned collection are in no particular order. This method is |
1238 |
* designed to facilitate construction of subclasses that provide |
1239 |
* more extensive monitoring facilities. |
1240 |
* |
1241 |
* @return the collection of threads |
1242 |
*/ |
1243 |
public final Collection<Thread> getQueuedThreads() { |
1244 |
ArrayList<Thread> list = new ArrayList<>(); |
1245 |
for (Node p = tail; p != null; p = p.prev) { |
1246 |
Thread t = p.waiter; |
1247 |
if (t != null) |
1248 |
list.add(t); |
1249 |
} |
1250 |
return list; |
1251 |
} |
1252 |
|
1253 |
/** |
1254 |
* Returns a collection containing threads that may be waiting to |
1255 |
* acquire in exclusive mode. This has the same properties |
1256 |
* as {@link #getQueuedThreads} except that it only returns |
1257 |
* those threads waiting due to an exclusive acquire. |
1258 |
* |
1259 |
* @return the collection of threads |
1260 |
*/ |
1261 |
public final Collection<Thread> getExclusiveQueuedThreads() { |
1262 |
ArrayList<Thread> list = new ArrayList<>(); |
1263 |
for (Node p = tail; p != null; p = p.prev) { |
1264 |
if (!(p instanceof SharedNode)) { |
1265 |
Thread t = p.waiter; |
1266 |
if (t != null) |
1267 |
list.add(t); |
1268 |
} |
1269 |
} |
1270 |
return list; |
1271 |
} |
1272 |
|
1273 |
/** |
1274 |
* Returns a collection containing threads that may be waiting to |
1275 |
* acquire in shared mode. This has the same properties |
1276 |
* as {@link #getQueuedThreads} except that it only returns |
1277 |
* those threads waiting due to a shared acquire. |
1278 |
* |
1279 |
* @return the collection of threads |
1280 |
*/ |
1281 |
public final Collection<Thread> getSharedQueuedThreads() { |
1282 |
ArrayList<Thread> list = new ArrayList<>(); |
1283 |
for (Node p = tail; p != null; p = p.prev) { |
1284 |
if (p instanceof SharedNode) { |
1285 |
Thread t = p.waiter; |
1286 |
if (t != null) |
1287 |
list.add(t); |
1288 |
} |
1289 |
} |
1290 |
return list; |
1291 |
} |
1292 |
|
1293 |
/** |
1294 |
* Returns a string identifying this synchronizer, as well as its state. |
1295 |
* The state, in brackets, includes the String {@code "State ="} |
1296 |
* followed by the current value of {@link #getState}, and either |
1297 |
* {@code "nonempty"} or {@code "empty"} depending on whether the |
1298 |
* queue is empty. |
1299 |
* |
1300 |
* @return a string identifying this synchronizer, as well as its state |
1301 |
*/ |
1302 |
public String toString() { |
1303 |
return super.toString() |
1304 |
+ "[State = " + getState() + ", " |
1305 |
+ (hasQueuedThreads() ? "non" : "") + "empty queue]"; |
1306 |
} |
1307 |
|
1308 |
// Instrumentation methods for conditions |
1309 |
|
1310 |
/** |
1311 |
* Queries whether the given ConditionObject |
1312 |
* uses this synchronizer as its lock. |
1313 |
* |
1314 |
* @param condition the condition |
1315 |
* @return {@code true} if owned |
1316 |
* @throws NullPointerException if the condition is null |
1317 |
*/ |
1318 |
public final boolean owns(ConditionObject condition) { |
1319 |
return condition.isOwnedBy(this); |
1320 |
} |
1321 |
|
1322 |
/** |
1323 |
* Queries whether any threads are waiting on the given condition |
1324 |
* associated with this synchronizer. Note that because timeouts |
1325 |
* and interrupts may occur at any time, a {@code true} return |
1326 |
* does not guarantee that a future {@code signal} will awaken |
1327 |
* any threads. This method is designed primarily for use in |
1328 |
* monitoring of the system state. |
1329 |
* |
1330 |
* @param condition the condition |
1331 |
* @return {@code true} if there are any waiting threads |
1332 |
* @throws IllegalMonitorStateException if exclusive synchronization |
1333 |
* is not held |
1334 |
* @throws IllegalArgumentException if the given condition is |
1335 |
* not associated with this synchronizer |
1336 |
* @throws NullPointerException if the condition is null |
1337 |
*/ |
1338 |
public final boolean hasWaiters(ConditionObject condition) { |
1339 |
if (!owns(condition)) |
1340 |
throw new IllegalArgumentException("Not owner"); |
1341 |
return condition.hasWaiters(); |
1342 |
} |
1343 |
|
1344 |
/** |
1345 |
* Returns an estimate of the number of threads waiting on the |
1346 |
* given condition associated with this synchronizer. Note that |
1347 |
* because timeouts and interrupts may occur at any time, the |
1348 |
* estimate serves only as an upper bound on the actual number of |
1349 |
* waiters. This method is designed for use in monitoring system |
1350 |
* state, not for synchronization control. |
1351 |
* |
1352 |
* @param condition the condition |
1353 |
* @return the estimated number of waiting threads |
1354 |
* @throws IllegalMonitorStateException if exclusive synchronization |
1355 |
* is not held |
1356 |
* @throws IllegalArgumentException if the given condition is |
1357 |
* not associated with this synchronizer |
1358 |
* @throws NullPointerException if the condition is null |
1359 |
*/ |
1360 |
public final int getWaitQueueLength(ConditionObject condition) { |
1361 |
if (!owns(condition)) |
1362 |
throw new IllegalArgumentException("Not owner"); |
1363 |
return condition.getWaitQueueLength(); |
1364 |
} |
1365 |
|
1366 |
/** |
1367 |
* Returns a collection containing those threads that may be |
1368 |
* waiting on the given condition associated with this |
1369 |
* synchronizer. Because the actual set of threads may change |
1370 |
* dynamically while constructing this result, the returned |
1371 |
* collection is only a best-effort estimate. The elements of the |
1372 |
* returned collection are in no particular order. |
1373 |
* |
1374 |
* @param condition the condition |
1375 |
* @return the collection of threads |
1376 |
* @throws IllegalMonitorStateException if exclusive synchronization |
1377 |
* is not held |
1378 |
* @throws IllegalArgumentException if the given condition is |
1379 |
* not associated with this synchronizer |
1380 |
* @throws NullPointerException if the condition is null |
1381 |
*/ |
1382 |
public final Collection<Thread> getWaitingThreads(ConditionObject condition) { |
1383 |
if (!owns(condition)) |
1384 |
throw new IllegalArgumentException("Not owner"); |
1385 |
return condition.getWaitingThreads(); |
1386 |
} |
1387 |
|
1388 |
/** |
1389 |
* Condition implementation for a {@link AbstractQueuedSynchronizer} |
1390 |
* serving as the basis of a {@link Lock} implementation. |
1391 |
* |
1392 |
* <p>Method documentation for this class describes mechanics, |
1393 |
* not behavioral specifications from the point of view of Lock |
1394 |
* and Condition users. Exported versions of this class will in |
1395 |
* general need to be accompanied by documentation describing |
1396 |
* condition semantics that rely on those of the associated |
1397 |
* {@code AbstractQueuedSynchronizer}. |
1398 |
* |
1399 |
* <p>This class is Serializable, but all fields are transient, |
1400 |
* so deserialized conditions have no waiters. |
1401 |
*/ |
1402 |
public class ConditionObject implements Condition, java.io.Serializable { |
1403 |
private static final long serialVersionUID = 1173984872572414699L; |
1404 |
/** First node of condition queue. */ |
1405 |
private transient ConditionNode firstWaiter; |
1406 |
/** Last node of condition queue. */ |
1407 |
private transient ConditionNode lastWaiter; |
1408 |
|
1409 |
/** |
1410 |
* Creates a new {@code ConditionObject} instance. |
1411 |
*/ |
1412 |
public ConditionObject() { } |
1413 |
|
1414 |
// Signalling methods |
1415 |
|
1416 |
/** |
1417 |
* Removes and transfers one or all waiters to sync queue. |
1418 |
*/ |
1419 |
private void doSignal(ConditionNode first, boolean all) { |
1420 |
while (first != null) { |
1421 |
ConditionNode next = first.nextWaiter; |
1422 |
if ((firstWaiter = next) == null) |
1423 |
lastWaiter = null; |
1424 |
if ((first.getAndUnsetStatus(COND) & COND) != 0) { |
1425 |
enqueue(first); |
1426 |
if (!all) |
1427 |
break; |
1428 |
} |
1429 |
first = next; |
1430 |
} |
1431 |
} |
1432 |
|
1433 |
/** |
1434 |
* Moves the longest-waiting thread, if one exists, from the |
1435 |
* wait queue for this condition to the wait queue for the |
1436 |
* owning lock. |
1437 |
* |
1438 |
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} |
1439 |
* returns {@code false} |
1440 |
*/ |
1441 |
public final void signal() { |
1442 |
ConditionNode first = firstWaiter; |
1443 |
if (!isHeldExclusively()) |
1444 |
throw new IllegalMonitorStateException(); |
1445 |
if (first != null) |
1446 |
doSignal(first, false); |
1447 |
} |
1448 |
|
1449 |
/** |
1450 |
* Moves all threads from the wait queue for this condition to |
1451 |
* the wait queue for the owning lock. |
1452 |
* |
1453 |
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} |
1454 |
* returns {@code false} |
1455 |
*/ |
1456 |
public final void signalAll() { |
1457 |
ConditionNode first = firstWaiter; |
1458 |
if (!isHeldExclusively()) |
1459 |
throw new IllegalMonitorStateException(); |
1460 |
if (first != null) |
1461 |
doSignal(first, true); |
1462 |
} |
1463 |
|
1464 |
// Waiting methods |
1465 |
|
1466 |
/** |
1467 |
* Adds node to condition list and releases lock. |
1468 |
* |
1469 |
* @param node the node |
1470 |
* @return savedState to reacquire after wait |
1471 |
*/ |
1472 |
private int enableWait(ConditionNode node) { |
1473 |
if (isHeldExclusively()) { |
1474 |
node.waiter = Thread.currentThread(); |
1475 |
node.setStatusRelaxed(COND | WAITING); |
1476 |
ConditionNode last = lastWaiter; |
1477 |
if (last == null) |
1478 |
firstWaiter = node; |
1479 |
else |
1480 |
last.nextWaiter = node; |
1481 |
lastWaiter = node; |
1482 |
int savedState = getState(); |
1483 |
if (release(savedState)) |
1484 |
return savedState; |
1485 |
} |
1486 |
node.status = CANCELLED; // lock not held or inconsistent |
1487 |
throw new IllegalMonitorStateException(); |
1488 |
} |
1489 |
|
1490 |
/** |
1491 |
* Returns true if a node that was initially placed on a condition |
1492 |
* queue is now ready to reacquire on sync queue. |
1493 |
* @param node the node |
1494 |
* @return true if is reacquiring |
1495 |
*/ |
1496 |
private boolean canReacquire(ConditionNode node) { |
1497 |
// check links, not status to avoid enqueue race |
1498 |
Node p; // traverse unless known to be bidirectionally linked |
1499 |
return node != null && (p = node.prev) != null && |
1500 |
(p.next == node || isEnqueued(node)); |
1501 |
} |
1502 |
|
1503 |
/** |
1504 |
* Unlinks the given node and other non-waiting nodes from |
1505 |
* condition queue unless already unlinked. |
1506 |
*/ |
1507 |
private void unlinkCancelledWaiters(ConditionNode node) { |
1508 |
if (node == null || node.nextWaiter != null || node == lastWaiter) { |
1509 |
ConditionNode w = firstWaiter, trail = null; |
1510 |
while (w != null) { |
1511 |
ConditionNode next = w.nextWaiter; |
1512 |
if ((w.status & COND) == 0) { |
1513 |
w.nextWaiter = null; |
1514 |
if (trail == null) |
1515 |
firstWaiter = next; |
1516 |
else |
1517 |
trail.nextWaiter = next; |
1518 |
if (next == null) |
1519 |
lastWaiter = trail; |
1520 |
} else |
1521 |
trail = w; |
1522 |
w = next; |
1523 |
} |
1524 |
} |
1525 |
} |
1526 |
|
1527 |
/** |
1528 |
* Implements uninterruptible condition wait. |
1529 |
* <ol> |
1530 |
* <li>Save lock state returned by {@link #getState}. |
1531 |
* <li>Invoke {@link #release} with saved state as argument, |
1532 |
* throwing IllegalMonitorStateException if it fails. |
1533 |
* <li>Block until signalled. |
1534 |
* <li>Reacquire by invoking specialized version of |
1535 |
* {@link #acquire} with saved state as argument. |
1536 |
* </ol> |
1537 |
*/ |
1538 |
public final void awaitUninterruptibly() { |
1539 |
ConditionNode node = new ConditionNode(); |
1540 |
int savedState = enableWait(node); |
1541 |
LockSupport.setCurrentBlocker(this); // for back-compatibility |
1542 |
boolean interrupted = false, rejected = false; |
1543 |
while (!canReacquire(node)) { |
1544 |
if (Thread.interrupted()) |
1545 |
interrupted = true; |
1546 |
else if ((node.status & COND) != 0) { |
1547 |
try { |
1548 |
if (rejected) |
1549 |
node.block(); |
1550 |
else |
1551 |
ForkJoinPool.managedBlock(node); |
1552 |
} catch (RejectedExecutionException ex) { |
1553 |
rejected = true; |
1554 |
} catch (InterruptedException ie) { |
1555 |
interrupted = true; |
1556 |
} |
1557 |
} else |
1558 |
Thread.onSpinWait(); // awoke while enqueuing |
1559 |
} |
1560 |
LockSupport.setCurrentBlocker(null); |
1561 |
node.clearStatus(); |
1562 |
acquire(node, savedState, false, false, false, 0L); |
1563 |
if (interrupted) |
1564 |
Thread.currentThread().interrupt(); |
1565 |
} |
1566 |
|
1567 |
/** |
1568 |
* Implements interruptible condition wait. |
1569 |
* <ol> |
1570 |
* <li>If current thread is interrupted, throw InterruptedException. |
1571 |
* <li>Save lock state returned by {@link #getState}. |
1572 |
* <li>Invoke {@link #release} with saved state as argument, |
1573 |
* throwing IllegalMonitorStateException if it fails. |
1574 |
* <li>Block until signalled or interrupted. |
1575 |
* <li>Reacquire by invoking specialized version of |
1576 |
* {@link #acquire} with saved state as argument. |
1577 |
* <li>If interrupted while blocked in step 4, throw InterruptedException. |
1578 |
* </ol> |
1579 |
*/ |
1580 |
public final void await() throws InterruptedException { |
1581 |
if (Thread.interrupted()) |
1582 |
throw new InterruptedException(); |
1583 |
ConditionNode node = new ConditionNode(); |
1584 |
int savedState = enableWait(node); |
1585 |
LockSupport.setCurrentBlocker(this); // for back-compatibility |
1586 |
boolean interrupted = false, cancelled = false, rejected = false; |
1587 |
while (!canReacquire(node)) { |
1588 |
if (interrupted |= Thread.interrupted()) { |
1589 |
if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0) |
1590 |
break; // else interrupted after signal |
1591 |
} else if ((node.status & COND) != 0) { |
1592 |
try { |
1593 |
if (rejected) |
1594 |
node.block(); |
1595 |
else |
1596 |
ForkJoinPool.managedBlock(node); |
1597 |
} catch (RejectedExecutionException ex) { |
1598 |
rejected = true; |
1599 |
} catch (InterruptedException ie) { |
1600 |
interrupted = true; |
1601 |
} |
1602 |
} else |
1603 |
Thread.onSpinWait(); // awoke while enqueuing |
1604 |
} |
1605 |
LockSupport.setCurrentBlocker(null); |
1606 |
node.clearStatus(); |
1607 |
acquire(node, savedState, false, false, false, 0L); |
1608 |
if (interrupted) { |
1609 |
if (cancelled) { |
1610 |
unlinkCancelledWaiters(node); |
1611 |
throw new InterruptedException(); |
1612 |
} |
1613 |
Thread.currentThread().interrupt(); |
1614 |
} |
1615 |
} |
1616 |
|
1617 |
/** |
1618 |
* Implements timed condition wait. |
1619 |
* <ol> |
1620 |
* <li>If current thread is interrupted, throw InterruptedException. |
1621 |
* <li>Save lock state returned by {@link #getState}. |
1622 |
* <li>Invoke {@link #release} with saved state as argument, |
1623 |
* throwing IllegalMonitorStateException if it fails. |
1624 |
* <li>Block until signalled, interrupted, or timed out. |
1625 |
* <li>Reacquire by invoking specialized version of |
1626 |
* {@link #acquire} with saved state as argument. |
1627 |
* <li>If interrupted while blocked in step 4, throw InterruptedException. |
1628 |
* </ol> |
1629 |
*/ |
1630 |
public final long awaitNanos(long nanosTimeout) |
1631 |
throws InterruptedException { |
1632 |
if (Thread.interrupted()) |
1633 |
throw new InterruptedException(); |
1634 |
ConditionNode node = new ConditionNode(); |
1635 |
int savedState = enableWait(node); |
1636 |
long nanos = (nanosTimeout < 0L) ? 0L : nanosTimeout; |
1637 |
long deadline = System.nanoTime() + nanos; |
1638 |
boolean cancelled = false, interrupted = false; |
1639 |
while (!canReacquire(node)) { |
1640 |
if ((interrupted |= Thread.interrupted()) || |
1641 |
(nanos = deadline - System.nanoTime()) <= 0L) { |
1642 |
if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0) |
1643 |
break; |
1644 |
} else |
1645 |
LockSupport.parkNanos(this, nanos); |
1646 |
} |
1647 |
node.clearStatus(); |
1648 |
acquire(node, savedState, false, false, false, 0L); |
1649 |
if (cancelled) { |
1650 |
unlinkCancelledWaiters(node); |
1651 |
if (interrupted) |
1652 |
throw new InterruptedException(); |
1653 |
} else if (interrupted) |
1654 |
Thread.currentThread().interrupt(); |
1655 |
long remaining = deadline - System.nanoTime(); // avoid overflow |
1656 |
return (remaining <= nanosTimeout) ? remaining : Long.MIN_VALUE; |
1657 |
} |
1658 |
|
1659 |
/** |
1660 |
* Implements absolute timed condition wait. |
1661 |
* <ol> |
1662 |
* <li>If current thread is interrupted, throw InterruptedException. |
1663 |
* <li>Save lock state returned by {@link #getState}. |
1664 |
* <li>Invoke {@link #release} with saved state as argument, |
1665 |
* throwing IllegalMonitorStateException if it fails. |
1666 |
* <li>Block until signalled, interrupted, or timed out. |
1667 |
* <li>Reacquire by invoking specialized version of |
1668 |
* {@link #acquire} with saved state as argument. |
1669 |
* <li>If interrupted while blocked in step 4, throw InterruptedException. |
1670 |
* <li>If timed out while blocked in step 4, return false, else true. |
1671 |
* </ol> |
1672 |
*/ |
1673 |
public final boolean awaitUntil(Date deadline) |
1674 |
throws InterruptedException { |
1675 |
long abstime = deadline.getTime(); |
1676 |
if (Thread.interrupted()) |
1677 |
throw new InterruptedException(); |
1678 |
ConditionNode node = new ConditionNode(); |
1679 |
int savedState = enableWait(node); |
1680 |
boolean cancelled = false, interrupted = false; |
1681 |
while (!canReacquire(node)) { |
1682 |
if ((interrupted |= Thread.interrupted()) || |
1683 |
System.currentTimeMillis() >= abstime) { |
1684 |
if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0) |
1685 |
break; |
1686 |
} else |
1687 |
LockSupport.parkUntil(this, abstime); |
1688 |
} |
1689 |
node.clearStatus(); |
1690 |
acquire(node, savedState, false, false, false, 0L); |
1691 |
if (cancelled) { |
1692 |
unlinkCancelledWaiters(node); |
1693 |
if (interrupted) |
1694 |
throw new InterruptedException(); |
1695 |
} else if (interrupted) |
1696 |
Thread.currentThread().interrupt(); |
1697 |
return !cancelled; |
1698 |
} |
1699 |
|
1700 |
/** |
1701 |
* Implements timed condition wait. |
1702 |
* <ol> |
1703 |
* <li>If current thread is interrupted, throw InterruptedException. |
1704 |
* <li>Save lock state returned by {@link #getState}. |
1705 |
* <li>Invoke {@link #release} with saved state as argument, |
1706 |
* throwing IllegalMonitorStateException if it fails. |
1707 |
* <li>Block until signalled, interrupted, or timed out. |
1708 |
* <li>Reacquire by invoking specialized version of |
1709 |
* {@link #acquire} with saved state as argument. |
1710 |
* <li>If interrupted while blocked in step 4, throw InterruptedException. |
1711 |
* <li>If timed out while blocked in step 4, return false, else true. |
1712 |
* </ol> |
1713 |
*/ |
1714 |
public final boolean await(long time, TimeUnit unit) |
1715 |
throws InterruptedException { |
1716 |
long nanosTimeout = unit.toNanos(time); |
1717 |
if (Thread.interrupted()) |
1718 |
throw new InterruptedException(); |
1719 |
ConditionNode node = new ConditionNode(); |
1720 |
int savedState = enableWait(node); |
1721 |
long nanos = (nanosTimeout < 0L) ? 0L : nanosTimeout; |
1722 |
long deadline = System.nanoTime() + nanos; |
1723 |
boolean cancelled = false, interrupted = false; |
1724 |
while (!canReacquire(node)) { |
1725 |
if ((interrupted |= Thread.interrupted()) || |
1726 |
(nanos = deadline - System.nanoTime()) <= 0L) { |
1727 |
if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0) |
1728 |
break; |
1729 |
} else |
1730 |
LockSupport.parkNanos(this, nanos); |
1731 |
} |
1732 |
node.clearStatus(); |
1733 |
acquire(node, savedState, false, false, false, 0L); |
1734 |
if (cancelled) { |
1735 |
unlinkCancelledWaiters(node); |
1736 |
if (interrupted) |
1737 |
throw new InterruptedException(); |
1738 |
} else if (interrupted) |
1739 |
Thread.currentThread().interrupt(); |
1740 |
return !cancelled; |
1741 |
} |
1742 |
|
1743 |
// support for instrumentation |
1744 |
|
1745 |
/** |
1746 |
* Returns true if this condition was created by the given |
1747 |
* synchronization object. |
1748 |
* |
1749 |
* @return {@code true} if owned |
1750 |
*/ |
1751 |
final boolean isOwnedBy(AbstractQueuedSynchronizer sync) { |
1752 |
return sync == AbstractQueuedSynchronizer.this; |
1753 |
} |
1754 |
|
1755 |
/** |
1756 |
* Queries whether any threads are waiting on this condition. |
1757 |
* Implements {@link AbstractQueuedSynchronizer#hasWaiters(ConditionObject)}. |
1758 |
* |
1759 |
* @return {@code true} if there are any waiting threads |
1760 |
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} |
1761 |
* returns {@code false} |
1762 |
*/ |
1763 |
protected final boolean hasWaiters() { |
1764 |
if (!isHeldExclusively()) |
1765 |
throw new IllegalMonitorStateException(); |
1766 |
for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) { |
1767 |
if ((w.status & COND) != 0) |
1768 |
return true; |
1769 |
} |
1770 |
return false; |
1771 |
} |
1772 |
|
1773 |
/** |
1774 |
* Returns an estimate of the number of threads waiting on |
1775 |
* this condition. |
1776 |
* Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength(ConditionObject)}. |
1777 |
* |
1778 |
* @return the estimated number of waiting threads |
1779 |
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} |
1780 |
* returns {@code false} |
1781 |
*/ |
1782 |
protected final int getWaitQueueLength() { |
1783 |
if (!isHeldExclusively()) |
1784 |
throw new IllegalMonitorStateException(); |
1785 |
int n = 0; |
1786 |
for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) { |
1787 |
if ((w.status & COND) != 0) |
1788 |
++n; |
1789 |
} |
1790 |
return n; |
1791 |
} |
1792 |
|
1793 |
/** |
1794 |
* Returns a collection containing those threads that may be |
1795 |
* waiting on this Condition. |
1796 |
* Implements {@link AbstractQueuedSynchronizer#getWaitingThreads(ConditionObject)}. |
1797 |
* |
1798 |
* @return the collection of threads |
1799 |
* @throws IllegalMonitorStateException if {@link #isHeldExclusively} |
1800 |
* returns {@code false} |
1801 |
*/ |
1802 |
protected final Collection<Thread> getWaitingThreads() { |
1803 |
if (!isHeldExclusively()) |
1804 |
throw new IllegalMonitorStateException(); |
1805 |
ArrayList<Thread> list = new ArrayList<>(); |
1806 |
for (ConditionNode w = firstWaiter; w != null; w = w.nextWaiter) { |
1807 |
if ((w.status & COND) != 0) { |
1808 |
Thread t = w.waiter; |
1809 |
if (t != null) |
1810 |
list.add(t); |
1811 |
} |
1812 |
} |
1813 |
return list; |
1814 |
} |
1815 |
} |
1816 |
|
1817 |
// Unsafe |
1818 |
private static final Unsafe U = Unsafe.getUnsafe(); |
1819 |
private static final long STATE |
1820 |
= U.objectFieldOffset(AbstractQueuedSynchronizer.class, "state"); |
1821 |
private static final long HEAD |
1822 |
= U.objectFieldOffset(AbstractQueuedSynchronizer.class, "head"); |
1823 |
private static final long TAIL |
1824 |
= U.objectFieldOffset(AbstractQueuedSynchronizer.class, "tail"); |
1825 |
|
1826 |
static { |
1827 |
Class<?> ensureLoaded = LockSupport.class; |
1828 |
} |
1829 |
} |