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 |
|
9 |
import java.util.concurrent.TimeUnit; |
10 |
import java.util.concurrent.locks.Lock; |
11 |
import java.util.concurrent.locks.Condition; |
12 |
import java.util.concurrent.locks.ReadWriteLock; |
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. |
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. |
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. |
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.) Method release |
200 |
* does not (and sometimes cannot) itself wake up cowaiters. This |
201 |
* is done by the primary thread, but helped by any other threads |
202 |
* with nothing better to do in methods acquireRead and |
203 |
* acquireWrite. |
204 |
* |
205 |
* These rules apply to threads actually queued. All tryLock forms |
206 |
* opportunistically try to acquire locks regardless of preference |
207 |
* rules, and so may "barge" their way in. Randomized spinning is |
208 |
* used in the acquire methods to reduce (increasingly expensive) |
209 |
* context switching while also avoiding sustained memory |
210 |
* thrashing among many threads. We limit spins to the head of |
211 |
* queue. A thread spin-waits up to SPINS times (where each |
212 |
* iteration decreases spin count with 50% probability) before |
213 |
* blocking. If, upon wakening it fails to obtain lock, and is |
214 |
* still (or becomes) the first waiting thread (which indicates |
215 |
* that some other thread barged and obtained lock), it escalates |
216 |
* spins (up to MAX_HEAD_SPINS) to reduce the likelihood of |
217 |
* continually losing to barging threads. |
218 |
* |
219 |
* Nearly all of these mechanics are carried out in methods |
220 |
* acquireWrite and acquireRead, that, as typical of such code, |
221 |
* sprawl out because actions and retries rely on consistent sets |
222 |
* of locally cached reads. |
223 |
* |
224 |
* As noted in Boehm's paper (above), sequence validation (mainly |
225 |
* method validate()) requires stricter ordering rules than apply |
226 |
* to normal volatile reads (of "state"). In the absence of (but |
227 |
* continual hope for) explicit JVM support of intrinsics with |
228 |
* double-sided reordering prohibition, or corresponding fence |
229 |
* intrinsics, we for now uncomfortably rely on the fact that the |
230 |
* Unsafe.getXVolatile intrinsic must have this property |
231 |
* (syntactic volatile reads do not) for internal purposes anyway, |
232 |
* even though it is not documented. |
233 |
* |
234 |
* The memory layout keeps lock state and queue pointers together |
235 |
* (normally on the same cache line). This usually works well for |
236 |
* read-mostly loads. In most other cases, the natural tendency of |
237 |
* adaptive-spin CLH locks to reduce memory contention lessens |
238 |
* motivation to further spread out contended locations, but might |
239 |
* be subject to future improvements. |
240 |
*/ |
241 |
|
242 |
private static final long serialVersionUID = -6001602636862214147L; |
243 |
|
244 |
/** Number of processors, for spin control */ |
245 |
private static final int NCPU = Runtime.getRuntime().availableProcessors(); |
246 |
|
247 |
/** Maximum number of retries before enqueuing on acquisition */ |
248 |
private static final int SPINS = (NCPU > 1) ? 1 << 6 : 0; |
249 |
|
250 |
/** Maximum number of retries before blocking at head on acquisition */ |
251 |
private static final int HEAD_SPINS = (NCPU > 1) ? 1 << 10 : 0; |
252 |
|
253 |
/** Maximum number of retries before re-blocking */ |
254 |
private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 16 : 0; |
255 |
|
256 |
/** The period for yielding when waiting for overflow spinlock */ |
257 |
private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1 |
258 |
|
259 |
/** The number of bits to use for reader count before overflowing */ |
260 |
private static final int LG_READERS = 7; |
261 |
|
262 |
// Values for lock state and stamp operations |
263 |
private static final long RUNIT = 1L; |
264 |
private static final long WBIT = 1L << LG_READERS; |
265 |
private static final long RBITS = WBIT - 1L; |
266 |
private static final long RFULL = RBITS - 1L; |
267 |
private static final long ABITS = RBITS | WBIT; |
268 |
private static final long SBITS = ~RBITS; // note overlap with ABITS |
269 |
|
270 |
// Initial value for lock state; avoid failure value zero |
271 |
private static final long ORIGIN = WBIT << 1; |
272 |
|
273 |
// Special value from cancelled acquire methods so caller can throw IE |
274 |
private static final long INTERRUPTED = 1L; |
275 |
|
276 |
// Values for node status; order matters |
277 |
private static final int WAITING = -1; |
278 |
private static final int CANCELLED = 1; |
279 |
|
280 |
// Modes for nodes (int not boolean to allow arithmetic) |
281 |
private static final int RMODE = 0; |
282 |
private static final int WMODE = 1; |
283 |
|
284 |
/** Wait nodes */ |
285 |
static final class WNode { |
286 |
volatile WNode prev; |
287 |
volatile WNode next; |
288 |
volatile WNode cowait; // list of linked readers |
289 |
volatile Thread thread; // non-null while possibly parked |
290 |
volatile int status; // 0, WAITING, or CANCELLED |
291 |
final int mode; // RMODE or WMODE |
292 |
WNode(int m, WNode p) { mode = m; prev = p; } |
293 |
} |
294 |
|
295 |
/** Head of CLH queue */ |
296 |
private transient volatile WNode whead; |
297 |
/** Tail (last) of CLH queue */ |
298 |
private transient volatile WNode wtail; |
299 |
|
300 |
// views |
301 |
transient ReadLockView readLockView; |
302 |
transient WriteLockView writeLockView; |
303 |
transient ReadWriteLockView readWriteLockView; |
304 |
|
305 |
/** Lock sequence/state */ |
306 |
private transient volatile long state; |
307 |
/** extra reader count when state read count saturated */ |
308 |
private transient int readerOverflow; |
309 |
|
310 |
/** |
311 |
* Creates a new lock, initially in unlocked state. |
312 |
*/ |
313 |
public StampedLock() { |
314 |
state = ORIGIN; |
315 |
} |
316 |
|
317 |
/** |
318 |
* Exclusively acquires the lock, blocking if necessary |
319 |
* until available. |
320 |
* |
321 |
* @return a stamp that can be used to unlock or convert mode |
322 |
*/ |
323 |
public long writeLock() { |
324 |
long s, next; // bypass acquireWrite in fully unlocked case only |
325 |
return ((((s = state) & ABITS) == 0L && |
326 |
U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ? |
327 |
next : acquireWrite(false, 0L)); |
328 |
} |
329 |
|
330 |
/** |
331 |
* Exclusively acquires the lock if it is immediately available. |
332 |
* |
333 |
* @return a stamp that can be used to unlock or convert mode, |
334 |
* or zero if the lock is not available |
335 |
*/ |
336 |
public long tryWriteLock() { |
337 |
long s, next; |
338 |
return ((((s = state) & ABITS) == 0L && |
339 |
U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ? |
340 |
next : 0L); |
341 |
} |
342 |
|
343 |
/** |
344 |
* Exclusively acquires the lock if it is available within the |
345 |
* given time and the current thread has not been interrupted. |
346 |
* Behavior under timeout and interruption matches that specified |
347 |
* for method {@link Lock#tryLock(long,TimeUnit)}. |
348 |
* |
349 |
* @param time the maximum time to wait for the lock |
350 |
* @param unit the time unit of the {@code time} argument |
351 |
* @return a stamp that can be used to unlock or convert mode, |
352 |
* or zero if the lock is not available |
353 |
* @throws InterruptedException if the current thread is interrupted |
354 |
* before acquiring the lock |
355 |
*/ |
356 |
public long tryWriteLock(long time, TimeUnit unit) |
357 |
throws InterruptedException { |
358 |
long nanos = unit.toNanos(time); |
359 |
if (!Thread.interrupted()) { |
360 |
long next, deadline; |
361 |
if ((next = tryWriteLock()) != 0L) |
362 |
return next; |
363 |
if (nanos <= 0L) |
364 |
return 0L; |
365 |
if ((deadline = System.nanoTime() + nanos) == 0L) |
366 |
deadline = 1L; |
367 |
if ((next = acquireWrite(true, deadline)) != INTERRUPTED) |
368 |
return next; |
369 |
} |
370 |
throw new InterruptedException(); |
371 |
} |
372 |
|
373 |
/** |
374 |
* Exclusively acquires the lock, blocking if necessary |
375 |
* until available or the current thread is interrupted. |
376 |
* Behavior under interruption matches that specified |
377 |
* for method {@link Lock#lockInterruptibly()}. |
378 |
* |
379 |
* @return a stamp that can be used to unlock or convert mode |
380 |
* @throws InterruptedException if the current thread is interrupted |
381 |
* before acquiring the lock |
382 |
*/ |
383 |
public long writeLockInterruptibly() throws InterruptedException { |
384 |
long next; |
385 |
if (!Thread.interrupted() && |
386 |
(next = acquireWrite(true, 0L)) != INTERRUPTED) |
387 |
return next; |
388 |
throw new InterruptedException(); |
389 |
} |
390 |
|
391 |
/** |
392 |
* Non-exclusively acquires the lock, blocking if necessary |
393 |
* until available. |
394 |
* |
395 |
* @return a stamp that can be used to unlock or convert mode |
396 |
*/ |
397 |
public long readLock() { |
398 |
long s = state, next; // bypass acquireRead on common uncontended case |
399 |
return ((whead == wtail && (s & ABITS) < RFULL && |
400 |
U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) ? |
401 |
next : acquireRead(false, 0L)); |
402 |
} |
403 |
|
404 |
/** |
405 |
* Non-exclusively acquires the lock if it is immediately available. |
406 |
* |
407 |
* @return a stamp that can be used to unlock or convert mode, |
408 |
* or zero if the lock is not available |
409 |
*/ |
410 |
public long tryReadLock() { |
411 |
for (;;) { |
412 |
long s, m, next; |
413 |
if ((m = (s = state) & ABITS) == WBIT) |
414 |
return 0L; |
415 |
else if (m < RFULL) { |
416 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
417 |
return next; |
418 |
} |
419 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
420 |
return next; |
421 |
} |
422 |
} |
423 |
|
424 |
/** |
425 |
* Non-exclusively acquires the lock if it is available within the |
426 |
* given time and the current thread has not been interrupted. |
427 |
* Behavior under timeout and interruption matches that specified |
428 |
* for method {@link Lock#tryLock(long,TimeUnit)}. |
429 |
* |
430 |
* @param time the maximum time to wait for the lock |
431 |
* @param unit the time unit of the {@code time} argument |
432 |
* @return a stamp that can be used to unlock or convert mode, |
433 |
* or zero if the lock is not available |
434 |
* @throws InterruptedException if the current thread is interrupted |
435 |
* before acquiring the lock |
436 |
*/ |
437 |
public long tryReadLock(long time, TimeUnit unit) |
438 |
throws InterruptedException { |
439 |
long s, m, next, deadline; |
440 |
long nanos = unit.toNanos(time); |
441 |
if (!Thread.interrupted()) { |
442 |
if ((m = (s = state) & ABITS) != WBIT) { |
443 |
if (m < RFULL) { |
444 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
445 |
return next; |
446 |
} |
447 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
448 |
return next; |
449 |
} |
450 |
if (nanos <= 0L) |
451 |
return 0L; |
452 |
if ((deadline = System.nanoTime() + nanos) == 0L) |
453 |
deadline = 1L; |
454 |
if ((next = acquireRead(true, deadline)) != INTERRUPTED) |
455 |
return next; |
456 |
} |
457 |
throw new InterruptedException(); |
458 |
} |
459 |
|
460 |
/** |
461 |
* Non-exclusively acquires the lock, blocking if necessary |
462 |
* until available or the current thread is interrupted. |
463 |
* Behavior under interruption matches that specified |
464 |
* for method {@link Lock#lockInterruptibly()}. |
465 |
* |
466 |
* @return a stamp that can be used to unlock or convert mode |
467 |
* @throws InterruptedException if the current thread is interrupted |
468 |
* before acquiring the lock |
469 |
*/ |
470 |
public long readLockInterruptibly() throws InterruptedException { |
471 |
long next; |
472 |
if (!Thread.interrupted() && |
473 |
(next = acquireRead(true, 0L)) != INTERRUPTED) |
474 |
return next; |
475 |
throw new InterruptedException(); |
476 |
} |
477 |
|
478 |
/** |
479 |
* Returns a stamp that can later be validated, or zero |
480 |
* if exclusively locked. |
481 |
* |
482 |
* @return a stamp, or zero if exclusively locked |
483 |
*/ |
484 |
public long tryOptimisticRead() { |
485 |
long s; |
486 |
return (((s = state) & WBIT) == 0L) ? (s & SBITS) : 0L; |
487 |
} |
488 |
|
489 |
/** |
490 |
* Returns true if the lock has not been exclusively acquired |
491 |
* since issuance of the given stamp. Always returns false if the |
492 |
* stamp is zero. Always returns true if the stamp represents a |
493 |
* currently held lock. Invoking this method with a value not |
494 |
* obtained from {@link #tryOptimisticRead} or a locking method |
495 |
* for this lock has no defined effect or result. |
496 |
* |
497 |
* @param stamp a stamp |
498 |
* @return {@code true} if the lock has not been exclusively acquired |
499 |
* since issuance of the given stamp; else false |
500 |
*/ |
501 |
public boolean validate(long stamp) { |
502 |
// See above about current use of getLongVolatile here |
503 |
return (stamp & SBITS) == (U.getLongVolatile(this, STATE) & SBITS); |
504 |
} |
505 |
|
506 |
/** |
507 |
* If the lock state matches the given stamp, releases the |
508 |
* exclusive lock. |
509 |
* |
510 |
* @param stamp a stamp returned by a write-lock operation |
511 |
* @throws IllegalMonitorStateException if the stamp does |
512 |
* not match the current state of this lock |
513 |
*/ |
514 |
public void unlockWrite(long stamp) { |
515 |
WNode h; |
516 |
if (state != stamp || (stamp & WBIT) == 0L) |
517 |
throw new IllegalMonitorStateException(); |
518 |
state = (stamp += WBIT) == 0L ? ORIGIN : stamp; |
519 |
if ((h = whead) != null && h.status != 0) |
520 |
release(h); |
521 |
} |
522 |
|
523 |
/** |
524 |
* If the lock state matches the given stamp, releases the |
525 |
* non-exclusive lock. |
526 |
* |
527 |
* @param stamp a stamp returned by a read-lock operation |
528 |
* @throws IllegalMonitorStateException if the stamp does |
529 |
* not match the current state of this lock |
530 |
*/ |
531 |
public void unlockRead(long stamp) { |
532 |
long s, m; WNode h; |
533 |
for (;;) { |
534 |
if (((s = state) & SBITS) != (stamp & SBITS) || |
535 |
(stamp & ABITS) == 0L || (m = s & ABITS) == 0L || m == WBIT) |
536 |
throw new IllegalMonitorStateException(); |
537 |
if (m < RFULL) { |
538 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
539 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
540 |
release(h); |
541 |
break; |
542 |
} |
543 |
} |
544 |
else if (tryDecReaderOverflow(s) != 0L) |
545 |
break; |
546 |
} |
547 |
} |
548 |
|
549 |
/** |
550 |
* If the lock state matches the given stamp, releases the |
551 |
* corresponding mode of the lock. |
552 |
* |
553 |
* @param stamp a stamp returned by a lock operation |
554 |
* @throws IllegalMonitorStateException if the stamp does |
555 |
* not match the current state of this lock |
556 |
*/ |
557 |
public void unlock(long stamp) { |
558 |
long a = stamp & ABITS, m, s; WNode h; |
559 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
560 |
if ((m = s & ABITS) == 0L) |
561 |
break; |
562 |
else if (m == WBIT) { |
563 |
if (a != m) |
564 |
break; |
565 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
566 |
if ((h = whead) != null && h.status != 0) |
567 |
release(h); |
568 |
return; |
569 |
} |
570 |
else if (a == 0L || a >= WBIT) |
571 |
break; |
572 |
else if (m < RFULL) { |
573 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
574 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
575 |
release(h); |
576 |
return; |
577 |
} |
578 |
} |
579 |
else if (tryDecReaderOverflow(s) != 0L) |
580 |
return; |
581 |
} |
582 |
throw new IllegalMonitorStateException(); |
583 |
} |
584 |
|
585 |
/** |
586 |
* If the lock state matches the given stamp, performs one of |
587 |
* the following actions. If the stamp represents holding a write |
588 |
* lock, returns it. Or, if a read lock, if the write lock is |
589 |
* available, releases the read lock and returns a write stamp. |
590 |
* Or, if an optimistic read, returns a write stamp only if |
591 |
* immediately available. This method returns zero in all other |
592 |
* cases. |
593 |
* |
594 |
* @param stamp a stamp |
595 |
* @return a valid write stamp, or zero on failure |
596 |
*/ |
597 |
public long tryConvertToWriteLock(long stamp) { |
598 |
long a = stamp & ABITS, m, s, next; |
599 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
600 |
if ((m = s & ABITS) == 0L) { |
601 |
if (a != 0L) |
602 |
break; |
603 |
if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) |
604 |
return next; |
605 |
} |
606 |
else if (m == WBIT) { |
607 |
if (a != m) |
608 |
break; |
609 |
return stamp; |
610 |
} |
611 |
else if (m == RUNIT && a != 0L) { |
612 |
if (U.compareAndSwapLong(this, STATE, s, |
613 |
next = s - RUNIT + WBIT)) |
614 |
return next; |
615 |
} |
616 |
else |
617 |
break; |
618 |
} |
619 |
return 0L; |
620 |
} |
621 |
|
622 |
/** |
623 |
* If the lock state matches the given stamp, performs one of |
624 |
* the following actions. If the stamp represents holding a write |
625 |
* lock, releases it and obtains a read lock. Or, if a read lock, |
626 |
* returns it. Or, if an optimistic read, acquires a read lock and |
627 |
* returns a read stamp only if immediately available. This method |
628 |
* returns zero in all other cases. |
629 |
* |
630 |
* @param stamp a stamp |
631 |
* @return a valid read stamp, or zero on failure |
632 |
*/ |
633 |
public long tryConvertToReadLock(long stamp) { |
634 |
long a = stamp & ABITS, m, s, next; WNode h; |
635 |
while (((s = state) & SBITS) == (stamp & SBITS)) { |
636 |
if ((m = s & ABITS) == 0L) { |
637 |
if (a != 0L) |
638 |
break; |
639 |
else if (m < RFULL) { |
640 |
if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) |
641 |
return next; |
642 |
} |
643 |
else if ((next = tryIncReaderOverflow(s)) != 0L) |
644 |
return next; |
645 |
} |
646 |
else if (m == WBIT) { |
647 |
if (a != m) |
648 |
break; |
649 |
state = next = s + (WBIT + RUNIT); |
650 |
if ((h = whead) != null && h.status != 0) |
651 |
release(h); |
652 |
return next; |
653 |
} |
654 |
else if (a != 0L && a < WBIT) |
655 |
return stamp; |
656 |
else |
657 |
break; |
658 |
} |
659 |
return 0L; |
660 |
} |
661 |
|
662 |
/** |
663 |
* If the lock state matches the given stamp then, if the stamp |
664 |
* represents holding a lock, releases it and returns an |
665 |
* observation stamp. Or, if an optimistic read, returns it if |
666 |
* validated. This method returns zero in all other cases, and so |
667 |
* may be useful as a form of "tryUnlock". |
668 |
* |
669 |
* @param stamp a stamp |
670 |
* @return a valid optimistic read stamp, or zero on failure |
671 |
*/ |
672 |
public long tryConvertToOptimisticRead(long stamp) { |
673 |
long a = stamp & ABITS, m, s, next; WNode h; |
674 |
for (;;) { |
675 |
s = U.getLongVolatile(this, STATE); // see above |
676 |
if (((s = state) & SBITS) != (stamp & SBITS)) |
677 |
break; |
678 |
if ((m = s & ABITS) == 0L) { |
679 |
if (a != 0L) |
680 |
break; |
681 |
return s; |
682 |
} |
683 |
else if (m == WBIT) { |
684 |
if (a != m) |
685 |
break; |
686 |
state = next = (s += WBIT) == 0L ? ORIGIN : s; |
687 |
if ((h = whead) != null && h.status != 0) |
688 |
release(h); |
689 |
return next; |
690 |
} |
691 |
else if (a == 0L || a >= WBIT) |
692 |
break; |
693 |
else if (m < RFULL) { |
694 |
if (U.compareAndSwapLong(this, STATE, s, next = s - RUNIT)) { |
695 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
696 |
release(h); |
697 |
return next & SBITS; |
698 |
} |
699 |
} |
700 |
else if ((next = tryDecReaderOverflow(s)) != 0L) |
701 |
return next & SBITS; |
702 |
} |
703 |
return 0L; |
704 |
} |
705 |
|
706 |
/** |
707 |
* Releases the write lock if it is held, without requiring a |
708 |
* stamp value. This method may be useful for recovery after |
709 |
* errors. |
710 |
* |
711 |
* @return {@code true} if the lock was held, else false |
712 |
*/ |
713 |
public boolean tryUnlockWrite() { |
714 |
long s; WNode h; |
715 |
if (((s = state) & WBIT) != 0L) { |
716 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
717 |
if ((h = whead) != null && h.status != 0) |
718 |
release(h); |
719 |
return true; |
720 |
} |
721 |
return false; |
722 |
} |
723 |
|
724 |
/** |
725 |
* Releases one hold of the read lock if it is held, without |
726 |
* requiring a stamp value. This method may be useful for recovery |
727 |
* after errors. |
728 |
* |
729 |
* @return {@code true} if the read lock was held, else false |
730 |
*/ |
731 |
public boolean tryUnlockRead() { |
732 |
long s, m; WNode h; |
733 |
while ((m = (s = state) & ABITS) != 0L && m < WBIT) { |
734 |
if (m < RFULL) { |
735 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
736 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
737 |
release(h); |
738 |
return true; |
739 |
} |
740 |
} |
741 |
else if (tryDecReaderOverflow(s) != 0L) |
742 |
return true; |
743 |
} |
744 |
return false; |
745 |
} |
746 |
|
747 |
// status monitoring methods |
748 |
|
749 |
/** |
750 |
* Returns combined state-held and overflow read count for given |
751 |
* state s. |
752 |
*/ |
753 |
private int getReadLockCount(long s) { |
754 |
long readers; |
755 |
if ((readers = s & RBITS) >= RFULL) |
756 |
readers = RFULL + readerOverflow; |
757 |
return (int) readers; |
758 |
} |
759 |
|
760 |
/** |
761 |
* Returns {@code true} if the lock is currently held exclusively. |
762 |
* |
763 |
* @return {@code true} if the lock is currently held exclusively |
764 |
*/ |
765 |
public boolean isWriteLocked() { |
766 |
return (state & WBIT) != 0L; |
767 |
} |
768 |
|
769 |
/** |
770 |
* Returns {@code true} if the lock is currently held non-exclusively. |
771 |
* |
772 |
* @return {@code true} if the lock is currently held non-exclusively |
773 |
*/ |
774 |
public boolean isReadLocked() { |
775 |
return (state & RBITS) != 0L; |
776 |
} |
777 |
|
778 |
/** |
779 |
* Queries the number of read locks held for this lock. This |
780 |
* method is designed for use in monitoring system state, not for |
781 |
* synchronization control. |
782 |
* @return the number of read locks held |
783 |
*/ |
784 |
public int getReadLockCount() { |
785 |
return getReadLockCount(state); |
786 |
} |
787 |
|
788 |
/** |
789 |
* Returns a string identifying this lock, as well as its lock |
790 |
* state. The state, in brackets, includes the String {@code |
791 |
* "Unlocked"} or the String {@code "Write-locked"} or the String |
792 |
* {@code "Read-locks:"} followed by the current number of |
793 |
* read-locks held. |
794 |
* |
795 |
* @return a string identifying this lock, as well as its lock state |
796 |
*/ |
797 |
public String toString() { |
798 |
long s = state; |
799 |
return super.toString() + |
800 |
((s & ABITS) == 0L ? "[Unlocked]" : |
801 |
(s & WBIT) != 0L ? "[Write-locked]" : |
802 |
"[Read-locks:" + getReadLockCount(s) + "]"); |
803 |
} |
804 |
|
805 |
// views |
806 |
|
807 |
/** |
808 |
* Returns a plain {@link Lock} view of this StampedLock in which |
809 |
* the {@link Lock#lock} method is mapped to {@link #readLock}, |
810 |
* and similarly for other methods. The returned Lock does not |
811 |
* support a {@link Condition}; method {@link |
812 |
* Lock#newCondition()} throws {@code |
813 |
* UnsupportedOperationException}. |
814 |
* |
815 |
* @return the lock |
816 |
*/ |
817 |
public Lock asReadLock() { |
818 |
ReadLockView v; |
819 |
return ((v = readLockView) != null ? v : |
820 |
(readLockView = new ReadLockView())); |
821 |
} |
822 |
|
823 |
/** |
824 |
* Returns a plain {@link Lock} view of this StampedLock in which |
825 |
* the {@link Lock#lock} method is mapped to {@link #writeLock}, |
826 |
* and similarly for other methods. The returned Lock does not |
827 |
* support a {@link Condition}; method {@link |
828 |
* Lock#newCondition()} throws {@code |
829 |
* UnsupportedOperationException}. |
830 |
* |
831 |
* @return the lock |
832 |
*/ |
833 |
public Lock asWriteLock() { |
834 |
WriteLockView v; |
835 |
return ((v = writeLockView) != null ? v : |
836 |
(writeLockView = new WriteLockView())); |
837 |
} |
838 |
|
839 |
/** |
840 |
* Returns a {@link ReadWriteLock} view of this StampedLock in |
841 |
* which the {@link ReadWriteLock#readLock()} method is mapped to |
842 |
* {@link #asReadLock()}, and {@link ReadWriteLock#writeLock()} to |
843 |
* {@link #asWriteLock()}. |
844 |
* |
845 |
* @return the lock |
846 |
*/ |
847 |
public ReadWriteLock asReadWriteLock() { |
848 |
ReadWriteLockView v; |
849 |
return ((v = readWriteLockView) != null ? v : |
850 |
(readWriteLockView = new ReadWriteLockView())); |
851 |
} |
852 |
|
853 |
// view classes |
854 |
|
855 |
final class ReadLockView implements Lock { |
856 |
public void lock() { readLock(); } |
857 |
public void lockInterruptibly() throws InterruptedException { |
858 |
readLockInterruptibly(); |
859 |
} |
860 |
public boolean tryLock() { return tryReadLock() != 0L; } |
861 |
public boolean tryLock(long time, TimeUnit unit) |
862 |
throws InterruptedException { |
863 |
return tryReadLock(time, unit) != 0L; |
864 |
} |
865 |
public void unlock() { unstampedUnlockRead(); } |
866 |
public Condition newCondition() { |
867 |
throw new UnsupportedOperationException(); |
868 |
} |
869 |
} |
870 |
|
871 |
final class WriteLockView implements Lock { |
872 |
public void lock() { writeLock(); } |
873 |
public void lockInterruptibly() throws InterruptedException { |
874 |
writeLockInterruptibly(); |
875 |
} |
876 |
public boolean tryLock() { return tryWriteLock() != 0L; } |
877 |
public boolean tryLock(long time, TimeUnit unit) |
878 |
throws InterruptedException { |
879 |
return tryWriteLock(time, unit) != 0L; |
880 |
} |
881 |
public void unlock() { unstampedUnlockWrite(); } |
882 |
public Condition newCondition() { |
883 |
throw new UnsupportedOperationException(); |
884 |
} |
885 |
} |
886 |
|
887 |
final class ReadWriteLockView implements ReadWriteLock { |
888 |
public Lock readLock() { return asReadLock(); } |
889 |
public Lock writeLock() { return asWriteLock(); } |
890 |
} |
891 |
|
892 |
// Unlock methods without stamp argument checks for view classes. |
893 |
// Needed because view-class lock methods throw away stamps. |
894 |
|
895 |
final void unstampedUnlockWrite() { |
896 |
WNode h; long s; |
897 |
if (((s = state) & WBIT) == 0L) |
898 |
throw new IllegalMonitorStateException(); |
899 |
state = (s += WBIT) == 0L ? ORIGIN : s; |
900 |
if ((h = whead) != null && h.status != 0) |
901 |
release(h); |
902 |
} |
903 |
|
904 |
final void unstampedUnlockRead() { |
905 |
for (;;) { |
906 |
long s, m; WNode h; |
907 |
if ((m = (s = state) & ABITS) == 0L || m >= WBIT) |
908 |
throw new IllegalMonitorStateException(); |
909 |
else if (m < RFULL) { |
910 |
if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) { |
911 |
if (m == RUNIT && (h = whead) != null && h.status != 0) |
912 |
release(h); |
913 |
break; |
914 |
} |
915 |
} |
916 |
else if (tryDecReaderOverflow(s) != 0L) |
917 |
break; |
918 |
} |
919 |
} |
920 |
|
921 |
private void readObject(java.io.ObjectInputStream s) |
922 |
throws java.io.IOException, ClassNotFoundException { |
923 |
s.defaultReadObject(); |
924 |
state = ORIGIN; // reset to unlocked state |
925 |
} |
926 |
|
927 |
// internals |
928 |
|
929 |
/** |
930 |
* Tries to increment readerOverflow by first setting state |
931 |
* access bits value to RBITS, indicating hold of spinlock, |
932 |
* then updating, then releasing. |
933 |
* |
934 |
* @param s a reader overflow stamp: (s & ABITS) >= RFULL |
935 |
* @return new stamp on success, else zero |
936 |
*/ |
937 |
private long tryIncReaderOverflow(long s) { |
938 |
// assert (s & ABITS) >= RFULL; |
939 |
if ((s & ABITS) == RFULL) { |
940 |
if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { |
941 |
++readerOverflow; |
942 |
state = s; |
943 |
return s; |
944 |
} |
945 |
} |
946 |
else if ((ThreadLocalRandom.current().nextInt() & |
947 |
OVERFLOW_YIELD_RATE) == 0) |
948 |
Thread.yield(); |
949 |
return 0L; |
950 |
} |
951 |
|
952 |
/** |
953 |
* Tries to decrement readerOverflow. |
954 |
* |
955 |
* @param s a reader overflow stamp: (s & ABITS) >= RFULL |
956 |
* @return new stamp on success, else zero |
957 |
*/ |
958 |
private long tryDecReaderOverflow(long s) { |
959 |
// assert (s & ABITS) >= RFULL; |
960 |
if ((s & ABITS) == RFULL) { |
961 |
if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) { |
962 |
int r; long next; |
963 |
if ((r = readerOverflow) > 0) { |
964 |
readerOverflow = r - 1; |
965 |
next = s; |
966 |
} |
967 |
else |
968 |
next = s - RUNIT; |
969 |
state = next; |
970 |
return next; |
971 |
} |
972 |
} |
973 |
else if ((ThreadLocalRandom.current().nextInt() & |
974 |
OVERFLOW_YIELD_RATE) == 0) |
975 |
Thread.yield(); |
976 |
return 0L; |
977 |
} |
978 |
|
979 |
/** |
980 |
* Wakes up the successor of h (normally whead). This is normally |
981 |
* just h.next, but may require traversal from wtail if next |
982 |
* pointers are lagging. This may fail to wake up an acquiring |
983 |
* thread when one or more have been cancelled, but the cancel |
984 |
* methods themselves provide extra safeguards to ensure liveness. |
985 |
*/ |
986 |
private void release(WNode h) { |
987 |
if (h != null) { |
988 |
WNode q; Thread w; |
989 |
U.compareAndSwapInt(h, WSTATUS, WAITING, 0); |
990 |
if ((q = h.next) == null || q.status == CANCELLED) { |
991 |
for (WNode t = wtail; t != null && t != h; t = t.prev) |
992 |
if (t.status <= 0) |
993 |
q = t; |
994 |
} |
995 |
if (q != null && (w = q.thread) != null) |
996 |
U.unpark(w); |
997 |
} |
998 |
} |
999 |
|
1000 |
/** |
1001 |
* See above for explanation. |
1002 |
* |
1003 |
* @param interruptible true if should check interrupts and if so |
1004 |
* return INTERRUPTED |
1005 |
* @param deadline if nonzero, the System.nanoTime value to timeout |
1006 |
* at (and return zero) |
1007 |
* @return next state, or INTERRUPTED |
1008 |
*/ |
1009 |
private long acquireWrite(boolean interruptible, long deadline) { |
1010 |
WNode node = null, p; |
1011 |
for (int spins = -1;;) { // spin while enqueuing |
1012 |
long m, s, ns; |
1013 |
if ((m = (s = state) & ABITS) == 0L) { |
1014 |
if (U.compareAndSwapLong(this, STATE, s, ns = s + WBIT)) |
1015 |
return ns; |
1016 |
} |
1017 |
else if (spins < 0) |
1018 |
spins = (m == WBIT && wtail == whead) ? SPINS : 0; |
1019 |
else if (spins > 0) { |
1020 |
if (ThreadLocalRandom.current().nextInt() >= 0) |
1021 |
--spins; |
1022 |
} |
1023 |
else if ((p = wtail) == null) { // initialize queue |
1024 |
WNode hd = new WNode(WMODE, null); |
1025 |
if (U.compareAndSwapObject(this, WHEAD, null, hd)) |
1026 |
wtail = hd; |
1027 |
} |
1028 |
else if (node == null) |
1029 |
node = new WNode(WMODE, p); |
1030 |
else if (node.prev != p) |
1031 |
node.prev = p; |
1032 |
else if (U.compareAndSwapObject(this, WTAIL, p, node)) { |
1033 |
p.next = node; |
1034 |
break; |
1035 |
} |
1036 |
} |
1037 |
|
1038 |
for (int spins = -1;;) { |
1039 |
WNode h, np, pp; int ps; |
1040 |
if ((h = whead) == p) { |
1041 |
if (spins < 0) |
1042 |
spins = HEAD_SPINS; |
1043 |
else if (spins < MAX_HEAD_SPINS) |
1044 |
spins <<= 1; |
1045 |
for (int k = spins;;) { // spin at head |
1046 |
long s, ns; |
1047 |
if (((s = state) & ABITS) == 0L) { |
1048 |
if (U.compareAndSwapLong(this, STATE, s, |
1049 |
ns = s + WBIT)) { |
1050 |
whead = node; |
1051 |
node.prev = null; |
1052 |
return ns; |
1053 |
} |
1054 |
} |
1055 |
else if (ThreadLocalRandom.current().nextInt() >= 0 && |
1056 |
--k <= 0) |
1057 |
break; |
1058 |
} |
1059 |
} |
1060 |
else if (h != null) { // help release stale waiters |
1061 |
WNode c; Thread w; |
1062 |
while ((c = h.cowait) != null) { |
1063 |
if (U.compareAndSwapObject(h, WCOWAIT, c, c.cowait) && |
1064 |
(w = c.thread) != null) |
1065 |
U.unpark(w); |
1066 |
} |
1067 |
} |
1068 |
if (whead == h) { |
1069 |
if ((np = node.prev) != p) { |
1070 |
if (np != null) |
1071 |
(p = np).next = node; // stale |
1072 |
} |
1073 |
else if ((ps = p.status) == 0) |
1074 |
U.compareAndSwapInt(p, WSTATUS, 0, WAITING); |
1075 |
else if (ps == CANCELLED) { |
1076 |
if ((pp = p.prev) != null) { |
1077 |
node.prev = pp; |
1078 |
pp.next = node; |
1079 |
} |
1080 |
} |
1081 |
else { |
1082 |
long time; // 0 argument to park means no timeout |
1083 |
if (deadline == 0L) |
1084 |
time = 0L; |
1085 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1086 |
return cancelWaiter(node, node, false); |
1087 |
Thread wt = Thread.currentThread(); |
1088 |
U.putObject(wt, PARKBLOCKER, this); |
1089 |
node.thread = wt; |
1090 |
if (p.status < 0 && (p != h || (state & ABITS) != 0L) && |
1091 |
whead == h && node.prev == p) |
1092 |
U.park(false, time); // emulate LockSupport.park |
1093 |
node.thread = null; |
1094 |
U.putObject(wt, PARKBLOCKER, null); |
1095 |
if (interruptible && Thread.interrupted()) |
1096 |
return cancelWaiter(node, node, true); |
1097 |
} |
1098 |
} |
1099 |
} |
1100 |
} |
1101 |
|
1102 |
/** |
1103 |
* See above for explanation. |
1104 |
* |
1105 |
* @param interruptible true if should check interrupts and if so |
1106 |
* return INTERRUPTED |
1107 |
* @param deadline if nonzero, the System.nanoTime value to timeout |
1108 |
* at (and return zero) |
1109 |
* @return next state, or INTERRUPTED |
1110 |
*/ |
1111 |
private long acquireRead(boolean interruptible, long deadline) { |
1112 |
WNode node = null, p; |
1113 |
for (int spins = -1;;) { |
1114 |
WNode h; |
1115 |
if ((h = whead) == (p = wtail)) { |
1116 |
for (long m, s, ns;;) { |
1117 |
if ((m = (s = state) & ABITS) < RFULL ? |
1118 |
U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT) : |
1119 |
(m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) |
1120 |
return ns; |
1121 |
else if (m >= WBIT) { |
1122 |
if (spins > 0) { |
1123 |
if (ThreadLocalRandom.current().nextInt() >= 0) |
1124 |
--spins; |
1125 |
} |
1126 |
else { |
1127 |
if (spins == 0) { |
1128 |
WNode nh = whead, np = wtail; |
1129 |
if ((nh == h && np == p) || (h = nh) != (p = np)) |
1130 |
break; |
1131 |
} |
1132 |
spins = SPINS; |
1133 |
} |
1134 |
} |
1135 |
} |
1136 |
} |
1137 |
if (p == null) { // initialize queue |
1138 |
WNode hd = new WNode(WMODE, null); |
1139 |
if (U.compareAndSwapObject(this, WHEAD, null, hd)) |
1140 |
wtail = hd; |
1141 |
} |
1142 |
else if (node == null) |
1143 |
node = new WNode(RMODE, p); |
1144 |
else if (h == p || p.mode != RMODE) { |
1145 |
if (node.prev != p) |
1146 |
node.prev = p; |
1147 |
else if (U.compareAndSwapObject(this, WTAIL, p, node)) { |
1148 |
p.next = node; |
1149 |
break; |
1150 |
} |
1151 |
} |
1152 |
else if (!U.compareAndSwapObject(p, WCOWAIT, |
1153 |
node.cowait = p.cowait, node)) |
1154 |
node.cowait = null; |
1155 |
else { |
1156 |
for (;;) { |
1157 |
WNode pp, c; Thread w; |
1158 |
if ((h = whead) != null && (c = h.cowait) != null && |
1159 |
U.compareAndSwapObject(h, WCOWAIT, c, c.cowait) && |
1160 |
(w = c.thread) != null) // help release |
1161 |
U.unpark(w); |
1162 |
if (h == (pp = p.prev) || h == p || pp == null) { |
1163 |
long m, s, ns; |
1164 |
do { |
1165 |
if ((m = (s = state) & ABITS) < RFULL ? |
1166 |
U.compareAndSwapLong(this, STATE, s, |
1167 |
ns = s + RUNIT) : |
1168 |
(m < WBIT && |
1169 |
(ns = tryIncReaderOverflow(s)) != 0L)) |
1170 |
return ns; |
1171 |
} while (m < WBIT); |
1172 |
} |
1173 |
if (whead == h && p.prev == pp) { |
1174 |
long time; |
1175 |
if (pp == null || h == p || p.status > 0) { |
1176 |
node = null; // throw away |
1177 |
break; |
1178 |
} |
1179 |
if (deadline == 0L) |
1180 |
time = 0L; |
1181 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1182 |
return cancelWaiter(node, p, false); |
1183 |
Thread wt = Thread.currentThread(); |
1184 |
U.putObject(wt, PARKBLOCKER, this); |
1185 |
node.thread = wt; |
1186 |
if ((h != pp || (state & ABITS) == WBIT) && |
1187 |
whead == h && p.prev == pp) |
1188 |
U.park(false, time); |
1189 |
node.thread = null; |
1190 |
U.putObject(wt, PARKBLOCKER, null); |
1191 |
if (interruptible && Thread.interrupted()) |
1192 |
return cancelWaiter(node, p, true); |
1193 |
} |
1194 |
} |
1195 |
} |
1196 |
} |
1197 |
|
1198 |
for (int spins = -1;;) { |
1199 |
WNode h, np, pp; int ps; |
1200 |
if ((h = whead) == p) { |
1201 |
if (spins < 0) |
1202 |
spins = HEAD_SPINS; |
1203 |
else if (spins < MAX_HEAD_SPINS) |
1204 |
spins <<= 1; |
1205 |
for (int k = spins;;) { // spin at head |
1206 |
long m, s, ns; |
1207 |
if ((m = (s = state) & ABITS) < RFULL ? |
1208 |
U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT) : |
1209 |
(m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) { |
1210 |
WNode c; Thread w; |
1211 |
whead = node; |
1212 |
node.prev = null; |
1213 |
while ((c = node.cowait) != null) { |
1214 |
if (U.compareAndSwapObject(node, WCOWAIT, |
1215 |
c, c.cowait) && |
1216 |
(w = c.thread) != null) |
1217 |
U.unpark(w); |
1218 |
} |
1219 |
return ns; |
1220 |
} |
1221 |
else if (m >= WBIT && |
1222 |
ThreadLocalRandom.current().nextInt() >= 0 && --k <= 0) |
1223 |
break; |
1224 |
} |
1225 |
} |
1226 |
else if (h != null) { |
1227 |
WNode c; Thread w; |
1228 |
while ((c = h.cowait) != null) { |
1229 |
if (U.compareAndSwapObject(h, WCOWAIT, c, c.cowait) && |
1230 |
(w = c.thread) != null) |
1231 |
U.unpark(w); |
1232 |
} |
1233 |
} |
1234 |
if (whead == h) { |
1235 |
if ((np = node.prev) != p) { |
1236 |
if (np != null) |
1237 |
(p = np).next = node; // stale |
1238 |
} |
1239 |
else if ((ps = p.status) == 0) |
1240 |
U.compareAndSwapInt(p, WSTATUS, 0, WAITING); |
1241 |
else if (ps == CANCELLED) { |
1242 |
if ((pp = p.prev) != null) { |
1243 |
node.prev = pp; |
1244 |
pp.next = node; |
1245 |
} |
1246 |
} |
1247 |
else { |
1248 |
long time; |
1249 |
if (deadline == 0L) |
1250 |
time = 0L; |
1251 |
else if ((time = deadline - System.nanoTime()) <= 0L) |
1252 |
return cancelWaiter(node, node, false); |
1253 |
Thread wt = Thread.currentThread(); |
1254 |
U.putObject(wt, PARKBLOCKER, this); |
1255 |
node.thread = wt; |
1256 |
if (p.status < 0 && |
1257 |
(p != h || (state & ABITS) == WBIT) && |
1258 |
whead == h && node.prev == p) |
1259 |
U.park(false, time); |
1260 |
node.thread = null; |
1261 |
U.putObject(wt, PARKBLOCKER, null); |
1262 |
if (interruptible && Thread.interrupted()) |
1263 |
return cancelWaiter(node, node, true); |
1264 |
} |
1265 |
} |
1266 |
} |
1267 |
} |
1268 |
|
1269 |
/** |
1270 |
* If node non-null, forces cancel status and unsplices it from |
1271 |
* queue if possible and wakes up any cowaiters (of the node, or |
1272 |
* group, as applicable), and in any case helps release current |
1273 |
* first waiter if lock is free. (Calling with null arguments |
1274 |
* serves as a conditional form of release, which is not currently |
1275 |
* needed but may be needed under possible future cancellation |
1276 |
* policies). This is a variant of cancellation methods in |
1277 |
* AbstractQueuedSynchronizer (see its detailed explanation in AQS |
1278 |
* internal documentation). |
1279 |
* |
1280 |
* @param node if non-null, the waiter |
1281 |
* @param group either node or the group node is cowaiting with |
1282 |
* @param interrupted if already interrupted |
1283 |
* @return INTERRUPTED if interrupted or Thread.interrupted, else zero |
1284 |
*/ |
1285 |
private long cancelWaiter(WNode node, WNode group, boolean interrupted) { |
1286 |
if (node != null && group != null) { |
1287 |
Thread w; |
1288 |
node.status = CANCELLED; |
1289 |
// unsplice cancelled nodes from group |
1290 |
for (WNode p = group, q; (q = p.cowait) != null;) { |
1291 |
if (q.status == CANCELLED) { |
1292 |
U.compareAndSwapObject(p, WCOWAIT, q, q.cowait); |
1293 |
p = group; // restart |
1294 |
} |
1295 |
else |
1296 |
p = q; |
1297 |
} |
1298 |
if (group == node) { |
1299 |
for (WNode r = group.cowait; r != null; r = r.cowait) { |
1300 |
if ((w = r.thread) != null) |
1301 |
U.unpark(w); // wake up uncancelled co-waiters |
1302 |
} |
1303 |
for (WNode pred = node.prev; pred != null; ) { // unsplice |
1304 |
WNode succ, pp; // find valid successor |
1305 |
while ((succ = node.next) == null || |
1306 |
succ.status == CANCELLED) { |
1307 |
WNode q = null; // find successor the slow way |
1308 |
for (WNode t = wtail; t != null && t != node; t = t.prev) |
1309 |
if (t.status != CANCELLED) |
1310 |
q = t; // don't link if succ cancelled |
1311 |
if (succ == q || // ensure accurate successor |
1312 |
U.compareAndSwapObject(node, WNEXT, |
1313 |
succ, succ = q)) { |
1314 |
if (succ == null && node == wtail) |
1315 |
U.compareAndSwapObject(this, WTAIL, node, pred); |
1316 |
break; |
1317 |
} |
1318 |
} |
1319 |
if (pred.next == node) // unsplice pred link |
1320 |
U.compareAndSwapObject(pred, WNEXT, node, succ); |
1321 |
if (succ != null && (w = succ.thread) != null) { |
1322 |
succ.thread = null; |
1323 |
U.unpark(w); // wake up succ to observe new pred |
1324 |
} |
1325 |
if (pred.status != CANCELLED || (pp = pred.prev) == null) |
1326 |
break; |
1327 |
node.prev = pp; // repeat if new pred wrong/cancelled |
1328 |
U.compareAndSwapObject(pp, WNEXT, pred, succ); |
1329 |
pred = pp; |
1330 |
} |
1331 |
} |
1332 |
} |
1333 |
WNode h; // Possibly release first waiter |
1334 |
while ((h = whead) != null) { |
1335 |
long s; WNode q; // similar to release() but check eligibility |
1336 |
if ((q = h.next) == null || q.status == CANCELLED) { |
1337 |
for (WNode t = wtail; t != null && t != h; t = t.prev) |
1338 |
if (t.status <= 0) |
1339 |
q = t; |
1340 |
} |
1341 |
if (h == whead) { |
1342 |
if (q != null && h.status == 0 && |
1343 |
((s = state) & ABITS) != WBIT && // waiter is eligible |
1344 |
(s == 0L || q.mode == RMODE)) |
1345 |
release(h); |
1346 |
break; |
1347 |
} |
1348 |
} |
1349 |
return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L; |
1350 |
} |
1351 |
|
1352 |
// Unsafe mechanics |
1353 |
private static final sun.misc.Unsafe U; |
1354 |
private static final long STATE; |
1355 |
private static final long WHEAD; |
1356 |
private static final long WTAIL; |
1357 |
private static final long WNEXT; |
1358 |
private static final long WSTATUS; |
1359 |
private static final long WCOWAIT; |
1360 |
private static final long PARKBLOCKER; |
1361 |
|
1362 |
static { |
1363 |
try { |
1364 |
U = getUnsafe(); |
1365 |
Class<?> k = StampedLock.class; |
1366 |
Class<?> wk = WNode.class; |
1367 |
STATE = U.objectFieldOffset |
1368 |
(k.getDeclaredField("state")); |
1369 |
WHEAD = U.objectFieldOffset |
1370 |
(k.getDeclaredField("whead")); |
1371 |
WTAIL = U.objectFieldOffset |
1372 |
(k.getDeclaredField("wtail")); |
1373 |
WSTATUS = U.objectFieldOffset |
1374 |
(wk.getDeclaredField("status")); |
1375 |
WNEXT = U.objectFieldOffset |
1376 |
(wk.getDeclaredField("next")); |
1377 |
WCOWAIT = U.objectFieldOffset |
1378 |
(wk.getDeclaredField("cowait")); |
1379 |
Class<?> tk = Thread.class; |
1380 |
PARKBLOCKER = U.objectFieldOffset |
1381 |
(tk.getDeclaredField("parkBlocker")); |
1382 |
|
1383 |
} catch (Exception e) { |
1384 |
throw new Error(e); |
1385 |
} |
1386 |
} |
1387 |
|
1388 |
/** |
1389 |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1390 |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1391 |
* into a jdk. |
1392 |
* |
1393 |
* @return a sun.misc.Unsafe |
1394 |
*/ |
1395 |
private static sun.misc.Unsafe getUnsafe() { |
1396 |
try { |
1397 |
return sun.misc.Unsafe.getUnsafe(); |
1398 |
} catch (SecurityException tryReflectionInstead) {} |
1399 |
try { |
1400 |
return java.security.AccessController.doPrivileged |
1401 |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1402 |
public sun.misc.Unsafe run() throws Exception { |
1403 |
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; |
1404 |
for (java.lang.reflect.Field f : k.getDeclaredFields()) { |
1405 |
f.setAccessible(true); |
1406 |
Object x = f.get(null); |
1407 |
if (k.isInstance(x)) |
1408 |
return k.cast(x); |
1409 |
} |
1410 |
throw new NoSuchFieldError("the Unsafe"); |
1411 |
}}); |
1412 |
} catch (java.security.PrivilegedActionException e) { |
1413 |
throw new RuntimeException("Could not initialize intrinsics", |
1414 |
e.getCause()); |
1415 |
} |
1416 |
} |
1417 |
} |