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