ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.19
Committed: Mon Oct 15 12:12:42 2012 UTC (11 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.18: +63 -55 lines
Log Message:
Various improvements incorporating review suggestions

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