ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
Revision: 1.28
Committed: Tue Jan 22 15:42:28 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.27: +468 -422 lines
Log Message:
Revamp scheduling

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