ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.8
Committed: Sat Oct 13 11:51:12 2012 UTC (11 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.7: +29 -21 lines
Log Message:
Misc minor improvements

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