ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.4
Committed: Fri Oct 12 16:48:15 2012 UTC (11 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +25 -23 lines
Log Message:
tidying

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