ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.2
Committed: Fri Oct 12 16:22:40 2012 UTC (11 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.1: +3 -3 lines
Log Message:
whitespace

File Contents

# Content
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.ThreadLocalRandom;
10 import java.util.concurrent.TimeUnit;
11
12 /**
13 * A capability-based lock with three modes for controlling read/write
14 * access. The state of a StampedLock consists of a version and
15 * mode. Lock acquisition methods return a stamp that represents and
16 * controls access with respect to a lock state; "try" versions of
17 * these methods may instead return the special value zero to
18 * represent failure to acquire access. Lock release and conversion
19 * methods require stamps as arguments, and fail if they do not match
20 * the state of the lock. The three modes are:
21 *
22 * <ul>
23 *
24 * <li><b>Writing.</b> Method {@link #writeLock} possibly blocks
25 * waiting for exclusive access, returning a stamp that can be used
26 * in method {@link #unlockWrite} to release the lock. Untimed and
27 * timed versions of {@code tryWriteLock} are also provided. When
28 * the lock is held in write mode, no read locks may be obtained,
29 * and all observer validations will fail. </li>
30 *
31 * <li><b>Reading.</b> Method {@link #readLock} possibly blocks
32 * waiting for non-exclusive access, returning a stamp that can be
33 * used in method {@link #unlockRead} to release the lock. Untimed
34 * and timed versions of {@code tryReadLock} are also provided. </li>
35 *
36 * <li><b>Optimistic Reading.</b> Method {@link #tryOptimisticRead}
37 * returns a non-zero stamp only if the lock is not currently held
38 * in write mode. Method {@link #validate} returns true if the lock
39 * has not since been acquired in write mode. This mode can be
40 * thought of as an extremely weak version of a read-lock, that can
41 * be broken by a writer at any time. The use of optimistic mode
42 * for short read-only code segments often reduces contention and
43 * improves throughput. However, its use is inherently fragile.
44 * Optimistic read sections should only read fields and hold them in
45 * local variables for later use after validation. Fields read while
46 * in optimistic mode may be wildly inconsistent, so usage applies
47 * only when you are familiar enough with data representations to
48 * check consistency and/or repeatedly invoke method {@code
49 * validate()}. For example, such steps are typically required when
50 * first reading an object or array reference, and then accessing
51 * one of its fields, elements or methods. </li>
52 *
53 * </ul>
54 *
55 * <p>This class also supports methods that conditionally provide
56 * conversions across the three modes. For example, method {@link
57 * #tryConvertToWriteLock} attempts to "upgrade" a mode, returning
58 * valid write stamp if (1) already in writing mode (2) in reading
59 * mode and there are no other readers or (3) in optimistic mode and
60 * the lock is available. The forms of these methods are designed to
61 * help reduce some of the code bloat that otherwise occurs in
62 * retry-based designs.
63 *
64 * <p>StampedLocks are designed for use in a different (and generally
65 * narrower) range of contexts than most other locks: They are not
66 * reentrant, so locked bodies should not call other unknown methods
67 * that may try to re-acquire locks (although you may pass a stamp to
68 * other methods that can use or convert it). Unvalidated optimistic
69 * read sections should further not call methods that are not known to
70 * tolerate potential inconsistencies. Stamps use finite
71 * representations, and are not cryptographically secure (i.e., a
72 * valid stamp may be guessable). Stamp values may recycle after (no
73 * sooner than) one year of continuous operation. A stamp held without
74 * use or validation for longer than this period may fail to validate
75 * correctly. StampedLocks are serializable, but always deserialize
76 * into initial unlocked state, so they are not useful for remote
77 * locking.
78 *
79 * <p>The scheduling policy of StampedLock does not consistently prefer
80 * readers over writers or vice versa.
81 *
82 * <p><b>Sample Usage.</b> The following illustrates some usage idioms
83 * in a class that maintains simple two-dimensional points. The sample
84 * code illustrates some try/catch conventions even though they are
85 * not strictly needed here because no exceptions can occur in their
86 * bodies.<br>
87 *
88 * <pre>{@code
89 * class Point {
90 * private volatile double x, y;
91 * private final StampedLock sl = new StampedLock();
92 *
93 * void move(double deltaX, double deltaY) { // an exclusively locked method
94 * long stamp = sl.writeLock();
95 * try {
96 * x += deltaX;
97 * y += deltaY;
98 * } finally {
99 * sl.unlockWrite(stamp);
100 * }
101 * }
102 *
103 * double distanceFromOriginV1() { // A read-only method
104 * long stamp;
105 * if ((stamp = sl.tryOptimisticRead()) != 0L) { // optimistic
106 * double currentX = x;
107 * double currentY = y;
108 * if (sl.validate(stamp))
109 * return Math.sqrt(currentX * currentX + currentY * currentY);
110 * }
111 * stamp = sl.readLock(); // fall back to read lock
112 * try {
113 * double currentX = x;
114 * double currentY = y;
115 * return Math.sqrt(currentX * currentX + currentY * currentY);
116 * } finally {
117 * sl.unlockRead(stamp);
118 * }
119 * }
120 *
121 * double distanceFromOriginV2() { // combines code paths
122 * for (long stamp = sl.optimisticRead(); ; stamp = sl.readLock()) {
123 * double currentX, currentY;
124 * try {
125 * currentX = x;
126 * currentY = y;
127 * } finally {
128 * if (sl.tryConvertToOptimisticRead(stamp) != 0L) // unlock or validate
129 * return Math.sqrt(currentX * currentX + currentY * currentY);
130 * }
131 * }
132 * }
133 *
134 * void moveIfAtOrigin(double newX, double newY) { // upgrade
135 * // Could instead start with optimistic, not read mode
136 * long stamp = sl.readLock();
137 * try {
138 * while (x == 0.0 && y == 0.0) {
139 * long ws = tryConvertToWriteLock(stamp);
140 * if (ws != 0L) {
141 * stamp = ws;
142 * x = newX;
143 * y = newY;
144 * break;
145 * }
146 * else {
147 * sl.unlockRead(stamp);
148 * stamp = sl.writeLock();
149 * }
150 * }
151 * } finally {
152 * sl.unlock(stamp);
153 * }
154 * }
155 * }}</pre>
156 *
157 * @since 1.8
158 * @author Doug Lea
159 */
160 public class StampedLock implements java.io.Serializable {
161 /*
162 * Algorithmic notes:
163 *
164 * The design employs elements of Sequence locks
165 * (as used in linux kernels; see Lameter's
166 * http://www.lameter.com/gelato2005.pdf
167 * and elsewhere; see
168 * Boehm's http://www.hpl.hp.com/techreports/2012/HPL-2012-68.html)
169 * Ordered RW locks (see Shirako et al
170 * http://dl.acm.org/citation.cfm?id=2312015)
171 * and Phase-Fair locks (see Brandenburg & Anderson, especially
172 * http://www.cs.unc.edu/~bbb/diss/).
173 *
174 * Conceptually, the primary state of the lock includes a sequence
175 * number that is odd when write-locked and even otherwise.
176 * However, this is offset by a reader count that is non-zero when
177 * read-locked. The read count is ignored when validating
178 * "optimistic" seqlock-reader-style stamps. Because we must use
179 * a small finite number of bits (currently 7) for readers, a
180 * supplementatry reader overflow word is used when then number of
181 * readers exceeds the count field. We do this by treating the max
182 * reader count value (RBITS) as a spinlock protecting overflow
183 * updates.
184 *
185 * Waiting readers and writers use different queues. The writer
186 * queue is a modified form of CLH lock. (For discussion of CLH,
187 * see the internal documentation of AbstractQueuedSynchronizer.)
188 * The reader "queue" is a form of Treiber stack, that supports
189 * simpler/faster operations because order within a queue doesn't
190 * matter and all are signalled at once. However the sequence of
191 * threads within the queue vs the current stamp does matter (see
192 * Shirako et al) so each carries its incoming stamp value.
193 * Waiting writers never need to track sequence values, so they
194 * don't.
195 *
196 * These queue mechanics hardwire the scheduling policy. Ignoring
197 * trylocks, cancellation, and spinning, they implement Phase-Fair
198 * preferences:
199 * 1. Unlocked writers prefer to signal waiting readers
200 * 2. Fully unlocked readers prefer to signal waiting writers
201 * 3. When read-locked and a waiting writer exists, the writer
202 * is preferred to incoming readers
203 *
204 * These rules apply to threads actually queued. All tryLock forms
205 * opportunistically try to acquire locks regardless of preference
206 * rules, and so may "barge" their way in. Additionally, initial
207 * phases of the await* methods (invoked from readLock() and
208 * writeLock()) use controlled spins that have similar effect.
209 * Phase-fair preferences may also be broken on cancellations due
210 * to timeouts and interrupts. Rule #3 (incoming readers when a
211 * waiting writer) is approximated with varying precision in
212 * different contexts -- some checks do not account for
213 * in-progress spins/signals, and others do not account for
214 * cancellations.
215 *
216 * As noted in Boehm's paper (above), sequence validation (mainly
217 * method validate()) requires stricter ordering rules than apply
218 * to normal volatile reads (of "state"). In the absence of (but
219 * continual hope for) explicit JVM support of intrinsics with
220 * double-sided reordering prohibition, or corresponding fence
221 * intrinsics, we for now uncomfortably rely on the fact that the
222 * Unsafe.getXVolatile intrinsic must have this property
223 * (syntactic volatile reads do not) for internal purposes anyway,
224 * even though it is not documented.
225 *
226 * The memory layout keeps lock state and queue pointers together
227 * (normally on the same cache line). This usually works well for
228 * read-mostly loads. In most other cases, the natural tendency of
229 * adaptive-spin CLH locks to reduce memory contention lessens
230 * motivation to further spread out contended locations, but might
231 * be subject to future improvements.
232 */
233
234 /** Number of processors, for spin control */
235 private static final int NCPU = Runtime.getRuntime().availableProcessors();
236
237 /** Maximum number of retries before blocking on acquisition */
238 private static final int SPINS = NCPU > 1 ? 1 << 6 : 1;
239
240 /** Maximum number of retries before re-blocking on write lock */
241 private static final int MAX_HEAD_SPINS = NCPU > 1 ? 1 << 12 : 1;
242
243 /** The period for yielding when waiting for overflow spinlock */
244 private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1
245
246 /** The number of bits to use for reader count before overflowing */
247 private static final int LG_READERS = 7;
248
249 // Values for lock state and stamp operations
250 private static final long RUNIT = 1L;
251 private static final long WBIT = 1L << LG_READERS;
252 private static final long RBITS = WBIT - 1L;
253 private static final long RFULL = RBITS - 1L;
254 private static final long ABITS = RBITS | WBIT;
255 private static final long SBITS = ~RBITS; // note overlap with ABITS
256
257 // Initial value for lock state; avoid failure value zero
258 private static final long ORIGIN = WBIT << 1;
259
260 // Special value from cancelled await methods so caller can throw IE
261 private static final long INTERRUPTED = 1L;
262
263 // Values for writer status; order matters
264 private static final int WAITING = -1;
265 private static final int CANCELLED = 1;
266
267 /** Wait nodes for readers */
268 static final class RNode {
269 final long seq; // stamp value upon enqueue
270 volatile Thread waiter; // null if no longer waiting
271 volatile RNode next;
272 RNode(long s, Thread w) { seq = s; waiter = w; }
273 }
274
275 /** Wait nodes for writers */
276 static final class WNode {
277 volatile int status; // 0, WAITING, or CANCELLED
278 volatile WNode prev;
279 volatile WNode next;
280 volatile Thread thread;
281 WNode(Thread t, WNode p) { thread = t; prev = p; }
282 }
283
284 /** Head of writer CLH queue */
285 private transient volatile WNode whead;
286 /** Tail (last) of writer CLH queue */
287 private transient volatile WNode wtail;
288 /** Head of read queue */
289 private transient volatile RNode rhead;
290 /** The state of the lock -- high bits hold sequence, low bits read count */
291 private transient volatile long state;
292 /** extra reader count when state read count saturated */
293 private transient int readerOverflow;
294
295 /**
296 * Creates a new lock initially in unlocked state.
297 */
298 public StampedLock() {
299 state = ORIGIN;
300 }
301
302 /**
303 * Exclusively acquires the lock, blocking if necessary
304 * until available.
305 *
306 * @return a stamp that can be used to unlock or convert mode.
307 */
308 public long writeLock() {
309 long s, next;
310 if (((s = state) & ABITS) == 0L &&
311 U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
312 return next;
313 return awaitWrite(false, 0L);
314 }
315
316 /**
317 * Exclusively acquires the lock if it is immediately available.
318 *
319 * @return a stamp that can be used to unlock or convert mode,
320 * or zero if the lock is not available.
321 */
322 public long tryWriteLock() {
323 long s, next;
324 if (((s = state) & ABITS) == 0L &&
325 U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
326 return next;
327 return 0L;
328 }
329
330 /**
331 * Exclusively acquires the lock if it is available within the
332 * given time and the current thread has not been interrupted
333 *
334 * @return a stamp that can be used to unlock or convert mode,
335 * or zero if the lock is not available.
336 * @throws InterruptedException if the current thread is interrupted
337 * before acquiring the lock.
338 */
339 public long tryWriteLock(long time, TimeUnit unit)
340 throws InterruptedException {
341 long nanos = unit.toNanos(time);
342 if (!Thread.interrupted()) {
343 long s, next, deadline;
344 if (((s = state) & ABITS) == 0L &&
345 U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
346 return next;
347 if (nanos <= 0L)
348 return 0L;
349 if ((deadline = System.nanoTime() + nanos) == 0L)
350 deadline = 1L;
351 if ((next = awaitWrite(true, deadline)) != INTERRUPTED)
352 return next;
353 }
354 throw new InterruptedException();
355 }
356
357 /**
358 * Exclusively acquires the lock, blocking if necessary
359 * until available or the current thread is interrupted.
360 *
361 * @return a stamp that can be used to unlock or convert mode.
362 * @throws InterruptedException if the current thread is interrupted
363 * before acquiring the lock.
364 */
365 public long writeLockInterruptibly() throws InterruptedException {
366 if (!Thread.interrupted()) {
367 long s, next;
368 if (((s = state) & ABITS) == 0L &&
369 U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
370 return next;
371 if ((next = awaitWrite(true, 0L)) != INTERRUPTED)
372 return next;
373 }
374 throw new InterruptedException();
375 }
376
377 /**
378 * Non-exclusively acquires the lock, blocking if necessary
379 * until available.
380 *
381 * @return a stamp that can be used to unlock or convert mode.
382 */
383 public long readLock() {
384 for (;;) {
385 long s, m, next;
386 if ((m = (s = state) & ABITS) == 0L ||
387 (m < WBIT && whead == wtail)) {
388 if (m < RFULL) {
389 if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
390 return next;
391 }
392 else if ((next = tryIncReaderOverflow(s)) != 0L)
393 return next;
394 }
395 else
396 return awaitRead(s, false, 0L);
397 }
398 }
399
400 /**
401 * Non-exclusively acquires the lock if it is immediately available.
402 *
403 * @return a stamp that can be used to unlock or convert mode,
404 * or zero if the lock is not available.
405 */
406 public long tryReadLock() {
407 for (;;) {
408 long s, m, next;
409 if ((m = (s = state) & ABITS) == WBIT)
410 return 0L;
411 else if (m < RFULL) {
412 if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
413 return next;
414 }
415 else if ((next = tryIncReaderOverflow(s)) != 0L)
416 return next;
417 }
418 }
419
420 /**
421 * Non-exclusively acquires the lock if it is available within the
422 * given time and the current thread has not been interrupted
423 *
424 * @return a stamp that can be used to unlock or convert mode,
425 * or zero if the lock is not available.
426 * @throws InterruptedException if the current thread is interrupted
427 * before acquiring the lock.
428 */
429 public long tryReadLock(long time, TimeUnit unit)
430 throws InterruptedException {
431 long nanos = unit.toNanos(time);
432 if (!Thread.interrupted()) {
433 for (;;) {
434 long s, m, next, deadline;
435 if ((m = (s = state) & ABITS) == WBIT ||
436 (m != 0L && whead != wtail)) {
437 if (nanos <= 0L)
438 return 0L;
439 if ((deadline = System.nanoTime() + nanos) == 0L)
440 deadline = 1L;
441 if ((next = awaitRead(s, true, deadline)) != INTERRUPTED)
442 return next;
443 break;
444 }
445 else if (m < RFULL) {
446 if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
447 return next;
448 }
449 else if ((next = tryIncReaderOverflow(s)) != 0L)
450 return next;
451 }
452 }
453 throw new InterruptedException();
454 }
455
456 /**
457 * Non-exclusively acquires the lock, blocking if necessary
458 * until available or the current thread is interrupted.
459 *
460 * @return a stamp that can be used to unlock or convert mode.
461 * @throws InterruptedException if the current thread is interrupted
462 * before acquiring the lock.
463 */
464 public long readLockInterruptibly() throws InterruptedException {
465 if (!Thread.interrupted()) {
466 for (;;) {
467 long s, next, m;
468 if ((m = (s = state) & ABITS) == WBIT ||
469 (m != 0L && whead != wtail)) {
470 if ((next = awaitRead(s, true, 0L)) != INTERRUPTED)
471 return next;
472 break;
473 }
474 else if (m < RFULL) {
475 if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
476 return next;
477 }
478 else if ((next = tryIncReaderOverflow(s)) != 0L)
479 return next;
480 }
481 }
482 throw new InterruptedException();
483 }
484
485 /**
486 * Returns a stamp that can later be validated, or zero
487 * if exclusively locked.
488 *
489 * @return a stamp, or zero if exclusively locked
490 */
491 public long tryOptimisticRead() {
492 long s;
493 return (((s = state) & WBIT) == 0L) ? (s & SBITS) : 0L;
494 }
495
496 /**
497 * Returns true if the lock has not been exclusively held since
498 * issuance of the given stamp. Always returns false if the stamp
499 * is zero. Always returns true if the stamp represents a
500 * currently held lock.
501 *
502 * @return true if the lock has not been exclusively held since
503 * issuance of the given stamp; else false
504 */
505 public boolean validate(long stamp) {
506 return (stamp & SBITS) == (U.getLongVolatile(this, STATE) & SBITS);
507 }
508
509 /**
510 * If the lock state matches the given stamp, releases the
511 * exclusive lock.
512 *
513 * @param stamp a stamp returned by a write-lock operation
514 * @throws IllegalMonitorStateException if the stamp does
515 * not match the current state of this lock.
516 */
517 public void unlockWrite(long stamp) {
518 if (state != stamp || (stamp & WBIT) == 0L)
519 throw new IllegalMonitorStateException();
520 state = (stamp += WBIT) == 0L ? ORIGIN : stamp;
521 readerPrefSignal();
522 }
523
524 /**
525 * If the lock state matches the given stamp, releases
526 * non-exclusive lock.
527 *
528 * @param stamp a stamp returned by a read-lock operation
529 * @throws IllegalMonitorStateException if the stamp does
530 * not match the current state of this lock.
531 */
532 public void unlockRead(long stamp) {
533 long s, m;
534 if ((stamp & RBITS) != 0L) {
535 while (((s = state) & SBITS) == (stamp & SBITS)) {
536 if ((m = s & ABITS) == 0L)
537 break;
538 else if (m < RFULL) {
539 if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
540 if (m == RUNIT)
541 writerPrefSignal();
542 return;
543 }
544 }
545 else if (m >= WBIT)
546 break;
547 else if (tryDecReaderOverflow(s) != 0L)
548 return;
549 }
550 }
551 throw new IllegalMonitorStateException();
552 }
553
554 /**
555 * If the lock state matches the given stamp, releases the
556 * corresponding mode of the lock.
557 *
558 * @param stamp a stamp returned by a lock operation
559 * @throws IllegalMonitorStateException if the stamp does
560 * not match the current state of this lock.
561 */
562 public void unlock(long stamp) {
563 long a = stamp & ABITS, m, s;
564 while (((s = state) & SBITS) == (stamp & SBITS)) {
565 if ((m = s & ABITS) == 0L)
566 break;
567 else if (m == WBIT) {
568 if (a != m)
569 break;
570 state = (s += WBIT) == 0L ? ORIGIN : s;
571 readerPrefSignal();
572 return;
573 }
574 else if (a == 0L || a >= WBIT)
575 break;
576 else if (m < RFULL) {
577 if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
578 if (m == RUNIT)
579 writerPrefSignal();
580 return;
581 }
582 }
583 else if (tryDecReaderOverflow(s) != 0L)
584 return;
585 }
586 throw new IllegalMonitorStateException();
587 }
588
589 /**
590 * If the lock state matches the given stamp then performs one of
591 * the following actions. If the stamp represents holding a write
592 * lock, returns it. Or, if a read lock, if the write lock is
593 * available, releases the read and returns a write stamp. Or, if
594 * an optimistic read, returns a write stamp only if immediately
595 * available. This method returns zero in all other cases.
596 *
597 * @param stamp a stamp
598 * @return a valid write stamp, or zero on failure
599 */
600 public long tryConvertToWriteLock(long stamp) {
601 long a = stamp & ABITS, m, s, next;
602 while (((s = state) & SBITS) == (stamp & SBITS)) {
603 if ((m = s & ABITS) == 0L) {
604 if (a != 0L)
605 break;
606 if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
607 return next;
608 }
609 else if (m == WBIT) {
610 if (a != m)
611 break;
612 return stamp;
613 }
614 else if (m == RUNIT && a != 0L && a < WBIT) {
615 if (U.compareAndSwapLong(this, STATE, s,
616 next = s - RUNIT + WBIT))
617 return next;
618 }
619 else
620 break;
621 }
622 return 0L;
623 }
624
625 /**
626 * If the lock state matches the given stamp then performs one of
627 * the following actions. If the stamp represents holding a write
628 * lock, releases it and obtains a read lock. Or, if a read lock,
629 * returns it. Or, if an optimistic read, acquires a read lock and
630 * returns a read stamp only if immediately available. This method
631 * returns zero in all other cases.
632 *
633 * @param stamp a stamp
634 * @return a valid read stamp, or zero on failure
635 */
636 public long tryConvertToReadLock(long stamp) {
637 long a = stamp & ABITS, m, s, next;
638 while (((s = state) & SBITS) == (stamp & SBITS)) {
639 if ((m = s & ABITS) == 0L) {
640 if (a != 0L)
641 break;
642 else if (m < RFULL) {
643 if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
644 return next;
645 }
646 else if ((next = tryIncReaderOverflow(s)) != 0L)
647 return next;
648 }
649 else if (m == WBIT) {
650 if (a != m)
651 break;
652 next = state = s + (WBIT + RUNIT);
653 readerPrefSignal();
654 return next;
655 }
656 else if (a != 0L && a < WBIT)
657 return stamp;
658 else
659 break;
660 }
661 return 0L;
662 }
663
664 /**
665 * If the lock state matches the given stamp then, if the stamp
666 * represents holding a lock, releases it and returns an
667 * observation stamp. Or, if an optimistic read, returns it if
668 * validated. This method returns zero in all other cases, and so
669 * may be useful as a form of "tryUnlock".
670 *
671 * @param stamp a stamp
672 * @return a valid optimistic read stamp, or zero on failure
673 */
674 public long tryConvertToOptimisticRead(long stamp) {
675 long a = stamp & ABITS, m, s, next;
676 while (((s = U.getLongVolatile(this, STATE)) &
677 SBITS) == (stamp & SBITS)) {
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 next = state = (s += WBIT) == 0L ? ORIGIN : s;
687 readerPrefSignal();
688 return next;
689 }
690 else if (a == 0L || a >= WBIT)
691 break;
692 else if (m < RFULL) {
693 if (U.compareAndSwapLong(this, STATE, s, next = s - RUNIT)) {
694 if (m == RUNIT)
695 writerPrefSignal();
696 return next & SBITS;
697 }
698 }
699 else if ((next = tryDecReaderOverflow(s)) != 0L)
700 return next & SBITS;
701 }
702 return 0L;
703 }
704
705 /**
706 * Releases the write lock if it is held, without requiring a
707 * stamp value. This method may be useful for recovery after
708 * errors.
709 *
710 * @return true if the lock was held, else false.
711 */
712 public boolean tryUnlockWrite() {
713 long s;
714 if (((s = state) & WBIT) != 0L) {
715 state = (s += WBIT) == 0L ? ORIGIN : s;
716 readerPrefSignal();
717 return true;
718 }
719 return false;
720 }
721
722 /**
723 * Releases one hold of the read lock if it is held, without
724 * requiring a stamp value. This method may be useful for recovery
725 * after errors.
726 *
727 * @return true if the read lock was held, else false.
728 */
729 public boolean tryUnlockRead() {
730 long s, m;
731 while ((m = (s = state) & ABITS) != 0L && m < WBIT) {
732 if (m < RFULL) {
733 if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
734 if (m == RUNIT)
735 writerPrefSignal();
736 return true;
737 }
738 }
739 else if (tryDecReaderOverflow(s) != 0L)
740 return true;
741 }
742 return false;
743 }
744
745 /**
746 * Returns true if the lock is currently held exclusively.
747 *
748 * @return true if the lock is currently held exclusively
749 */
750 public boolean isWriteLocked() {
751 return (state & WBIT) != 0L;
752 }
753
754 /**
755 * Returns true if the lock is currently held non-exclusively.
756 *
757 * @return true if the lock is currently held non-exclusively
758 */
759 public boolean isReadLocked() {
760 long m;
761 return (m = state & ABITS) > 0L && m < WBIT;
762 }
763
764 private void readObject(java.io.ObjectInputStream s)
765 throws java.io.IOException, ClassNotFoundException {
766 s.defaultReadObject();
767 state = ORIGIN; // reset to unlocked state
768 }
769
770 // internals
771
772 /**
773 * Tries to increment readerOverflow by first setting state
774 * access bits value to RBITS, indicating hold of spinlock,
775 * then updating, then releasing.
776 * @param stamp, assumed that (stamp & ABITS) >= RFULL
777 * @return new stamp on success, else zero
778 */
779 private long tryIncReaderOverflow(long s) {
780 if ((s & ABITS) == RFULL) {
781 if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
782 ++readerOverflow;
783 state = s;
784 return s;
785 }
786 }
787 else if ((ThreadLocalRandom.current().nextInt() &
788 OVERFLOW_YIELD_RATE) == 0)
789 Thread.yield();
790 return 0L;
791 }
792
793 /**
794 * Tries to decrement readerOverflow.
795 * @param stamp, assumed that (stamp & ABITS) >= RFULL
796 * @return new stamp on success, else zero
797 */
798 private long tryDecReaderOverflow(long s) {
799 if ((s & ABITS) == RFULL) {
800 if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
801 int r; long next;
802 if ((r = readerOverflow) > 0) {
803 readerOverflow = r - 1;
804 next = s;
805 }
806 else
807 next = s - RUNIT;
808 state = next;
809 return next;
810 }
811 }
812 else if ((ThreadLocalRandom.current().nextInt() &
813 OVERFLOW_YIELD_RATE) == 0)
814 Thread.yield();
815 return 0L;
816 }
817
818 /*
819 * The two versions of signal implement the phase-fair policy.
820 * They include almost the same code, but repacked in different
821 * ways. Integrating the policy with the mechanics eliminates
822 * state rechecks that would be needed with separate reader and
823 * writer signal methods. Both methods assume that they are
824 * called when the lock is last known to be available, and
825 * continue until the lock is unavailable, or at least one thread
826 * is signalled, or there are no more waiting threads. Signalling
827 * a reader entails popping (CASing) from rhead and unparking
828 * unless the thread already cancelled (indicated by a null waiter
829 * field). Signalling a writer requires finding the first node,
830 * i.e., the successor of whead. This is normally just head.next,
831 * but may require traversal from wtail if next pointers are
832 * lagging. These methods may fail to wake up an acquiring thread
833 * when one or more have been cancelled, but the cancel methods
834 * themselves provide extra safeguards to ensure liveness.
835 */
836
837 private void readerPrefSignal() {
838 boolean readers = false;
839 RNode p; WNode h, q; long s; Thread w;
840 while ((p = rhead) != null) {
841 if (((s = state) & WBIT) != 0L)
842 return;
843 if (p.seq == (s & SBITS))
844 break;
845 readers = true;
846 if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
847 (w = p.waiter) != null &&
848 U.compareAndSwapObject(p, WAITER, w, null))
849 U.unpark(w);
850 }
851 if (!readers && (state & ABITS) == 0L &&
852 (h = whead) != null && h.status != 0) {
853 U.compareAndSwapInt(h, STATUS, WAITING, 0);
854 if ((q = h.next) == null || q.status == CANCELLED) {
855 q = null;
856 for (WNode t = wtail; t != null && t != h; t = t.prev)
857 if (t.status <= 0)
858 q = t;
859 }
860 if (q != null && (w = q.thread) != null)
861 U.unpark(w);
862 }
863 }
864
865 private void writerPrefSignal() {
866 RNode p; WNode h, q; long s; Thread w;
867 if ((h = whead) != null && h.status != 0) {
868 U.compareAndSwapInt(h, STATUS, WAITING, 0);
869 if ((q = h.next) == null || q.status == CANCELLED) {
870 q = null;
871 for (WNode t = wtail; t != null && t != h; t = t.prev)
872 if (t.status <= 0)
873 q = t;
874 }
875 if (q != null && (w = q.thread) != null)
876 U.unpark(w);
877 }
878 else {
879 while ((p = rhead) != null && ((s = state) & WBIT) == 0L &&
880 p.seq != (s & SBITS)) {
881 if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
882 (w = p.waiter) != null &&
883 U.compareAndSwapObject(p, WAITER, w, null))
884 U.unpark(w);
885 }
886 }
887 }
888
889 /**
890 * RNG for local spins. The first call from await{Read,Write}
891 * produces a thread-local value. Unless zero, subsequent calls
892 * use an xorShift to further reduce memory traffic. Both await
893 * methods use a similar spin strategy: If associated queue
894 * appears to be empty, then the thread spin-waits up to SPINS
895 * times before enqueing, and then, if the first thread to be
896 * enqueued, spins again up to SPINS times before blocking. If,
897 * upon wakening it fails to obtain lock, and is still (or
898 * becomes) the first waiting thread (which indicates that some
899 * other thread barged and obtained lock), it escalates spins (up
900 * to MAX_HEAD_SPINS) to reduce the likelihood of continually
901 * losing to barging threads.
902 */
903 private static int nextRandom(int r) {
904 if (r == 0)
905 return ThreadLocalRandom.current().nextInt();
906 r ^= r << 1; // xorshift
907 r ^= r >>> 3;
908 r ^= r << 10;
909 return r;
910 }
911
912 /**
913 * Possibly spins trying to obtain write lock, then enqueues and
914 * blocks while not head of write queue or cannot aquire lock,
915 * possibly spinning when at head; cancelling on timeout or
916 * interrupt.
917 *
918 * @param interruptible true if should check interrupts and if so
919 * return INTERRUPTED
920 * @param deadline if nonzero, the System.nanoTime value to timeout
921 * at (and return zero).
922 */
923 private long awaitWrite(boolean interruptible, long deadline) {
924 WNode node = null;
925 for (int r = 0, spins = -1;;) {
926 WNode p; long s, next;
927 if (((s = state) & ABITS) == 0L) {
928 if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
929 return next;
930 }
931 else if (spins < 0)
932 spins = whead == wtail ? SPINS : 0;
933 else if (spins > 0) {
934 if ((r = nextRandom(r)) >= 0)
935 --spins;
936 }
937 else if ((p = wtail) == null) { // initialize queue
938 if (U.compareAndSwapObject(this, WHEAD, null,
939 new WNode(null, null)))
940 wtail = whead;
941 }
942 else if (node == null)
943 node = new WNode(Thread.currentThread(), p);
944 else if (node.prev != p)
945 node.prev = p;
946 else if (U.compareAndSwapObject(this, WTAIL, p, node)) {
947 p.next = node;
948 for (int headSpins = SPINS;;) {
949 WNode np; int ps;
950 if ((np = node.prev) != p && np != null)
951 (p = np).next = node; // stale
952 if (p == whead) {
953 for (int k = headSpins;;) {
954 if (((s = state) & ABITS) == 0L) {
955 if (U.compareAndSwapLong(this, STATE,
956 s, next = s + WBIT)) {
957 whead = node;
958 node.thread = null;
959 node.prev = null;
960 return next;
961 }
962 break;
963 }
964 if ((r = nextRandom(r)) >= 0 && --k <= 0)
965 break;
966 }
967 if (headSpins < MAX_HEAD_SPINS)
968 headSpins <<= 1;
969 }
970 if ((ps = p.status) == 0)
971 U.compareAndSwapInt(p, STATUS, 0, WAITING);
972 else if (ps == CANCELLED)
973 node.prev = p.prev;
974 else {
975 long time; // 0 argument to park means no timeout
976 if (deadline == 0L)
977 time = 0L;
978 else if ((time = deadline - System.nanoTime()) <= 0L)
979 return cancelWriter(node, false);
980 if (node.prev == p && p.status == WAITING &&
981 (p != whead || (state & WBIT) != 0L)) { // recheck
982 U.park(false, time);
983 if (interruptible && Thread.interrupted())
984 return cancelWriter(node, true);
985 }
986 }
987 }
988 }
989 }
990 }
991
992 /**
993 * If node non-null, forces cancel status and unsplices from queue
994 * if possible. This is a streamlined variant of cancellation
995 * methods in AbstractQueuedSynchronizer that includes a detailed
996 * explanation.
997 */
998 private long cancelWriter(WNode node, boolean interrupted) {
999 WNode pred;
1000 if (node != null && (pred = node.prev) != null) {
1001 WNode pp;
1002 node.thread = null;
1003 while (pred.status == CANCELLED && (pp = pred.prev) != null)
1004 pred = node.prev = pp;
1005 WNode predNext = pred.next;
1006 node.status = CANCELLED;
1007 if (predNext != null) {
1008 Thread w = null;
1009 WNode succ = node.next;
1010 while (succ != null && succ.status == CANCELLED)
1011 succ = succ.next;
1012 if (succ != null)
1013 w = succ.thread;
1014 else if (node == wtail)
1015 U.compareAndSwapObject(this, WTAIL, node, pred);
1016 U.compareAndSwapObject(pred, WNEXT, predNext, succ);
1017 if (w != null)
1018 U.unpark(w);
1019 }
1020 }
1021 writerPrefSignal();
1022 return (interrupted || Thread.interrupted())? INTERRUPTED : 0L;
1023 }
1024
1025 /*
1026 * Waits for read lock or timeout or interrupt. The form of
1027 * awaitRead differs from awaitWrite mainly because it must
1028 * restart (with a new wait node) if the thread was unqueued and
1029 * unparked but could not the obtain lock. We also need to help
1030 * with preference rules by not trying to acquire the lock before
1031 * enqueuing if there is a known waiting writer, but also helping
1032 * to release those threads that are still queued from the last
1033 * release.
1034 */
1035 private long awaitRead(long stamp, boolean interruptible, long deadline) {
1036 long seq = stamp & SBITS;
1037 RNode node = null;
1038 boolean queued = false;
1039 for (int r = 0, headSpins = SPINS, spins = -1;;) {
1040 long s, m, next; RNode p; WNode wh; Thread w;
1041 if ((m = (s = state) & ABITS) != WBIT &&
1042 ((s & SBITS) != seq || (wh = whead) == null ||
1043 wh.status == 0)) {
1044 if (m < RFULL ?
1045 U.compareAndSwapLong(this, STATE, s, next = s + RUNIT) :
1046 (next = tryIncReaderOverflow(s)) != 0L) {
1047 if (node != null && (w = node.waiter) != null)
1048 U.compareAndSwapObject(node, WAITER, w, null);
1049 if ((p = rhead) != null && (s & SBITS) != p.seq &&
1050 U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1051 (w = p.waiter) != null &&
1052 U.compareAndSwapObject(p, WAITER, w, null))
1053 U.unpark(w); // help signal other waiters
1054 return next;
1055 }
1056 }
1057 else if (m != WBIT && (p = rhead) != null &&
1058 (s & SBITS) != p.seq) { // help release old readers
1059 if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1060 (w = p.waiter) != null &&
1061 U.compareAndSwapObject(p, WAITER, w, null))
1062 U.unpark(w);
1063 }
1064 else if (queued && node != null && node.waiter == null) {
1065 node = null; // restart
1066 queued = false;
1067 spins = -1;
1068 }
1069 else if (spins < 0) {
1070 if (rhead != node)
1071 spins = 0;
1072 else if ((spins = headSpins) < MAX_HEAD_SPINS && node != null)
1073 headSpins <<= 1;
1074 }
1075 else if (spins > 0) {
1076 if ((r = nextRandom(r)) >= 0)
1077 --spins;
1078 }
1079 else if (node == null)
1080 node = new RNode(seq, Thread.currentThread());
1081 else if (!queued) {
1082 if (queued = U.compareAndSwapObject(this, RHEAD,
1083 node.next = rhead, node))
1084 spins = -1;
1085 }
1086 else {
1087 long time;
1088 if (deadline == 0L)
1089 time = 0L;
1090 else if ((time = deadline - System.nanoTime()) <= 0L)
1091 return cancelReader(node, false);
1092 if ((state & WBIT) != 0L && node.waiter != null) { // recheck
1093 U.park(false, time);
1094 if (interruptible && Thread.interrupted())
1095 return cancelReader(node, true);
1096 }
1097 }
1098 }
1099 }
1100
1101 /**
1102 * If node non-null, forces cancel status and unsplices from queue
1103 * if possible, by traversing entire queue looking for cancelled
1104 * nodes, cleaning out all at head, but stopping upon first
1105 * encounter otherwise.
1106 */
1107 private long cancelReader(RNode node, boolean interrupted) {
1108 Thread w;
1109 if (node != null && (w = node.waiter) != null &&
1110 U.compareAndSwapObject(node, WAITER, w, null)) {
1111 for (RNode pred = null, p = rhead; p != null;) {
1112 RNode q = p.next;
1113 if (p.waiter == null) {
1114 if (pred == null) {
1115 U.compareAndSwapObject(this, RHEAD, p, q);
1116 p = rhead;
1117 }
1118 else {
1119 U.compareAndSwapObject(pred, RNEXT, p, q);
1120 break;
1121 }
1122 }
1123 else {
1124 pred = p;
1125 p = q;
1126 }
1127 }
1128 }
1129 readerPrefSignal();
1130 return (interrupted || Thread.interrupted())? INTERRUPTED : 0L;
1131 }
1132
1133 // Unsafe mechanics
1134 private static final sun.misc.Unsafe U;
1135 private static final long STATE;
1136 private static final long RHEAD;
1137 private static final long WHEAD;
1138 private static final long WTAIL;
1139 private static final long RNEXT;
1140 private static final long WNEXT;
1141 private static final long WPREV;
1142 private static final long WAITER;
1143 private static final long STATUS;
1144
1145 static {
1146 try {
1147 U = getUnsafe();
1148 Class<?> k = StampedLock.class;
1149 Class<?> rk = RNode.class;
1150 Class<?> wk = WNode.class;
1151 STATE = U.objectFieldOffset
1152 (k.getDeclaredField("state"));
1153 RHEAD = U.objectFieldOffset
1154 (k.getDeclaredField("rhead"));
1155 WHEAD = U.objectFieldOffset
1156 (k.getDeclaredField("whead"));
1157 WTAIL = U.objectFieldOffset
1158 (k.getDeclaredField("wtail"));
1159 RNEXT = U.objectFieldOffset
1160 (rk.getDeclaredField("next"));
1161 WAITER = U.objectFieldOffset
1162 (rk.getDeclaredField("waiter"));
1163 STATUS = U.objectFieldOffset
1164 (wk.getDeclaredField("status"));
1165 WNEXT = U.objectFieldOffset
1166 (wk.getDeclaredField("next"));
1167 WPREV = U.objectFieldOffset
1168 (wk.getDeclaredField("prev"));
1169
1170 } catch (Exception e) {
1171 throw new Error(e);
1172 }
1173 }
1174
1175 /**
1176 * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1177 * Replace with a simple call to Unsafe.getUnsafe when integrating
1178 * into a jdk.
1179 *
1180 * @return a sun.misc.Unsafe
1181 */
1182 private static sun.misc.Unsafe getUnsafe() {
1183 try {
1184 return sun.misc.Unsafe.getUnsafe();
1185 } catch (SecurityException se) {
1186 try {
1187 return java.security.AccessController.doPrivileged
1188 (new java.security
1189 .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1190 public sun.misc.Unsafe run() throws Exception {
1191 java.lang.reflect.Field f = sun.misc
1192 .Unsafe.class.getDeclaredField("theUnsafe");
1193 f.setAccessible(true);
1194 return (sun.misc.Unsafe) f.get(null);
1195 }});
1196 } catch (java.security.PrivilegedActionException e) {
1197 throw new RuntimeException("Could not initialize intrinsics",
1198 e.getCause());
1199 }
1200 }
1201 }
1202
1203 }
1204