ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.32
Committed: Sat Jan 26 01:22:37 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.31: +115 -14 lines
Log Message:
API and internal documentation improvements

File Contents

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