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