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 jsr166e; |
8 |
import java.util.concurrent.TimeUnit; |
9 |
import java.util.concurrent.locks.Lock; |
10 |
import java.util.concurrent.locks.Condition; |
11 |
import java.util.concurrent.locks.ReadWriteLock; |
12 |
import java.util.concurrent.locks.LockSupport; |
13 |
|
14 |
/** |
15 |
* A capability-based lock with three modes for controlling read/write |
16 |
* access. The state of a StampedLock consists of a version and mode. |
17 |
* Lock acquisition methods return a stamp that represents and |
18 |
* controls access with respect to a lock state; "try" versions of |
19 |
* these methods may instead return the special value zero to |
20 |
* represent failure to acquire access. Lock release and conversion |
21 |
* methods require stamps as arguments, and fail if they do not match |
22 |
* the state of the lock. The three modes are: |
23 |
* |
24 |
* <ul> |
25 |
* |
26 |
* <li><b>Writing.</b> Method {@link #writeLock} possibly blocks |
27 |
* waiting for exclusive access, returning a stamp that can be used |
28 |
* in method {@link #unlockWrite} to release the lock. Untimed and |
29 |
* timed versions of {@code tryWriteLock} are also provided. When |
30 |
* the lock is held in write mode, no read locks may be obtained, |
31 |
* and all optimistic read validations will fail. </li> |
32 |
* |
33 |
* <li><b>Reading.</b> Method {@link #readLock} possibly blocks |
34 |
* waiting for non-exclusive access, returning a stamp that can be |
35 |
* used in method {@link #unlockRead} to release the lock. Untimed |
36 |
* and timed versions of {@code tryReadLock} are also provided. </li> |
37 |
* |
38 |
* <li><b>Optimistic Reading.</b> Method {@link #tryOptimisticRead} |
39 |
* returns a non-zero stamp only if the lock is not currently held |
40 |
* in write mode. Method {@link #validate} returns true if the lock |
41 |
* has not been acquired in write mode since obtaining a given |
42 |
* stamp. This mode can be thought of as an extremely weak version |
43 |
* of a read-lock, that can be broken by a writer at any time. The |
44 |
* use of optimistic mode for short read-only code segments often |
45 |
* reduces contention and improves throughput. However, its use is |
46 |
* inherently fragile. Optimistic read sections should only read |
47 |
* fields and hold them in local variables for later use after |
48 |
* validation. Fields read while in optimistic mode may be wildly |
49 |
* inconsistent, so usage applies only when you are familiar enough |
50 |
* with data representations to check consistency and/or repeatedly |
51 |
* invoke method {@code validate()}. For example, such steps are |
52 |
* typically required when first reading an object or array |
53 |
* reference, and then accessing one of its fields, elements or |
54 |
* methods. </li> |
55 |
* |
56 |
* </ul> |
57 |
* |
58 |
* <p>This class also supports methods that conditionally provide |
59 |
* conversions across the three modes. For example, method {@link |
60 |
* #tryConvertToWriteLock} attempts to "upgrade" a mode, returning |
61 |
* a valid write stamp if (1) already in writing mode (2) in reading |
62 |
* mode and there are no other readers or (3) in optimistic mode and |
63 |
* the lock is available. The forms of these methods are designed to |
64 |
* help reduce some of the code bloat that otherwise occurs in |
65 |
* retry-based designs. |
66 |
* |
67 |
* <p>StampedLocks are designed for use as internal utilities in the |
68 |
* development of thread-safe components. Their use relies on |
69 |
* knowledge of the internal properties of the data, objects, and |
70 |
* methods they are protecting. They are not reentrant, so locked |
71 |
* bodies should not call other unknown methods that may try to |
72 |
* re-acquire locks (although you may pass a stamp to other methods |
73 |
* that can use or convert it). The use of read lock modes relies on |
74 |
* the associated code sections being side-effect-free. Unvalidated |
75 |
* optimistic read sections cannot call methods that are not known to |
76 |
* tolerate potential inconsistencies. Stamps use finite |
77 |
* representations, and are not cryptographically secure (i.e., a |
78 |
* valid stamp may be guessable). Stamp values may recycle after (no |
79 |
* sooner than) one year of continuous operation. A stamp held without |
80 |
* use or validation for longer than this period may fail to validate |
81 |
* correctly. StampedLocks are serializable, but always deserialize |
82 |
* into initial unlocked state, so they are not useful for remote |
83 |
* locking. |
84 |
* |
85 |
* <p>The scheduling policy of StampedLock does not consistently |
86 |
* prefer readers over writers or vice versa. All "try" methods are |
87 |
* best-effort and do not necessarily conform to any scheduling or |
88 |
* fairness policy. A zero return from any "try" method for acquiring |
89 |
* or converting locks does not carry any information about the state |
90 |
* of the lock; a subsequent invocation may succeed. |
91 |
* |
92 |
* <p>Because it supports coordinated usage across multiple lock |
93 |
* modes, this class does not directly implement the {@link Lock} or |
94 |
* {@link ReadWriteLock} interfaces. However, a StampedLock may be |
95 |
* viewed {@link #asReadLock()}, {@link #asWriteLock()}, or {@link |
96 |
* #asReadWriteLock()} in applications requiring only the associated |
97 |
* set of functionality. |
98 |
* |
99 |
* <p><b>Sample Usage.</b> The following illustrates some usage idioms |
100 |
* in a class that maintains simple two-dimensional points. The sample |
101 |
* code illustrates some try/catch conventions even though they are |
102 |
* not strictly needed here because no exceptions can occur in their |
103 |
* bodies.<br> |
104 |
* |
105 |
* <pre>{@code |
106 |
* class Point { |
107 |
* private double x, y; |
108 |
* private final StampedLock sl = new StampedLock(); |
109 |
* |
110 |
* void move(double deltaX, double deltaY) { // an exclusively locked method |
111 |
* long stamp = sl.writeLock(); |
112 |
* try { |
113 |
* x += deltaX; |
114 |
* y += deltaY; |
115 |
* } finally { |
116 |
* sl.unlockWrite(stamp); |
117 |
* } |
118 |
* } |
119 |
* |
120 |
* double distanceFromOrigin() { // A read-only method |
121 |
* long stamp = sl.tryOptimisticRead(); |
122 |
* double currentX = x, currentY = y; |
123 |
* if (!sl.validate(stamp)) { |
124 |
* stamp = sl.readLock(); |
125 |
* try { |
126 |
* currentX = x; |
127 |
* currentY = y; |
128 |
* } finally { |
129 |
* sl.unlockRead(stamp); |
130 |
* } |
131 |
* } |
132 |
* return Math.sqrt(currentX * currentX + currentY * currentY); |
133 |
* } |
134 |
* |
135 |
* void moveIfAtOrigin(double newX, double newY) { // upgrade |
136 |
* // Could instead start with optimistic, not read mode |
137 |
* long stamp = sl.readLock(); |
138 |
* try { |
139 |
* while (x == 0.0 && y == 0.0) { |
140 |
* long ws = sl.tryConvertToWriteLock(stamp); |
141 |
* if (ws != 0L) { |
142 |
* stamp = ws; |
143 |
* x = newX; |
144 |
* y = newY; |
145 |
* break; |
146 |
* } |
147 |
* else { |
148 |
* sl.unlockRead(stamp); |
149 |
* stamp = sl.writeLock(); |
150 |
* } |
151 |
* } |
152 |
* } finally { |
153 |
* sl.unlock(stamp); |
154 |
* } |
155 |
* } |
156 |
* }}</pre> |
157 |
* |
158 |
* @since 1.8 |
159 |
* @author Doug Lea |
160 |
*/ |
161 |
public class StampedLock implements java.io.Serializable { |
162 |
/* |
163 |
* Algorithmic notes: |
164 |
* |
165 |
* The design employs elements of Sequence locks |
166 |
* (as used in linux kernels; see Lameter's |
167 |
* http://www.lameter.com/gelato2005.pdf |
168 |
* and elsewhere; see |
169 |
* Boehm's http://www.hpl.hp.com/techreports/2012/HPL-2012-68.html) |
170 |
* and Ordered RW locks (see Shirako et al |
171 |
* http://dl.acm.org/citation.cfm?id=2312015) |
172 |
* |
173 |
* Conceptually, the primary state of the lock includes a sequence |
174 |
* number that is odd when write-locked and even otherwise. |
175 |
* However, this is offset by a reader count that is non-zero when |
176 |
* read-locked. The read count is ignored when validating |
177 |
* "optimistic" seqlock-reader-style stamps. Because we must use |
178 |
* a small finite number of bits (currently 7) for readers, a |
179 |
* supplementary reader overflow word is used when the number of |
180 |
* readers exceeds the count field. We do this by treating the max |
181 |
* reader count value (RBITS) as a spinlock protecting overflow |
182 |
* updates. |
183 |
* |
184 |
* Waiters use a modified form of CLH lock used in |
185 |
* AbstractQueuedSynchronizer (see its internal documentation for |
186 |
* a fuller account), where each node is tagged (field mode) as |
187 |
* either a reader or writer. Sets of waiting readers are grouped |
188 |
* (linked) under a common node (field cowait) so act as a single |
189 |
* node with respect to most CLH mechanics. By virtue of the |
190 |
* queue structure, wait nodes need not actually carry sequence |
191 |
* numbers; we know each is greater than its predecessor. This |
192 |
* simplifies the scheduling policy to a mainly-FIFO scheme that |
193 |
* incorporates elements of Phase-Fair locks (see Brandenburg & |
194 |
* Anderson, especially http://www.cs.unc.edu/~bbb/diss/). In |
195 |
* particular, we use the phase-fair anti-barging rule: If an |
196 |
* incoming reader arrives while read lock is held but there is a |
197 |
* queued writer, this incoming reader is queued. (This rule is |
198 |
* responsible for some of the complexity of method acquireRead, |
199 |
* but without it, the lock becomes highly unfair.) |
200 |
* |
201 |
* These rules apply to threads actually queued. All tryLock forms |
202 |
* opportunistically try to acquire locks regardless of preference |
203 |
* rules, and so may "barge" their way in. Randomized spinning is |
204 |
* used in the acquire methods to reduce (increasingly expensive) |
205 |
* context switching while also avoiding sustained memory |
206 |
* thrashing among many threads. We limit spins to the head of |
207 |
* queue. A thread spin-waits up to SPINS times (where each |
208 |
* iteration decreases spin count with 50% probability) before |
209 |
* blocking. If, upon wakening it fails to obtain lock, and is |
210 |
* still (or becomes) the first waiting thread (which indicates |
211 |
* that some other thread barged and obtained lock), it escalates |
212 |
* spins (up to MAX_HEAD_SPINS) to reduce the likelihood of |
213 |
* continually losing to barging threads. |
214 |
* |
215 |
* Nearly all of these mechanics are carried out in methods |
216 |
* acquireWrite and acquireRead, that, as typical of such code, |
217 |
* sprawl out because actions and retries rely on consistent sets |
218 |
* of locally cached reads. |
219 |
* |
220 |
* As noted in Boehm's paper (above), sequence validation (mainly |
221 |
* method validate()) requires stricter ordering rules than apply |
222 |
* to normal volatile reads (of "state"). In the absence of (but |
223 |
* continual hope for) explicit JVM support of intrinsics with |
224 |
* double-sided reordering prohibition, or corresponding fence |
225 |
* intrinsics, we for now uncomfortably rely on the fact that the |
226 |
* Unsafe.getXVolatile intrinsic must have this property |
227 |
* (syntactic volatile reads do not) for internal purposes anyway, |
228 |
* even though it is not documented. |
229 |
* |
230 |
* The memory layout keeps lock state and queue pointers together |
231 |
* (normally on the same cache line). This usually works well for |
232 |
* read-mostly loads. In most other cases, the natural tendency of |
233 |
* adaptive-spin CLH locks to reduce memory contention lessens |
234 |
* motivation to further spread out contended locations, but might |
235 |
* be subject to future improvements. |
236 |
*/ |
237 |
|
238 |
private static final long serialVersionUID = -6001602636862214147L; |
239 |
|
240 |
/** Number of processors, for spin control */ |
241 |
private static final int NCPU = Runtime.getRuntime().availableProcessors(); |
242 |
|
243 |
/** Maximum number of retries before blocking on acquisition */ |
244 |
private static final int SPINS = (NCPU > 1) ? 1 << 6 : 0; |
245 |
|
246 |
/** Maximum number of retries before re-blocking */ |
247 |
private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 12 : 0; |
248 |
|
249 |
/** The period for yielding when waiting for overflow spinlock */ |
250 |
private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1 |
251 |
|
252 |
/** The number of bits to use for reader count before overflowing */ |
253 |
private static final int LG_READERS = 7; |
254 |
|
255 |
// Values for lock state and stamp operations |
256 |
private static final long RUNIT = 1L; |
257 |
private static final long WBIT = 1L << LG_READERS; |
258 |
private static final long RBITS = WBIT - 1L; |
259 |
private static final long RFULL = RBITS - 1L; |
260 |
private static final long ABITS = RBITS | WBIT; |
261 |
private static final long SBITS = ~RBITS; // note overlap with ABITS |
262 |
|
263 |
// Initial value for lock state; avoid failure value zero |
264 |
private static final long ORIGIN = WBIT << 1; |
265 |
|
266 |
// Special value from cancelled acquire methods so caller can throw IE |
267 |
private static final long INTERRUPTED = 1L; |
268 |
|
269 |
// Values for node status; order matters |
270 |
private static final int WAITING = -1; |
271 |
private static final int CANCELLED = 1; |
272 |
|
273 |
// Modes for nodes (int not boolean to allow arithmetic) |
274 |
private static final int RMODE = 0; |
275 |
private static final int WMODE = 1; |
276 |
|
277 |
/** Wait nodes */ |
278 |
static final class WNode { |
279 |
volatile WNode prev; |
280 |
volatile WNode next; |
281 |
volatile WNode cowait; // list of linked readers |
282 |
volatile Thread thread; // non-null while possibly parked |
283 |
volatile int status; // 0, WAITING, or CANCELLED |
284 |
final int mode; // RMODE or WMODE |
285 |
WNode(int m, WNode p) { mode = m; prev = p; } |
286 |
} |
287 |
|
288 |
/** Head of CLH queue */ |
289 |
private transient volatile WNode whead; |
290 |
/** Tail (last) of CLH queue */ |
291 |
private transient volatile WNode wtail; |
292 |
|
293 |
// views |
294 |
transient ReadLockView readLockView; |
295 |
transient WriteLockView writeLockView; |
296 |
transient ReadWriteLockView readWriteLockView; |
297 |
|
298 |
/** Lock sequence/state */ |
299 |
private transient volatile long state; |
300 |
/** extra reader count when state read count saturated */ |
301 |
private transient int readerOverflow; |
302 |
|
303 |
/** |
304 |
* Creates a new lock, initially in unlocked state. |
305 |
*/ |
306 |
public StampedLock() { |
307 |
state = ORIGIN; |
308 |
} |
309 |
|
310 |
/** |
311 |
* Exclusively acquires the lock, blocking if necessary |
312 |
* until available. |
313 |
* |
314 |
* @return a stamp that can be used to unlock or convert mode |
315 |
*/ |
316 |
public long writeLock() { |
317 |
long s, next; // bypass acquireWrite in fully unlocked case only |
318 |
return ((((s = state) & ABITS) == 0L && |
319 |
U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ? |
320 |
next : acquireWrite(false, 0L)); |
321 |
} |
322 |
|
323 |
/** |
324 |
* Exclusively acquires the lock if it is immediately available. |
325 |
* |
326 |
* @return a stamp that can be used to unlock or convert mode, |
327 |
* or zero if the lock is not available |
328 |
*/ |
329 |
public long tryWriteLock() { |
330 |
long s, next; |
331 |
return ((((s = state) & ABITS) == 0L && |
332 |
U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ? |
333 |
next : 0L); |
334 |
} |
335 |
|
336 |
/** |
337 |
* Exclusively acquires the lock if it is available within the |
338 |
* given time and the current thread has not been interrupted. |
339 |
* Behavior under timeout and interruption matches that specified |
340 |
* for method {@link Lock#tryLock(long,TimeUnit)}. |
341 |
* |
342 |
* @param time the maximum time to wait for the lock |
343 |
* @param unit the time unit of the {@code time} argument |
344 |
* @return a stamp that can be used to unlock or convert mode, |
345 |
* or zero if the lock is not available |
346 |
* @throws InterruptedException if the current thread is interrupted |
347 |
* before acquiring the lock |
348 |
*/ |
349 |
public long tryWriteLock(long time, TimeUnit unit) |
350 |
throws InterruptedException { |
351 |
long nanos = unit.toNanos(time); |
352 |
if (!Thread.interrupted()) { |
353 |
long next, deadline; |
354 |
if ((next = tryWriteLock()) != 0L) |
355 |
return next; |
356 |
if (nanos <= 0L) |
357 |
return 0L; |
358 |
if ((deadline = System.nanoTime() + nanos) == 0L) |
359 |
deadline = 1L; |
360 |
if ((next = acquireWrite(true, deadline)) != INTERRUPTED) |
361 |
return next; |
362 |
} |
363 |
throw new InterruptedException(); |
364 |
} |
365 |
|
366 |
/** |
367 |
* Exclusively acquires the lock, blocking if necessary |
368 |
* until available or the current thread is interrupted. |
369 |
* Behavior under interruption matches that specified |
370 |
* for method {@link Lock#lockInterruptibly()}. |
371 |
* |
372 |
* @return a stamp that can be used to unlock or convert mode |
373 |
* @throws InterruptedException if the current thread is interrupted |
374 |
* before acquiring the lock |
375 |
*/ |
376 |
public long writeLockInterruptibly() throws InterruptedException { |
377 |
long next; |
378 |
if (!Thread.interrupted() && |
379 |
(next = acquireWrite(true, 0L)) != INTERRUPTED) |
380 |
return next; |
381 |
throw new InterruptedException(); |
382 |
} |
383 |
|
384 |
/** |
385 |
* Non-exclusively acquires the lock, blocking if necessary |
386 |
* until available. |
387 |
* |
388 |
* @return a stamp that can be used to unlock or convert mode |
389 |
*/ |
390 |
public long readLock() { |
391 |
long s, next; // bypass acquireRead on fully unlocked case only |
392 |
return ((((s = state) & ABITS) == 0L && |
393 |
U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) ? |
394 |
next : acquireRead(false, 0L)); |
395 |
} |
396 |
|
397 |
/** |
398 |
* Non-exclusively acquires the lock if it is immediately available. |
399 |
* |
400 |
* @return a stamp that can be used to unlock or convert mode, |
401 |
* or zero if the lock is not available |
402 |
*/ |
403 |
public long tryReadLock() { |
404 |
for (;;) { |
405 |
long s, m, next; |
406 |
if ((m = (s = state) & ABITS) == WBIT) |
407 |
return 0L; |
408 |
else if (m < RFULL) { |
409 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
410 |
return next; |
411 |
} |
412 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
413 |
return next; |
414 |
} |
415 |
} |
416 |
|
417 |
/** |
418 |
* Non-exclusively acquires the lock if it is available within the |
419 |
* given time and the current thread has not been interrupted. |
420 |
* Behavior under timeout and interruption matches that specified |
421 |
* for method {@link Lock#tryLock(long,TimeUnit)}. |
422 |
* |
423 |
* @param time the maximum time to wait for the lock |
424 |
* @param unit the time unit of the {@code time} argument |
425 |
* @return a stamp that can be used to unlock or convert mode, |
426 |
* or zero if the lock is not available |
427 |
* @throws InterruptedException if the current thread is interrupted |
428 |
* before acquiring the lock |
429 |
*/ |
430 |
public long tryReadLock(long time, TimeUnit unit) |
431 |
throws InterruptedException { |
432 |
long s, m, next, deadline; |
433 |
long nanos = unit.toNanos(time); |
434 |
if (!Thread.interrupted()) { |
435 |
if ((m = (s = state) & ABITS) != WBIT) { |
436 |
if (m < RFULL) { |
437 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
438 |
return next; |
439 |
} |
440 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
441 |
return next; |
442 |
} |
443 |
if (nanos <= 0L) |
444 |
return 0L; |
445 |
if ((deadline = System.nanoTime() + nanos) == 0L) |
446 |
deadline = 1L; |
447 |
if ((next = acquireRead(true, deadline)) != INTERRUPTED) |
448 |
return next; |
449 |
} |
450 |
throw new InterruptedException(); |
451 |
} |
452 |
|
453 |
/** |
454 |
* Non-exclusively acquires the lock, blocking if necessary |
455 |
* until available or the current thread is interrupted. |
456 |
* Behavior under interruption matches that specified |
457 |
* for method {@link Lock#lockInterruptibly()}. |
458 |
* |
459 |
* @return a stamp that can be used to unlock or convert mode |
460 |
* @throws InterruptedException if the current thread is interrupted |
461 |
* before acquiring the lock |
462 |
*/ |
463 |
public long readLockInterruptibly() throws InterruptedException { |
464 |
long next; |
465 |
if (!Thread.interrupted() && |
466 |
(next = acquireRead(true, 0L)) != INTERRUPTED) |
467 |
return next; |
468 |
throw new InterruptedException(); |
469 |
} |
470 |
|
471 |
/** |
472 |
* Returns a stamp that can later be validated, or zero |
473 |
* if exclusively locked. |
474 |
* |
475 |
* @return a stamp, or zero if exclusively locked |
476 |
*/ |
477 |
public long tryOptimisticRead() { |
478 |
long s; |
479 |
return (((s = state) & WBIT) == 0L) ? (s & SBITS) : 0L; |
480 |
} |
481 |
|
482 |
/** |
483 |
* Returns true if the lock has not been exclusively acquired |
484 |
* since issuance of the given stamp. Always returns false if the |
485 |
* stamp is zero. Always returns true if the stamp represents a |
486 |
* currently held lock. Invoking this method with a value not |
487 |
* obtained from {@link #tryOptimisticRead} or a locking method |
488 |
* for this lock has no defined effect or result. |
489 |
* |
490 |
* @param stamp a stamp |
491 |
* @return {@code true} if the lock has not been exclusively acquired |
492 |
* since issuance of the given stamp; else false |
493 |
*/ |
494 |
public boolean validate(long stamp) { |
495 |
// See above about current use of getLongVolatile here |
496 |
return (stamp & SBITS) == (U.getLongVolatile(this, STATE) & SBITS); |
497 |
} |
498 |
|
499 |
/** |
500 |
* If the lock state matches the given stamp, releases the |
501 |
* exclusive lock. |
502 |
* |
503 |
* @param stamp a stamp returned by a write-lock operation |
504 |
* @throws IllegalMonitorStateException if the stamp does |
505 |
* not match the current state of this lock |
506 |
*/ |
507 |
public void unlockWrite(long stamp) { |
508 |
WNode h; |
509 |
if (state != stamp || (stamp & WBIT) == 0L) |
510 |
throw new IllegalMonitorStateException(); |
511 |
state = (stamp += WBIT) == 0L ? ORIGIN : stamp; |
512 |
if ((h = whead) != null && h.status != 0) |
513 |
release(h); |
514 |
} |
515 |
|
516 |
/** |
517 |
* If the lock state matches the given stamp, releases the |
518 |
* non-exclusive lock. |
519 |
* |
520 |
* @param stamp a stamp returned by a read-lock operation |
521 |
* @throws IllegalMonitorStateException if the stamp does |
522 |
* not match the current state of this lock |
523 |
*/ |
524 |
public void unlockRead(long stamp) { |
525 |
long s, m; WNode h; |
526 |
for (;;) { |
527 |
if (((s = state) & SBITS) != (stamp & SBITS) || |
528 |
(stamp & ABITS) == 0L || (m = s & ABITS) == 0L || m == WBIT) |
529 |
throw new IllegalMonitorStateException(); |
530 |
if (m < RFULL) { |
531 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
532 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
533 |
release(h); |
534 |
break; |
535 |
} |
536 |
} |
537 |
else if (tryDecReaderOverflow(s) != 0L) |
538 |
break; |
539 |
} |
540 |
} |
541 |
|
542 |
/** |
543 |
* If the lock state matches the given stamp, releases the |
544 |
* corresponding mode of the lock. |
545 |
* |
546 |
* @param stamp a stamp returned by a lock operation |
547 |
* @throws IllegalMonitorStateException if the stamp does |
548 |
* not match the current state of this lock |
549 |
*/ |
550 |
public void unlock(long stamp) { |
551 |
long a = stamp & ABITS, m, s; WNode h; |
552 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
553 |
if ((m = s & ABITS) == 0L) |
554 |
break; |
555 |
else if (m == WBIT) { |
556 |
if (a != m) |
557 |
break; |
558 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
559 |
if ((h = whead) != null && h.status != 0) |
560 |
release(h); |
561 |
return; |
562 |
} |
563 |
else if (a == 0L || a >= WBIT) |
564 |
break; |
565 |
else if (m < RFULL) { |
566 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
567 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
568 |
release(h); |
569 |
return; |
570 |
} |
571 |
} |
572 |
else if (tryDecReaderOverflow(s) != 0L) |
573 |
return; |
574 |
} |
575 |
throw new IllegalMonitorStateException(); |
576 |
} |
577 |
|
578 |
/** |
579 |
* If the lock state matches the given stamp, performs one of |
580 |
* the following actions. If the stamp represents holding a write |
581 |
* lock, returns it. Or, if a read lock, if the write lock is |
582 |
* available, releases the read lock and returns a write stamp. |
583 |
* Or, if an optimistic read, returns a write stamp only if |
584 |
* immediately available. This method returns zero in all other |
585 |
* cases. |
586 |
* |
587 |
* @param stamp a stamp |
588 |
* @return a valid write stamp, or zero on failure |
589 |
*/ |
590 |
public long tryConvertToWriteLock(long stamp) { |
591 |
long a = stamp & ABITS, m, s, next; |
592 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
593 |
if ((m = s & ABITS) == 0L) { |
594 |
if (a != 0L) |
595 |
break; |
596 |
if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) |
597 |
return next; |
598 |
} |
599 |
else if (m == WBIT) { |
600 |
if (a != m) |
601 |
break; |
602 |
return stamp; |
603 |
} |
604 |
else if (m == RUNIT && a != 0L) { |
605 |
if (U.compareAndSwapLong(this, STATE, s, |
606 |
next = s - RUNIT + WBIT)) |
607 |
return next; |
608 |
} |
609 |
else |
610 |
break; |
611 |
} |
612 |
return 0L; |
613 |
} |
614 |
|
615 |
/** |
616 |
* If the lock state matches the given stamp, performs one of |
617 |
* the following actions. If the stamp represents holding a write |
618 |
* lock, releases it and obtains a read lock. Or, if a read lock, |
619 |
* returns it. Or, if an optimistic read, acquires a read lock and |
620 |
* returns a read stamp only if immediately available. This method |
621 |
* returns zero in all other cases. |
622 |
* |
623 |
* @param stamp a stamp |
624 |
* @return a valid read stamp, or zero on failure |
625 |
*/ |
626 |
public long tryConvertToReadLock(long stamp) { |
627 |
long a = stamp & ABITS, m, s, next; WNode h; |
628 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
629 |
if ((m = s & ABITS) == 0L) { |
630 |
if (a != 0L) |
631 |
break; |
632 |
else if (m < RFULL) { |
633 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
634 |
return next; |
635 |
} |
636 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
637 |
return next; |
638 |
} |
639 |
else if (m == WBIT) { |
640 |
if (a != m) |
641 |
break; |
642 |
state = next = s + (WBIT + RUNIT); |
643 |
if ((h = whead) != null && h.status != 0) |
644 |
release(h); |
645 |
return next; |
646 |
} |
647 |
else if (a != 0L && a < WBIT) |
648 |
return stamp; |
649 |
else |
650 |
break; |
651 |
} |
652 |
return 0L; |
653 |
} |
654 |
|
655 |
/** |
656 |
* If the lock state matches the given stamp then, if the stamp |
657 |
* represents holding a lock, releases it and returns an |
658 |
* observation stamp. Or, if an optimistic read, returns it if |
659 |
* validated. This method returns zero in all other cases, and so |
660 |
* may be useful as a form of "tryUnlock". |
661 |
* |
662 |
* @param stamp a stamp |
663 |
* @return a valid optimistic read stamp, or zero on failure |
664 |
*/ |
665 |
public long tryConvertToOptimisticRead(long stamp) { |
666 |
long a = stamp & ABITS, m, s, next; WNode h; |
667 |
for (;;) { |
668 |
s = U.getLongVolatile(this, STATE); // see above |
669 |
if ((s & SBITS) != (stamp & SBITS)) |
670 |
break; |
671 |
if ((m = s & ABITS) == 0L) { |
672 |
if (a != 0L) |
673 |
break; |
674 |
return s; |
675 |
} |
676 |
else if (m == WBIT) { |
677 |
if (a != m) |
678 |
break; |
679 |
state = next = (s += WBIT) == 0L ? ORIGIN : s; |
680 |
if ((h = whead) != null && h.status != 0) |
681 |
release(h); |
682 |
return next; |
683 |
} |
684 |
else if (a == 0L || a >= WBIT) |
685 |
break; |
686 |
else if (m < RFULL) { |
687 |
if (U.compareAndSwapLong(this, STATE, s, next = s - RUNIT)) { |
688 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
689 |
release(h); |
690 |
return next & SBITS; |
691 |
} |
692 |
} |
693 |
else if ((next = tryDecReaderOverflow(s)) != 0L) |
694 |
return next & SBITS; |
695 |
} |
696 |
return 0L; |
697 |
} |
698 |
|
699 |
/** |
700 |
* Releases the write lock if it is held, without requiring a |
701 |
* stamp value. This method may be useful for recovery after |
702 |
* errors. |
703 |
* |
704 |
* @return {@code true} if the lock was held, else false |
705 |
*/ |
706 |
public boolean tryUnlockWrite() { |
707 |
long s; WNode h; |
708 |
if (((s = state) & WBIT) != 0L) { |
709 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
710 |
if ((h = whead) != null && h.status != 0) |
711 |
release(h); |
712 |
return true; |
713 |
} |
714 |
return false; |
715 |
} |
716 |
|
717 |
/** |
718 |
* Releases one hold of the read lock if it is held, without |
719 |
* requiring a stamp value. This method may be useful for recovery |
720 |
* after errors. |
721 |
* |
722 |
* @return {@code true} if the read lock was held, else false |
723 |
*/ |
724 |
public boolean tryUnlockRead() { |
725 |
long s, m; WNode h; |
726 |
while ((m = (s = state) & ABITS) != 0L && m < WBIT) { |
727 |
if (m < RFULL) { |
728 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
729 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
730 |
release(h); |
731 |
return true; |
732 |
} |
733 |
} |
734 |
else if (tryDecReaderOverflow(s) != 0L) |
735 |
return true; |
736 |
} |
737 |
return false; |
738 |
} |
739 |
|
740 |
// status monitoring methods |
741 |
|
742 |
/** |
743 |
* Returns combined state-held and overflow read count for given |
744 |
* state s. |
745 |
*/ |
746 |
private int getReadLockCount(long s) { |
747 |
long readers; |
748 |
if ((readers = s & RBITS) >= RFULL) |
749 |
readers = RFULL + readerOverflow; |
750 |
return (int) readers; |
751 |
} |
752 |
|
753 |
/** |
754 |
* Returns {@code true} if the lock is currently held exclusively. |
755 |
* |
756 |
* @return {@code true} if the lock is currently held exclusively |
757 |
*/ |
758 |
public boolean isWriteLocked() { |
759 |
return (state & WBIT) != 0L; |
760 |
} |
761 |
|
762 |
/** |
763 |
* Returns {@code true} if the lock is currently held non-exclusively. |
764 |
* |
765 |
* @return {@code true} if the lock is currently held non-exclusively |
766 |
*/ |
767 |
public boolean isReadLocked() { |
768 |
return (state & RBITS) != 0L; |
769 |
} |
770 |
|
771 |
/** |
772 |
* Queries the number of read locks held for this lock. This |
773 |
* method is designed for use in monitoring system state, not for |
774 |
* synchronization control. |
775 |
* @return the number of read locks held |
776 |
*/ |
777 |
public int getReadLockCount() { |
778 |
return getReadLockCount(state); |
779 |
} |
780 |
|
781 |
/** |
782 |
* Returns a string identifying this lock, as well as its lock |
783 |
* state. The state, in brackets, includes the String {@code |
784 |
* "Unlocked"} or the String {@code "Write-locked"} or the String |
785 |
* {@code "Read-locks:"} followed by the current number of |
786 |
* read-locks held. |
787 |
* |
788 |
* @return a string identifying this lock, as well as its lock state |
789 |
*/ |
790 |
public String toString() { |
791 |
long s = state; |
792 |
return super.toString() + |
793 |
((s & ABITS) == 0L ? "[Unlocked]" : |
794 |
(s & WBIT) != 0L ? "[Write-locked]" : |
795 |
"[Read-locks:" + getReadLockCount(s) + "]"); |
796 |
} |
797 |
|
798 |
// views |
799 |
|
800 |
/** |
801 |
* Returns a plain {@link Lock} view of this StampedLock in which |
802 |
* the {@link Lock#lock} method is mapped to {@link #readLock}, |
803 |
* and similarly for other methods. The returned Lock does not |
804 |
* support a {@link Condition}; method {@link |
805 |
* Lock#newCondition()} throws {@code |
806 |
* UnsupportedOperationException}. |
807 |
* |
808 |
* @return the lock |
809 |
*/ |
810 |
public Lock asReadLock() { |
811 |
ReadLockView v; |
812 |
return ((v = readLockView) != null ? v : |
813 |
(readLockView = new ReadLockView())); |
814 |
} |
815 |
|
816 |
/** |
817 |
* Returns a plain {@link Lock} view of this StampedLock in which |
818 |
* the {@link Lock#lock} method is mapped to {@link #writeLock}, |
819 |
* and similarly for other methods. The returned Lock does not |
820 |
* support a {@link Condition}; method {@link |
821 |
* Lock#newCondition()} throws {@code |
822 |
* UnsupportedOperationException}. |
823 |
* |
824 |
* @return the lock |
825 |
*/ |
826 |
public Lock asWriteLock() { |
827 |
WriteLockView v; |
828 |
return ((v = writeLockView) != null ? v : |
829 |
(writeLockView = new WriteLockView())); |
830 |
} |
831 |
|
832 |
/** |
833 |
* Returns a {@link ReadWriteLock} view of this StampedLock in |
834 |
* which the {@link ReadWriteLock#readLock()} method is mapped to |
835 |
* {@link #asReadLock()}, and {@link ReadWriteLock#writeLock()} to |
836 |
* {@link #asWriteLock()}. |
837 |
* |
838 |
* @return the lock |
839 |
*/ |
840 |
public ReadWriteLock asReadWriteLock() { |
841 |
ReadWriteLockView v; |
842 |
return ((v = readWriteLockView) != null ? v : |
843 |
(readWriteLockView = new ReadWriteLockView())); |
844 |
} |
845 |
|
846 |
// view classes |
847 |
|
848 |
final class ReadLockView implements Lock { |
849 |
public void lock() { readLock(); } |
850 |
public void lockInterruptibly() throws InterruptedException { |
851 |
readLockInterruptibly(); |
852 |
} |
853 |
public boolean tryLock() { return tryReadLock() != 0L; } |
854 |
public boolean tryLock(long time, TimeUnit unit) |
855 |
throws InterruptedException { |
856 |
return tryReadLock(time, unit) != 0L; |
857 |
} |
858 |
public void unlock() { unstampedUnlockRead(); } |
859 |
public Condition newCondition() { |
860 |
throw new UnsupportedOperationException(); |
861 |
} |
862 |
} |
863 |
|
864 |
final class WriteLockView implements Lock { |
865 |
public void lock() { writeLock(); } |
866 |
public void lockInterruptibly() throws InterruptedException { |
867 |
writeLockInterruptibly(); |
868 |
} |
869 |
public boolean tryLock() { return tryWriteLock() != 0L; } |
870 |
public boolean tryLock(long time, TimeUnit unit) |
871 |
throws InterruptedException { |
872 |
return tryWriteLock(time, unit) != 0L; |
873 |
} |
874 |
public void unlock() { unstampedUnlockWrite(); } |
875 |
public Condition newCondition() { |
876 |
throw new UnsupportedOperationException(); |
877 |
} |
878 |
} |
879 |
|
880 |
final class ReadWriteLockView implements ReadWriteLock { |
881 |
public Lock readLock() { return asReadLock(); } |
882 |
public Lock writeLock() { return asWriteLock(); } |
883 |
} |
884 |
|
885 |
// Unlock methods without stamp argument checks for view classes. |
886 |
// Needed because view-class lock methods throw away stamps. |
887 |
|
888 |
final void unstampedUnlockWrite() { |
889 |
WNode h; long s; |
890 |
if (((s = state) & WBIT) == 0L) |
891 |
throw new IllegalMonitorStateException(); |
892 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
893 |
if ((h = whead) != null && h.status != 0) |
894 |
release(h); |
895 |
} |
896 |
|
897 |
final void unstampedUnlockRead() { |
898 |
for (;;) { |
899 |
long s, m; WNode h; |
900 |
if ((m = (s = state) & ABITS) == 0L || m >= WBIT) |
901 |
throw new IllegalMonitorStateException(); |
902 |
else if (m < RFULL) { |
903 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
904 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
905 |
release(h); |
906 |
break; |
907 |
} |
908 |
} |
909 |
else if (tryDecReaderOverflow(s) != 0L) |
910 |
break; |
911 |
} |
912 |
} |
913 |
|
914 |
private void readObject(java.io.ObjectInputStream s) |
915 |
throws java.io.IOException, ClassNotFoundException { |
916 |
s.defaultReadObject(); |
917 |
state = ORIGIN; // reset to unlocked state |
918 |
} |
919 |
|
920 |
// internals |
921 |
|
922 |
/** |
923 |
* Tries to increment readerOverflow by first setting state |
924 |
* access bits value to RBITS, indicating hold of spinlock, |
925 |
* then updating, then releasing. |
926 |
* |
927 |
* @param s a reader overflow stamp: (s & ABITS) >= RFULL |
928 |
* @return new stamp on success, else zero |
929 |
*/ |
930 |
private long tryIncReaderOverflow(long s) { |
931 |
// assert (s & ABITS) >= RFULL; |
932 |
if ((s & ABITS) == RFULL) { |
933 |
if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { |
934 |
++readerOverflow; |
935 |
state = s; |
936 |
return s; |
937 |
} |
938 |
} |
939 |
else if ((ThreadLocalRandom.current().nextInt() & |
940 |
OVERFLOW_YIELD_RATE) == 0) |
941 |
Thread.yield(); |
942 |
return 0L; |
943 |
} |
944 |
|
945 |
/** |
946 |
* Tries to decrement readerOverflow. |
947 |
* |
948 |
* @param s a reader overflow stamp: (s & ABITS) >= RFULL |
949 |
* @return new stamp on success, else zero |
950 |
*/ |
951 |
private long tryDecReaderOverflow(long s) { |
952 |
// assert (s & ABITS) >= RFULL; |
953 |
if ((s & ABITS) == RFULL) { |
954 |
if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { |
955 |
int r; long next; |
956 |
if ((r = readerOverflow) > 0) { |
957 |
readerOverflow = r - 1; |
958 |
next = s; |
959 |
} |
960 |
else |
961 |
next = s - RUNIT; |
962 |
state = next; |
963 |
return next; |
964 |
} |
965 |
} |
966 |
else if ((ThreadLocalRandom.current().nextInt() & |
967 |
OVERFLOW_YIELD_RATE) == 0) |
968 |
Thread.yield(); |
969 |
return 0L; |
970 |
} |
971 |
|
972 |
/** |
973 |
* Wakes up the successor of h (normally whead). This is normally |
974 |
* just h.next, but may require traversal from wtail if next |
975 |
* pointers are lagging. This may fail to wake up an acquiring |
976 |
* thread when one or more have been cancelled, but the cancel |
977 |
* methods themselves provide extra safeguards to ensure liveness. |
978 |
*/ |
979 |
private void release(WNode h) { |
980 |
if (h != null) { |
981 |
WNode q; Thread w; |
982 |
U.compareAndSwapInt(h, WSTATUS, WAITING, 0); |
983 |
if ((q = h.next) == null || q.status == CANCELLED) { |
984 |
for (WNode t = wtail; t != null && t != h; t = t.prev) |
985 |
if (t.status <= 0) |
986 |
q = t; |
987 |
} |
988 |
if (q != null) { |
989 |
for (WNode r = q;;) { // release co-waiters too |
990 |
if ((w = r.thread) != null) { |
991 |
r.thread = null; |
992 |
U.unpark(w); |
993 |
} |
994 |
if ((r = q.cowait) == null) |
995 |
break; |
996 |
U.compareAndSwapObject(q, WCOWAIT, r, r.cowait); |
997 |
} |
998 |
} |
999 |
} |
1000 |
} |
1001 |
|
1002 |
/** |
1003 |
* See above for explanation. |
1004 |
* |
1005 |
* @param interruptible true if should check interrupts and if so |
1006 |
* return INTERRUPTED |
1007 |
* @param deadline if nonzero, the System.nanoTime value to timeout |
1008 |
* at (and return zero) |
1009 |
* @return next state, or INTERRUPTED |
1010 |
*/ |
1011 |
private long acquireWrite(boolean interruptible, long deadline) { |
1012 |
WNode node = null, p; |
1013 |
for (int spins = -1;;) { // spin while enqueuing |
1014 |
long s, ns; |
1015 |
if (((s = state) & ABITS) == 0L) { |
1016 |
if (U.compareAndSwapLong(this, STATE, s, ns = s + WBIT)) |
1017 |
return ns; |
1018 |
} |
1019 |
else if (spins > 0) { |
1020 |
if (ThreadLocalRandom.current().nextInt() >= 0) |
1021 |
--spins; |
1022 |
} |
1023 |
else if ((p = wtail) == null) { // initialize queue |
1024 |
WNode h = new WNode(WMODE, null); |
1025 |
if (U.compareAndSwapObject(this, WHEAD, null, h)) |
1026 |
wtail = h; |
1027 |
} |
1028 |
else if (spins < 0) |
1029 |
spins = (p == whead) ? SPINS : 0; |
1030 |
else if (node == null) |
1031 |
node = new WNode(WMODE, p); |
1032 |
else if (node.prev != p) |
1033 |
node.prev = p; |
1034 |
else if (U.compareAndSwapObject(this, WTAIL, p, node)) { |
1035 |
p.next = node; |
1036 |
break; |
1037 |
} |
1038 |
} |
1039 |
|
1040 |
for (int spins = SPINS;;) { |
1041 |
WNode np, pp; int ps; long s, ns; Thread w; |
1042 |
while ((np = node.prev) != p && np != null) |
1043 |
(p = np).next = node; // stale |
1044 |
if (whead == p) { |
1045 |
for (int k = spins;;) { // spin at head |
1046 |
if (((s = state) & ABITS) == 0L) { |
1047 |
if (U.compareAndSwapLong(this, STATE, s, ns = s+WBIT)) { |
1048 |
whead = node; |
1049 |
node.prev = null; |
1050 |
return ns; |
1051 |
} |
1052 |
} |
1053 |
else if (ThreadLocalRandom.current().nextInt() >= 0 && |
1054 |
--k <= 0) |
1055 |
break; |
1056 |
} |
1057 |
if (spins < MAX_HEAD_SPINS) |
1058 |
spins <<= 1; |
1059 |
} |
1060 |
if ((ps = p.status) == 0) |
1061 |
U.compareAndSwapInt(p, WSTATUS, 0, WAITING); |
1062 |
else if (ps == CANCELLED) { |
1063 |
if ((pp = p.prev) != null) { |
1064 |
node.prev = pp; |
1065 |
pp.next = node; |
1066 |
} |
1067 |
} |
1068 |
else { |
1069 |
long time; // 0 argument to park means no timeout |
1070 |
if (deadline == 0L) |
1071 |
time = 0L; |
1072 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1073 |
return cancelWaiter(node, node, false); |
1074 |
Thread wt = Thread.currentThread(); |
1075 |
U.putObject(wt, PARKBLOCKER, this); // emulate LockSupport.park |
1076 |
node.thread = wt; |
1077 |
if (node.prev == p && p.status == WAITING && // recheck |
1078 |
(p != whead || (state & ABITS) != 0L)) |
1079 |
U.park(false, time); |
1080 |
node.thread = null; |
1081 |
U.putObject(wt, PARKBLOCKER, null); |
1082 |
if (interruptible && Thread.interrupted()) |
1083 |
return cancelWaiter(node, node, true); |
1084 |
} |
1085 |
} |
1086 |
} |
1087 |
|
1088 |
/** |
1089 |
* See above for explanation. |
1090 |
* |
1091 |
* @param interruptible true if should check interrupts and if so |
1092 |
* return INTERRUPTED |
1093 |
* @param deadline if nonzero, the System.nanoTime value to timeout |
1094 |
* at (and return zero) |
1095 |
* @return next state, or INTERRUPTED |
1096 |
*/ |
1097 |
private long acquireRead(boolean interruptible, long deadline) { |
1098 |
WNode node = null, group = null, p; |
1099 |
for (int spins = -1;;) { |
1100 |
for (;;) { |
1101 |
long s, m, ns; WNode h, q; Thread w; // anti-barging guard |
1102 |
if (group == null && (h = whead) != null && |
1103 |
(q = h.next) != null && q.mode != RMODE) |
1104 |
break; |
1105 |
if ((m = (s = state) & ABITS) < RFULL ? |
1106 |
U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT) : |
1107 |
(m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) { |
1108 |
if (group != null) { // help release others |
1109 |
for (WNode r = group;;) { |
1110 |
if ((w = r.thread) != null) { |
1111 |
r.thread = null; |
1112 |
U.unpark(w); |
1113 |
} |
1114 |
if ((r = group.cowait) == null) |
1115 |
break; |
1116 |
U.compareAndSwapObject(group, WCOWAIT, r, r.cowait); |
1117 |
} |
1118 |
} |
1119 |
return ns; |
1120 |
} |
1121 |
if (m >= WBIT) |
1122 |
break; |
1123 |
} |
1124 |
if (spins > 0) { |
1125 |
if (ThreadLocalRandom.current().nextInt() >= 0) |
1126 |
--spins; |
1127 |
} |
1128 |
else if ((p = wtail) == null) { |
1129 |
WNode h = new WNode(WMODE, null); |
1130 |
if (U.compareAndSwapObject(this, WHEAD, null, h)) |
1131 |
wtail = h; |
1132 |
} |
1133 |
else if (spins < 0) |
1134 |
spins = (p == whead) ? SPINS : 0; |
1135 |
else if (node == null) |
1136 |
node = new WNode(WMODE, p); |
1137 |
else if (node.prev != p) |
1138 |
node.prev = p; |
1139 |
else if (p.mode == RMODE && p != whead) { |
1140 |
WNode pp = p.prev; // become co-waiter with group p |
1141 |
if (pp != null && p == wtail && |
1142 |
U.compareAndSwapObject(p, WCOWAIT, |
1143 |
node.cowait = p.cowait, node)) { |
1144 |
node.thread = Thread.currentThread(); |
1145 |
for (long time;;) { |
1146 |
if (deadline == 0L) |
1147 |
time = 0L; |
1148 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1149 |
return cancelWaiter(node, p, false); |
1150 |
if (node.thread == null) |
1151 |
break; |
1152 |
if (p.prev != pp || p.status == CANCELLED || |
1153 |
p == whead || p.prev != pp) { |
1154 |
node.thread = null; |
1155 |
break; |
1156 |
} |
1157 |
Thread wt = Thread.currentThread(); |
1158 |
U.putObject(wt, PARKBLOCKER, this); |
1159 |
if (node.thread == null) // must recheck |
1160 |
break; |
1161 |
U.park(false, time); |
1162 |
U.putObject(wt, PARKBLOCKER, null); |
1163 |
if (interruptible && Thread.interrupted()) |
1164 |
return cancelWaiter(node, p, true); |
1165 |
} |
1166 |
group = p; |
1167 |
} |
1168 |
node = null; // throw away |
1169 |
} |
1170 |
else if (U.compareAndSwapObject(this, WTAIL, p, node)) { |
1171 |
p.next = node; |
1172 |
break; |
1173 |
} |
1174 |
} |
1175 |
|
1176 |
for (int spins = SPINS;;) { |
1177 |
WNode np, pp, r; int ps; long m, s, ns; Thread w; |
1178 |
while ((np = node.prev) != p && np != null) |
1179 |
(p = np).next = node; |
1180 |
if (whead == p) { |
1181 |
for (int k = spins;;) { |
1182 |
if ((m = (s = state) & ABITS) != WBIT) { |
1183 |
if (m < RFULL ? |
1184 |
U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT): |
1185 |
(ns = tryIncReaderOverflow(s)) != 0L) { |
1186 |
whead = node; |
1187 |
node.prev = null; |
1188 |
while ((r = node.cowait) != null) { |
1189 |
if (U.compareAndSwapObject(node, WCOWAIT, |
1190 |
r, r.cowait) && |
1191 |
(w = r.thread) != null) { |
1192 |
r.thread = null; |
1193 |
U.unpark(w); // release co-waiter |
1194 |
} |
1195 |
} |
1196 |
return ns; |
1197 |
} |
1198 |
} |
1199 |
else if (ThreadLocalRandom.current().nextInt() >= 0 && |
1200 |
--k <= 0) |
1201 |
break; |
1202 |
} |
1203 |
if (spins < MAX_HEAD_SPINS) |
1204 |
spins <<= 1; |
1205 |
} |
1206 |
if ((ps = p.status) == 0) |
1207 |
U.compareAndSwapInt(p, WSTATUS, 0, WAITING); |
1208 |
else if (ps == CANCELLED) { |
1209 |
if ((pp = p.prev) != null) { |
1210 |
node.prev = pp; |
1211 |
pp.next = node; |
1212 |
} |
1213 |
} |
1214 |
else { |
1215 |
long time; |
1216 |
if (deadline == 0L) |
1217 |
time = 0L; |
1218 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1219 |
return cancelWaiter(node, node, false); |
1220 |
Thread wt = Thread.currentThread(); |
1221 |
U.putObject(wt, PARKBLOCKER, this); |
1222 |
node.thread = wt; |
1223 |
if (node.prev == p && p.status == WAITING && |
1224 |
(p != whead || (state & ABITS) != WBIT)) |
1225 |
U.park(false, time); |
1226 |
node.thread = null; |
1227 |
U.putObject(wt, PARKBLOCKER, null); |
1228 |
if (interruptible && Thread.interrupted()) |
1229 |
return cancelWaiter(node, node, true); |
1230 |
} |
1231 |
} |
1232 |
} |
1233 |
|
1234 |
/** |
1235 |
* If node non-null, forces cancel status and unsplices it from |
1236 |
* queue if possible and wakes up any cowaiters (of the node, or |
1237 |
* group, as applicable), and in any case helps release current |
1238 |
* first waiter if lock is free. (Calling with null arguments |
1239 |
* serves as a conditional form of release, which is not currently |
1240 |
* needed but may be needed under possible future cancellation |
1241 |
* policies). This is a variant of cancellation methods in |
1242 |
* AbstractQueuedSynchronizer (see its detailed explanation in AQS |
1243 |
* internal documentation). |
1244 |
* |
1245 |
* @param node if nonnull, the waiter |
1246 |
* @param group either node or the group node is cowaiting with |
1247 |
* @param interrupted if already interrupted |
1248 |
* @return INTERRUPTED if interrupted or Thread.interrupted, else zero |
1249 |
*/ |
1250 |
private long cancelWaiter(WNode node, WNode group, boolean interrupted) { |
1251 |
if (node != null && group != null) { |
1252 |
Thread w; |
1253 |
node.status = CANCELLED; |
1254 |
node.thread = null; |
1255 |
// unsplice cancelled nodes from group |
1256 |
for (WNode p = group, q; (q = p.cowait) != null;) { |
1257 |
if (q.status == CANCELLED) |
1258 |
U.compareAndSwapObject(p, WNEXT, q, q.next); |
1259 |
else |
1260 |
p = q; |
1261 |
} |
1262 |
if (group == node) { |
1263 |
WNode r; // detach and wake up uncancelled co-waiters |
1264 |
while ((r = node.cowait) != null) { |
1265 |
if (U.compareAndSwapObject(node, WCOWAIT, r, r.cowait) && |
1266 |
(w = r.thread) != null) { |
1267 |
r.thread = null; |
1268 |
U.unpark(w); |
1269 |
} |
1270 |
} |
1271 |
for (WNode pred = node.prev; pred != null; ) { // unsplice |
1272 |
WNode succ, pp; // find valid successor |
1273 |
while ((succ = node.next) == null || |
1274 |
succ.status == CANCELLED) { |
1275 |
WNode q = null; // find successor the slow way |
1276 |
for (WNode t = wtail; t != null && t != node; t = t.prev) |
1277 |
if (t.status != CANCELLED) |
1278 |
q = t; // don't link if succ cancelled |
1279 |
if (succ == q || // ensure accurate successor |
1280 |
U.compareAndSwapObject(node, WNEXT, |
1281 |
succ, succ = q)) { |
1282 |
if (succ == null && node == wtail) |
1283 |
U.compareAndSwapObject(this, WTAIL, node, pred); |
1284 |
break; |
1285 |
} |
1286 |
} |
1287 |
if (pred.next == node) // unsplice pred link |
1288 |
U.compareAndSwapObject(pred, WNEXT, node, succ); |
1289 |
if (succ != null && (w = succ.thread) != null) { |
1290 |
succ.thread = null; |
1291 |
U.unpark(w); // wake up succ to observe new pred |
1292 |
} |
1293 |
if (pred.status != CANCELLED || (pp = pred.prev) == null) |
1294 |
break; |
1295 |
node.prev = pp; // repeat if new pred wrong/cancelled |
1296 |
U.compareAndSwapObject(pp, WNEXT, pred, succ); |
1297 |
pred = pp; |
1298 |
} |
1299 |
} |
1300 |
} |
1301 |
WNode h; // Possibly release first waiter |
1302 |
while ((h = whead) != null) { |
1303 |
long s; WNode q; // similar to release() but check eligibility |
1304 |
if ((q = h.next) == null || q.status == CANCELLED) { |
1305 |
for (WNode t = wtail; t != null && t != h; t = t.prev) |
1306 |
if (t.status <= 0) |
1307 |
q = t; |
1308 |
} |
1309 |
if (h == whead) { |
1310 |
if (q != null && h.status == 0 && |
1311 |
((s = state) & ABITS) != WBIT && // waiter is eligible |
1312 |
(s == 0L || q.mode == RMODE)) |
1313 |
release(h); |
1314 |
break; |
1315 |
} |
1316 |
} |
1317 |
return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L; |
1318 |
} |
1319 |
|
1320 |
// Unsafe mechanics |
1321 |
private static final sun.misc.Unsafe U; |
1322 |
private static final long STATE; |
1323 |
private static final long WHEAD; |
1324 |
private static final long WTAIL; |
1325 |
private static final long WNEXT; |
1326 |
private static final long WSTATUS; |
1327 |
private static final long WCOWAIT; |
1328 |
private static final long PARKBLOCKER; |
1329 |
|
1330 |
static { |
1331 |
try { |
1332 |
U = getUnsafe(); |
1333 |
Class<?> k = StampedLock.class; |
1334 |
Class<?> wk = WNode.class; |
1335 |
STATE = U.objectFieldOffset |
1336 |
(k.getDeclaredField("state")); |
1337 |
WHEAD = U.objectFieldOffset |
1338 |
(k.getDeclaredField("whead")); |
1339 |
WTAIL = U.objectFieldOffset |
1340 |
(k.getDeclaredField("wtail")); |
1341 |
WSTATUS = U.objectFieldOffset |
1342 |
(wk.getDeclaredField("status")); |
1343 |
WNEXT = U.objectFieldOffset |
1344 |
(wk.getDeclaredField("next")); |
1345 |
WCOWAIT = U.objectFieldOffset |
1346 |
(wk.getDeclaredField("cowait")); |
1347 |
Class<?> tk = Thread.class; |
1348 |
PARKBLOCKER = U.objectFieldOffset |
1349 |
(tk.getDeclaredField("parkBlocker")); |
1350 |
|
1351 |
} catch (Exception e) { |
1352 |
throw new Error(e); |
1353 |
} |
1354 |
} |
1355 |
|
1356 |
/** |
1357 |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1358 |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1359 |
* into a jdk. |
1360 |
* |
1361 |
* @return a sun.misc.Unsafe |
1362 |
*/ |
1363 |
private static sun.misc.Unsafe getUnsafe() { |
1364 |
try { |
1365 |
return sun.misc.Unsafe.getUnsafe(); |
1366 |
} catch (SecurityException tryReflectionInstead) {} |
1367 |
try { |
1368 |
return java.security.AccessController.doPrivileged |
1369 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1370 |
public sun.misc.Unsafe run() throws Exception { |
1371 |
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; |
1372 |
for (java.lang.reflect.Field f : k.getDeclaredFields()) { |
1373 |
f.setAccessible(true); |
1374 |
Object x = f.get(null); |
1375 |
if (k.isInstance(x)) |
1376 |
return k.cast(x); |
1377 |
} |
1378 |
throw new NoSuchFieldError("the Unsafe"); |
1379 |
}}); |
1380 |
} catch (java.security.PrivilegedActionException e) { |
1381 |
throw new RuntimeException("Could not initialize intrinsics", |
1382 |
e.getCause()); |
1383 |
} |
1384 |
} |
1385 |
} |