ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.16
Committed: Sun Oct 14 20:00:48 2012 UTC (11 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.15: +1 -1 lines
Log Message:
more obviously correct

File Contents

# User Rev Content
1 dl 1.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 jsr166 1.9 * access. The state of a StampedLock consists of a version and mode.
15     * Lock acquisition methods return a stamp that represents and
16 dl 1.1 * 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 dl 1.6 * and all optimistic read validations will fail. </li>
30 dl 1.1 *
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 jsr166 1.10 * a valid write stamp if (1) already in writing mode (2) in reading
59 dl 1.1 * 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 dl 1.7 * <p>The scheduling policy of StampedLock does not consistently
80     * prefer readers over writers or vice versa. A zero return from any
81 dl 1.8 * "try" method for acquiring or converting locks does not carry any
82 dl 1.7 * information about the state of the lock; a subsequent invocation
83     * may succeed.
84 dl 1.1 *
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 dl 1.6 * private double x, y;
94 dl 1.1 * 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 dl 1.7 * for (long stamp = sl.tryOptimisticRead(); ; stamp = sl.readLock()) {
126 dl 1.1 * 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 jsr166 1.15 * supplementary reader overflow word is used when the number of
184 dl 1.1 * 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 dl 1.8 * 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 dl 1.1 * 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 jsr166 1.4 private static final int SPINS = (NCPU > 1) ? 1 << 6 : 1;
256 dl 1.1
257 dl 1.6 /** Maximum number of retries before re-blocking */
258 jsr166 1.4 private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 12 : 1;
259 dl 1.1
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 jsr166 1.14 private static final int LG_READERS = 7;
265 dl 1.1
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 jsr166 1.4 * @return a stamp that can be used to unlock or convert mode
324 dl 1.1 */
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 jsr166 1.13 * or zero if the lock is not available
338 dl 1.1 */
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 jsr166 1.5 * given time and the current thread has not been interrupted.
350 dl 1.1 *
351     * @return a stamp that can be used to unlock or convert mode,
352 jsr166 1.4 * or zero if the lock is not available
353 dl 1.1 * @throws InterruptedException if the current thread is interrupted
354 jsr166 1.4 * before acquiring the lock
355 dl 1.1 */
356     public long tryWriteLock(long time, TimeUnit unit)
357     throws InterruptedException {
358 jsr166 1.4 long nanos = unit.toNanos(time);
359 dl 1.1 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 jsr166 1.4 * @return a stamp that can be used to unlock or convert mode
379 dl 1.1 * @throws InterruptedException if the current thread is interrupted
380 jsr166 1.4 * before acquiring the lock
381 dl 1.1 */
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 jsr166 1.4 * @return a stamp that can be used to unlock or convert mode
399 dl 1.1 */
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 jsr166 1.4 * or zero if the lock is not available
422 dl 1.1 */
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 jsr166 1.5 * given time and the current thread has not been interrupted.
440 dl 1.1 *
441     * @return a stamp that can be used to unlock or convert mode,
442 jsr166 1.4 * or zero if the lock is not available
443 dl 1.1 * @throws InterruptedException if the current thread is interrupted
444 jsr166 1.4 * before acquiring the lock
445 dl 1.1 */
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 jsr166 1.4 * @return a stamp that can be used to unlock or convert mode
478 dl 1.1 * @throws InterruptedException if the current thread is interrupted
479 jsr166 1.4 * before acquiring the lock
480 dl 1.1 */
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 jsr166 1.4 * not match the current state of this lock
533 dl 1.1 */
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 jsr166 1.11 * If the lock state matches the given stamp, releases the
543 dl 1.1 * non-exclusive lock.
544     *
545     * @param stamp a stamp returned by a read-lock operation
546     * @throws IllegalMonitorStateException if the stamp does
547 jsr166 1.4 * not match the current state of this lock
548 dl 1.1 */
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 jsr166 1.4 * not match the current state of this lock
578 dl 1.1 */
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 jsr166 1.12 * lock, returns it. Or, if a read lock, if the write lock is
610     * available, releases the read lock and returns a write stamp.
611     * Or, if an optimistic read, returns a write stamp only if
612     * immediately available. This method returns zero in all other
613     * cases.
614 dl 1.1 *
615     * @param stamp a stamp
616     * @return a valid write stamp, or zero on failure
617     */
618     public long tryConvertToWriteLock(long stamp) {
619     long a = stamp & ABITS, m, s, next;
620     while (((s = state) & SBITS) == (stamp & SBITS)) {
621     if ((m = s & ABITS) == 0L) {
622     if (a != 0L)
623     break;
624     if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
625     return next;
626     }
627     else if (m == WBIT) {
628     if (a != m)
629     break;
630     return stamp;
631     }
632     else if (m == RUNIT && a != 0L && a < WBIT) {
633     if (U.compareAndSwapLong(this, STATE, s,
634     next = s - RUNIT + WBIT))
635     return next;
636     }
637     else
638     break;
639     }
640     return 0L;
641     }
642    
643     /**
644     * If the lock state matches the given stamp then performs one of
645     * the following actions. If the stamp represents holding a write
646     * lock, releases it and obtains a read lock. Or, if a read lock,
647     * returns it. Or, if an optimistic read, acquires a read lock and
648     * returns a read stamp only if immediately available. This method
649     * returns zero in all other cases.
650     *
651     * @param stamp a stamp
652     * @return a valid read stamp, or zero on failure
653     */
654     public long tryConvertToReadLock(long stamp) {
655     long a = stamp & ABITS, m, s, next;
656     while (((s = state) & SBITS) == (stamp & SBITS)) {
657     if ((m = s & ABITS) == 0L) {
658     if (a != 0L)
659     break;
660     else if (m < RFULL) {
661     if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
662     return next;
663     }
664     else if ((next = tryIncReaderOverflow(s)) != 0L)
665     return next;
666     }
667     else if (m == WBIT) {
668     if (a != m)
669     break;
670     next = state = s + (WBIT + RUNIT);
671     readerPrefSignal();
672     return next;
673     }
674     else if (a != 0L && a < WBIT)
675     return stamp;
676     else
677     break;
678     }
679     return 0L;
680     }
681    
682     /**
683     * If the lock state matches the given stamp then, if the stamp
684     * represents holding a lock, releases it and returns an
685     * observation stamp. Or, if an optimistic read, returns it if
686     * validated. This method returns zero in all other cases, and so
687     * may be useful as a form of "tryUnlock".
688     *
689     * @param stamp a stamp
690     * @return a valid optimistic read stamp, or zero on failure
691     */
692     public long tryConvertToOptimisticRead(long stamp) {
693     long a = stamp & ABITS, m, s, next;
694 jsr166 1.2 while (((s = U.getLongVolatile(this, STATE)) &
695 dl 1.1 SBITS) == (stamp & SBITS)) {
696     if ((m = s & ABITS) == 0L) {
697     if (a != 0L)
698     break;
699     return s;
700     }
701     else if (m == WBIT) {
702     if (a != m)
703     break;
704 jsr166 1.16 state = next = (s += WBIT) == 0L ? ORIGIN : s;
705 dl 1.1 readerPrefSignal();
706     return next;
707     }
708     else if (a == 0L || a >= WBIT)
709     break;
710     else if (m < RFULL) {
711     if (U.compareAndSwapLong(this, STATE, s, next = s - RUNIT)) {
712     if (m == RUNIT)
713     writerPrefSignal();
714     return next & SBITS;
715     }
716     }
717     else if ((next = tryDecReaderOverflow(s)) != 0L)
718     return next & SBITS;
719     }
720     return 0L;
721     }
722    
723     /**
724     * Releases the write lock if it is held, without requiring a
725     * stamp value. This method may be useful for recovery after
726     * errors.
727     *
728 jsr166 1.4 * @return true if the lock was held, else false
729 dl 1.1 */
730     public boolean tryUnlockWrite() {
731     long s;
732     if (((s = state) & WBIT) != 0L) {
733     state = (s += WBIT) == 0L ? ORIGIN : s;
734     readerPrefSignal();
735     return true;
736     }
737     return false;
738     }
739    
740     /**
741     * Releases one hold of the read lock if it is held, without
742     * requiring a stamp value. This method may be useful for recovery
743     * after errors.
744     *
745 jsr166 1.4 * @return true if the read lock was held, else false
746 dl 1.1 */
747     public boolean tryUnlockRead() {
748     long s, m;
749     while ((m = (s = state) & ABITS) != 0L && m < WBIT) {
750     if (m < RFULL) {
751     if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
752     if (m == RUNIT)
753     writerPrefSignal();
754     return true;
755     }
756     }
757     else if (tryDecReaderOverflow(s) != 0L)
758     return true;
759     }
760     return false;
761     }
762    
763     /**
764     * Returns true if the lock is currently held exclusively.
765     *
766     * @return true if the lock is currently held exclusively
767     */
768     public boolean isWriteLocked() {
769     return (state & WBIT) != 0L;
770     }
771    
772     /**
773     * Returns true if the lock is currently held non-exclusively.
774     *
775     * @return true if the lock is currently held non-exclusively
776     */
777     public boolean isReadLocked() {
778     long m;
779     return (m = state & ABITS) > 0L && m < WBIT;
780     }
781    
782     private void readObject(java.io.ObjectInputStream s)
783     throws java.io.IOException, ClassNotFoundException {
784     s.defaultReadObject();
785     state = ORIGIN; // reset to unlocked state
786     }
787    
788     // internals
789    
790     /**
791     * Tries to increment readerOverflow by first setting state
792     * access bits value to RBITS, indicating hold of spinlock,
793     * then updating, then releasing.
794 jsr166 1.4 *
795 dl 1.1 * @param stamp, assumed that (stamp & ABITS) >= RFULL
796     * @return new stamp on success, else zero
797     */
798     private long tryIncReaderOverflow(long s) {
799     if ((s & ABITS) == RFULL) {
800     if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
801     ++readerOverflow;
802     state = s;
803     return s;
804     }
805     }
806 jsr166 1.2 else if ((ThreadLocalRandom.current().nextInt() &
807 dl 1.1 OVERFLOW_YIELD_RATE) == 0)
808     Thread.yield();
809     return 0L;
810     }
811    
812     /**
813     * Tries to decrement readerOverflow.
814 jsr166 1.4 *
815 dl 1.1 * @param stamp, assumed that (stamp & ABITS) >= RFULL
816     * @return new stamp on success, else zero
817     */
818     private long tryDecReaderOverflow(long s) {
819     if ((s & ABITS) == RFULL) {
820     if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
821     int r; long next;
822     if ((r = readerOverflow) > 0) {
823     readerOverflow = r - 1;
824     next = s;
825     }
826     else
827     next = s - RUNIT;
828     state = next;
829     return next;
830     }
831     }
832 jsr166 1.2 else if ((ThreadLocalRandom.current().nextInt() &
833 dl 1.1 OVERFLOW_YIELD_RATE) == 0)
834     Thread.yield();
835     return 0L;
836     }
837    
838     /*
839     * The two versions of signal implement the phase-fair policy.
840     * They include almost the same code, but repacked in different
841     * ways. Integrating the policy with the mechanics eliminates
842     * state rechecks that would be needed with separate reader and
843     * writer signal methods. Both methods assume that they are
844     * called when the lock is last known to be available, and
845     * continue until the lock is unavailable, or at least one thread
846     * is signalled, or there are no more waiting threads. Signalling
847     * a reader entails popping (CASing) from rhead and unparking
848     * unless the thread already cancelled (indicated by a null waiter
849     * field). Signalling a writer requires finding the first node,
850     * i.e., the successor of whead. This is normally just head.next,
851     * but may require traversal from wtail if next pointers are
852     * lagging. These methods may fail to wake up an acquiring thread
853     * when one or more have been cancelled, but the cancel methods
854     * themselves provide extra safeguards to ensure liveness.
855     */
856    
857     private void readerPrefSignal() {
858     boolean readers = false;
859     RNode p; WNode h, q; long s; Thread w;
860     while ((p = rhead) != null) {
861     if (((s = state) & WBIT) != 0L)
862     return;
863     if (p.seq == (s & SBITS))
864     break;
865     readers = true;
866     if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
867     (w = p.waiter) != null &&
868     U.compareAndSwapObject(p, WAITER, w, null))
869     U.unpark(w);
870     }
871     if (!readers && (state & ABITS) == 0L &&
872     (h = whead) != null && h.status != 0) {
873     U.compareAndSwapInt(h, STATUS, WAITING, 0);
874     if ((q = h.next) == null || q.status == CANCELLED) {
875     q = null;
876     for (WNode t = wtail; t != null && t != h; t = t.prev)
877     if (t.status <= 0)
878     q = t;
879     }
880     if (q != null && (w = q.thread) != null)
881     U.unpark(w);
882     }
883     }
884    
885     private void writerPrefSignal() {
886     RNode p; WNode h, q; long s; Thread w;
887     if ((h = whead) != null && h.status != 0) {
888     U.compareAndSwapInt(h, STATUS, WAITING, 0);
889     if ((q = h.next) == null || q.status == CANCELLED) {
890     q = null;
891     for (WNode t = wtail; t != null && t != h; t = t.prev)
892     if (t.status <= 0)
893     q = t;
894     }
895     if (q != null && (w = q.thread) != null)
896     U.unpark(w);
897     }
898     else {
899     while ((p = rhead) != null && ((s = state) & WBIT) == 0L &&
900     p.seq != (s & SBITS)) {
901     if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
902     (w = p.waiter) != null &&
903     U.compareAndSwapObject(p, WAITER, w, null))
904     U.unpark(w);
905     }
906     }
907     }
908    
909     /**
910     * RNG for local spins. The first call from await{Read,Write}
911     * produces a thread-local value. Unless zero, subsequent calls
912 dl 1.8 * use an xorShift to further reduce memory traffic.
913 dl 1.1 */
914     private static int nextRandom(int r) {
915     if (r == 0)
916     return ThreadLocalRandom.current().nextInt();
917     r ^= r << 1; // xorshift
918     r ^= r >>> 3;
919     r ^= r << 10;
920     return r;
921     }
922    
923     /**
924     * Possibly spins trying to obtain write lock, then enqueues and
925 jsr166 1.4 * blocks while not head of write queue or cannot acquire lock,
926 dl 1.1 * possibly spinning when at head; cancelling on timeout or
927     * interrupt.
928     *
929     * @param interruptible true if should check interrupts and if so
930     * return INTERRUPTED
931     * @param deadline if nonzero, the System.nanoTime value to timeout
932 jsr166 1.4 * at (and return zero)
933 dl 1.1 */
934     private long awaitWrite(boolean interruptible, long deadline) {
935     WNode node = null;
936     for (int r = 0, spins = -1;;) {
937     WNode p; long s, next;
938     if (((s = state) & ABITS) == 0L) {
939     if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
940     return next;
941     }
942     else if (spins < 0)
943     spins = whead == wtail ? SPINS : 0;
944     else if (spins > 0) {
945     if ((r = nextRandom(r)) >= 0)
946     --spins;
947     }
948     else if ((p = wtail) == null) { // initialize queue
949     if (U.compareAndSwapObject(this, WHEAD, null,
950     new WNode(null, null)))
951     wtail = whead;
952     }
953     else if (node == null)
954     node = new WNode(Thread.currentThread(), p);
955     else if (node.prev != p)
956     node.prev = p;
957     else if (U.compareAndSwapObject(this, WTAIL, p, node)) {
958     p.next = node;
959     for (int headSpins = SPINS;;) {
960     WNode np; int ps;
961 dl 1.8 if ((np = node.prev) != p && np != null &&
962     (p = np).next != node)
963     p.next = node; // stale
964 dl 1.1 if (p == whead) {
965     for (int k = headSpins;;) {
966     if (((s = state) & ABITS) == 0L) {
967     if (U.compareAndSwapLong(this, STATE,
968     s, next = s + WBIT)) {
969     whead = node;
970     node.thread = null;
971     node.prev = null;
972     return next;
973     }
974     break;
975     }
976     if ((r = nextRandom(r)) >= 0 && --k <= 0)
977     break;
978     }
979     if (headSpins < MAX_HEAD_SPINS)
980     headSpins <<= 1;
981     }
982     if ((ps = p.status) == 0)
983     U.compareAndSwapInt(p, STATUS, 0, WAITING);
984     else if (ps == CANCELLED)
985     node.prev = p.prev;
986     else {
987     long time; // 0 argument to park means no timeout
988     if (deadline == 0L)
989     time = 0L;
990     else if ((time = deadline - System.nanoTime()) <= 0L)
991     return cancelWriter(node, false);
992     if (node.prev == p && p.status == WAITING &&
993     (p != whead || (state & WBIT) != 0L)) { // recheck
994     U.park(false, time);
995     if (interruptible && Thread.interrupted())
996     return cancelWriter(node, true);
997     }
998     }
999     }
1000     }
1001     }
1002     }
1003    
1004     /**
1005     * If node non-null, forces cancel status and unsplices from queue
1006     * if possible. This is a streamlined variant of cancellation
1007     * methods in AbstractQueuedSynchronizer that includes a detailed
1008     * explanation.
1009     */
1010     private long cancelWriter(WNode node, boolean interrupted) {
1011     WNode pred;
1012     if (node != null && (pred = node.prev) != null) {
1013     WNode pp;
1014     node.thread = null;
1015     while (pred.status == CANCELLED && (pp = pred.prev) != null)
1016     pred = node.prev = pp;
1017     WNode predNext = pred.next;
1018     node.status = CANCELLED;
1019     if (predNext != null) {
1020 dl 1.8 Thread w;
1021 dl 1.1 WNode succ = node.next;
1022 dl 1.8 if (succ == null || succ.status == CANCELLED) {
1023     succ = null;
1024     for (WNode t = wtail; t != null && t != node; t = t.prev)
1025     if (t.status <= 0)
1026     succ = t;
1027     if (succ == null && node == wtail)
1028     U.compareAndSwapObject(this, WTAIL, node, pred);
1029     }
1030 dl 1.1 U.compareAndSwapObject(pred, WNEXT, predNext, succ);
1031 dl 1.8 if (succ != null && (w = succ.thread) != null)
1032 dl 1.1 U.unpark(w);
1033     }
1034     }
1035     writerPrefSignal();
1036 jsr166 1.3 return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L;
1037 dl 1.1 }
1038    
1039 jsr166 1.4 /**
1040 dl 1.1 * Waits for read lock or timeout or interrupt. The form of
1041     * awaitRead differs from awaitWrite mainly because it must
1042     * restart (with a new wait node) if the thread was unqueued and
1043     * unparked but could not the obtain lock. We also need to help
1044     * with preference rules by not trying to acquire the lock before
1045     * enqueuing if there is a known waiting writer, but also helping
1046     * to release those threads that are still queued from the last
1047     * release.
1048     */
1049     private long awaitRead(long stamp, boolean interruptible, long deadline) {
1050     long seq = stamp & SBITS;
1051     RNode node = null;
1052     boolean queued = false;
1053     for (int r = 0, headSpins = SPINS, spins = -1;;) {
1054     long s, m, next; RNode p; WNode wh; Thread w;
1055     if ((m = (s = state) & ABITS) != WBIT &&
1056     ((s & SBITS) != seq || (wh = whead) == null ||
1057     wh.status == 0)) {
1058     if (m < RFULL ?
1059     U.compareAndSwapLong(this, STATE, s, next = s + RUNIT) :
1060     (next = tryIncReaderOverflow(s)) != 0L) {
1061     if (node != null && (w = node.waiter) != null)
1062     U.compareAndSwapObject(node, WAITER, w, null);
1063     if ((p = rhead) != null && (s & SBITS) != p.seq &&
1064     U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1065     (w = p.waiter) != null &&
1066     U.compareAndSwapObject(p, WAITER, w, null))
1067     U.unpark(w); // help signal other waiters
1068     return next;
1069     }
1070     }
1071     else if (m != WBIT && (p = rhead) != null &&
1072     (s & SBITS) != p.seq) { // help release old readers
1073     if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1074     (w = p.waiter) != null &&
1075     U.compareAndSwapObject(p, WAITER, w, null))
1076     U.unpark(w);
1077     }
1078     else if (queued && node != null && node.waiter == null) {
1079     node = null; // restart
1080     queued = false;
1081     spins = -1;
1082     }
1083     else if (spins < 0) {
1084     if (rhead != node)
1085     spins = 0;
1086     else if ((spins = headSpins) < MAX_HEAD_SPINS && node != null)
1087     headSpins <<= 1;
1088     }
1089     else if (spins > 0) {
1090     if ((r = nextRandom(r)) >= 0)
1091     --spins;
1092     }
1093     else if (node == null)
1094     node = new RNode(seq, Thread.currentThread());
1095     else if (!queued) {
1096     if (queued = U.compareAndSwapObject(this, RHEAD,
1097     node.next = rhead, node))
1098     spins = -1;
1099     }
1100     else {
1101     long time;
1102     if (deadline == 0L)
1103     time = 0L;
1104     else if ((time = deadline - System.nanoTime()) <= 0L)
1105     return cancelReader(node, false);
1106     if ((state & WBIT) != 0L && node.waiter != null) { // recheck
1107     U.park(false, time);
1108     if (interruptible && Thread.interrupted())
1109     return cancelReader(node, true);
1110     }
1111     }
1112     }
1113     }
1114    
1115     /**
1116     * If node non-null, forces cancel status and unsplices from queue
1117     * if possible, by traversing entire queue looking for cancelled
1118 dl 1.6 * nodes.
1119 dl 1.1 */
1120     private long cancelReader(RNode node, boolean interrupted) {
1121     Thread w;
1122     if (node != null && (w = node.waiter) != null &&
1123     U.compareAndSwapObject(node, WAITER, w, null)) {
1124     for (RNode pred = null, p = rhead; p != null;) {
1125     RNode q = p.next;
1126     if (p.waiter == null) {
1127     if (pred == null) {
1128     U.compareAndSwapObject(this, RHEAD, p, q);
1129     p = rhead;
1130     }
1131     else {
1132     U.compareAndSwapObject(pred, RNEXT, p, q);
1133 dl 1.6 p = pred.next;
1134 dl 1.1 }
1135     }
1136     else {
1137     pred = p;
1138     p = q;
1139     }
1140     }
1141     }
1142     readerPrefSignal();
1143 jsr166 1.3 return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L;
1144 dl 1.1 }
1145    
1146     // Unsafe mechanics
1147     private static final sun.misc.Unsafe U;
1148     private static final long STATE;
1149     private static final long RHEAD;
1150     private static final long WHEAD;
1151     private static final long WTAIL;
1152     private static final long RNEXT;
1153     private static final long WNEXT;
1154     private static final long WPREV;
1155     private static final long WAITER;
1156     private static final long STATUS;
1157    
1158     static {
1159     try {
1160     U = getUnsafe();
1161     Class<?> k = StampedLock.class;
1162     Class<?> rk = RNode.class;
1163     Class<?> wk = WNode.class;
1164     STATE = U.objectFieldOffset
1165     (k.getDeclaredField("state"));
1166     RHEAD = U.objectFieldOffset
1167     (k.getDeclaredField("rhead"));
1168     WHEAD = U.objectFieldOffset
1169     (k.getDeclaredField("whead"));
1170     WTAIL = U.objectFieldOffset
1171     (k.getDeclaredField("wtail"));
1172     RNEXT = U.objectFieldOffset
1173     (rk.getDeclaredField("next"));
1174     WAITER = U.objectFieldOffset
1175     (rk.getDeclaredField("waiter"));
1176     STATUS = U.objectFieldOffset
1177     (wk.getDeclaredField("status"));
1178     WNEXT = U.objectFieldOffset
1179     (wk.getDeclaredField("next"));
1180     WPREV = U.objectFieldOffset
1181     (wk.getDeclaredField("prev"));
1182    
1183     } catch (Exception e) {
1184     throw new Error(e);
1185     }
1186     }
1187    
1188     /**
1189     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1190     * Replace with a simple call to Unsafe.getUnsafe when integrating
1191     * into a jdk.
1192     *
1193     * @return a sun.misc.Unsafe
1194     */
1195     private static sun.misc.Unsafe getUnsafe() {
1196     try {
1197     return sun.misc.Unsafe.getUnsafe();
1198     } catch (SecurityException se) {
1199     try {
1200     return java.security.AccessController.doPrivileged
1201     (new java.security
1202     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1203     public sun.misc.Unsafe run() throws Exception {
1204     java.lang.reflect.Field f = sun.misc
1205     .Unsafe.class.getDeclaredField("theUnsafe");
1206     f.setAccessible(true);
1207     return (sun.misc.Unsafe) f.get(null);
1208     }});
1209     } catch (java.security.PrivilegedActionException e) {
1210     throw new RuntimeException("Could not initialize intrinsics",
1211     e.getCause());
1212     }
1213     }
1214     }
1215    
1216     }