ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StampedLock.java
(Generate patch)

Comparing jsr166/src/jsr166e/StampedLock.java (file contents):
Revision 1.22 by jsr166, Wed Oct 17 00:02:47 2012 UTC vs.
Revision 1.34 by jsr166, Mon Jan 28 17:23:04 2013 UTC

# Line 8 | Line 8 | package jsr166e;
8  
9   import java.util.concurrent.ThreadLocalRandom;
10   import java.util.concurrent.TimeUnit;
11 + import java.util.concurrent.locks.Lock;
12 + import java.util.concurrent.locks.Condition;
13 + import java.util.concurrent.locks.ReadWriteLock;
14 + import java.util.concurrent.locks.LockSupport;
15  
16   /**
17   * A capability-based lock with three modes for controlling read/write
# Line 36 | Line 40 | import java.util.concurrent.TimeUnit;
40   *  <li><b>Optimistic Reading.</b> Method {@link #tryOptimisticRead}
41   *   returns a non-zero stamp only if the lock is not currently held
42   *   in write mode. Method {@link #validate} returns true if the lock
43 < *   has not since been acquired in write mode. This mode can be
44 < *   thought of as an extremely weak version of a read-lock, that can
45 < *   be broken by a writer at any time.  The use of optimistic mode
46 < *   for short read-only code segments often reduces contention and
47 < *   improves throughput.  However, its use is inherently fragile.
48 < *   Optimistic read sections should only read fields and hold them in
49 < *   local variables for later use after validation. Fields read while
50 < *   in optimistic mode may be wildly inconsistent, so usage applies
51 < *   only when you are familiar enough with data representations to
52 < *   check consistency and/or repeatedly invoke method {@code
53 < *   validate()}.  For example, such steps are typically required when
54 < *   first reading an object or array reference, and then accessing
55 < *   one of its fields, elements or methods. </li>
43 > *   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   *
58   * </ul>
59   *
# Line 80 | Line 85 | import java.util.concurrent.TimeUnit;
85   * locking.
86   *
87   * <p>The scheduling policy of StampedLock does not consistently
88 < * prefer readers over writers or vice versa.  A zero return from any
89 < * "try" method for acquiring or converting locks does not carry any
90 < * information about the state of the lock; a subsequent invocation
91 < * may succeed.
88 > * 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   *
101   * <p><b>Sample Usage.</b> The following illustrates some usage idioms
102   * in a class that maintains simple two-dimensional points. The sample
# Line 156 | Line 169 | import java.util.concurrent.TimeUnit;
169   *         }
170   *       }
171   *     } finally {
172 < *        sl.unlock(stamp);
172 > *       sl.unlock(stamp);
173   *     }
174   *   }
175   * }}</pre>
# Line 173 | Line 186 | public class StampedLock implements java
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 <     * Ordered RW locks (see Shirako et al
189 >     * and Ordered RW locks (see Shirako et al
190       * http://dl.acm.org/citation.cfm?id=2312015)
178     * and Phase-Fair locks (see Brandenburg & Anderson, especially
179     * http://www.cs.unc.edu/~bbb/diss/).
191       *
192       * Conceptually, the primary state of the lock includes a sequence
193       * number that is odd when write-locked and even otherwise.
# Line 189 | Line 200 | public class StampedLock implements java
200       * reader count value (RBITS) as a spinlock protecting overflow
201       * updates.
202       *
203 <     * Waiting readers and writers use different queues. The writer
204 <     * queue is a modified form of CLH lock.  (For discussion of CLH,
205 <     * see the internal documentation of AbstractQueuedSynchronizer.)
206 <     * The reader "queue" is a form of Treiber stack, that supports
207 <     * simpler/faster operations because order within a queue doesn't
208 <     * matter and all are signalled at once.  However the sequence of
209 <     * threads within the queue vs the current stamp does matter (see
210 <     * Shirako et al) so each carries its incoming stamp value.
211 <     * Waiting writers never need to track sequence values, so they
212 <     * don't.
213 <     *
214 <     * These queue mechanics hardwire the scheduling policy.  Ignoring
215 <     * trylocks, cancellation, and spinning, they implement Phase-Fair
216 <     * preferences:
217 <     *   1. Unlocked writers prefer to signal waiting readers
218 <     *   2. Fully unlocked readers prefer to signal waiting writers
208 <     *   3. When read-locked and a waiting writer exists, the writer
209 <     *      is preferred to incoming readers
203 >     * Waiters use a modified form of CLH lock used in
204 >     * AbstractQueuedSynchronizer (see its internal documentation for
205 >     * a fuller account), where each node is tagged (field mode) as
206 >     * 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 >     * 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 >     * 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       *
220       * These rules apply to threads actually queued. All tryLock forms
221       * opportunistically try to acquire locks regardless of preference
222 <     * rules, and so may "barge" their way in.  Additionally, initial
223 <     * phases of the await* methods (invoked from readLock() and
224 <     * writeLock()) use controlled spins that have similar effect.
225 <     * Phase-fair preferences may also be broken on cancellations due
226 <     * to timeouts and interrupts.  Rule #3 (incoming readers when a
227 <     * waiting writer) is approximated with varying precision in
228 <     * different contexts -- some checks do not account for
229 <     * in-progress spins/signals, and others do not account for
230 <     * cancellations.
231 <     *
232 <     * Controlled, randomized spinning is used in the two await
233 <     * methods to reduce (increasingly expensive) context switching
234 <     * while also avoiding sustained memory thrashing among many
235 <     * threads.  Both await methods use a similar spin strategy: If
236 <     * the associated queue appears to be empty, then the thread
237 <     * spin-waits up to SPINS times (where each iteration decreases
229 <     * spin count with 50% probability) before enqueing, and then, if
230 <     * it is the first thread to be enqueued, spins again up to SPINS
231 <     * times before blocking. If, upon wakening it fails to obtain
232 <     * lock, and is still (or becomes) the first waiting thread (which
233 <     * indicates that some other thread barged and obtained lock), it
234 <     * escalates spins (up to MAX_HEAD_SPINS) to reduce the likelihood
235 <     * of continually losing to barging threads.
222 >     * 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 >     * sprawl out because actions and retries rely on consistent sets
237 >     * of locally cached reads.
238       *
239       * As noted in Boehm's paper (above), sequence validation (mainly
240       * method validate()) requires stricter ordering rules than apply
# Line 252 | Line 254 | public class StampedLock implements java
254       * be subject to future improvements.
255       */
256  
257 +    private static final long serialVersionUID = -6001602636862214147L;
258 +
259      /** Number of processors, for spin control */
260      private static final int NCPU = Runtime.getRuntime().availableProcessors();
261  
262      /** Maximum number of retries before blocking on acquisition */
263 <    private static final int SPINS = (NCPU > 1) ? 1 << 6 : 1;
263 >    private static final int SPINS = (NCPU > 1) ? 1 << 6 : 0;
264  
265      /** Maximum number of retries before re-blocking */
266 <    private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 12 : 1;
266 >    private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 12 : 0;
267  
268      /** The period for yielding when waiting for overflow spinlock */
269      private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1
# Line 278 | Line 282 | public class StampedLock implements java
282      // Initial value for lock state; avoid failure value zero
283      private static final long ORIGIN = WBIT << 1;
284  
285 <    // Special value from cancelled await methods so caller can throw IE
285 >    // Special value from cancelled acquire methods so caller can throw IE
286      private static final long INTERRUPTED = 1L;
287  
288 <    // Values for writer status; order matters
288 >    // Values for node status; order matters
289      private static final int WAITING   = -1;
290      private static final int CANCELLED =  1;
291  
292 <    /** Wait nodes for readers */
293 <    static final class RNode {
294 <        final long seq;         // stamp value upon enqueue
291 <        volatile Thread waiter; // null if no longer waiting
292 <        volatile RNode next;
293 <        RNode(long s, Thread w) { seq = s; waiter = w; }
294 <    }
292 >    // Modes for nodes (int not boolean to allow arithmetic)
293 >    private static final int RMODE = 0;
294 >    private static final int WMODE = 1;
295  
296 <    /** Wait nodes for writers */
296 >    /** Wait nodes */
297      static final class WNode {
298        volatile int status;   // 0, WAITING, or CANCELLED
298          volatile WNode prev;
299          volatile WNode next;
300 <        volatile Thread thread;
301 <        WNode(Thread t, WNode p) { thread = t; prev = p; }
300 >        volatile WNode cowait;    // list of linked readers
301 >        volatile Thread thread;   // non-null while possibly parked
302 >        volatile int status;      // 0, WAITING, or CANCELLED
303 >        final int mode;           // RMODE or WMODE
304 >        WNode(int m, WNode p) { mode = m; prev = p; }
305      }
306  
307 <    /** Head of writer CLH queue */
307 >    /** Head of CLH queue */
308      private transient volatile WNode whead;
309 <    /** Tail (last) of writer CLH queue */
309 >    /** Tail (last) of CLH queue */
310      private transient volatile WNode wtail;
311 <    /** Head of read queue  */
312 <    private transient volatile RNode rhead;
313 <    /** The state of the lock -- high bits hold sequence, low bits read count */
311 >
312 >    // views
313 >    transient ReadLockView readLockView;
314 >    transient WriteLockView writeLockView;
315 >    transient ReadWriteLockView readWriteLockView;
316 >
317 >    /** Lock sequence/state */
318      private transient volatile long state;
319      /** extra reader count when state read count saturated */
320      private transient int readerOverflow;
# Line 327 | Line 333 | public class StampedLock implements java
333       * @return a stamp that can be used to unlock or convert mode
334       */
335      public long writeLock() {
336 <        long s, next;
337 <        if (((s = state) & ABITS) == 0L &&
338 <            U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
339 <            return next;
334 <        return awaitWrite(false, 0L);
336 >        long s, next;  // bypass acquireWrite in fully unlocked case only
337 >        return ((((s = state) & ABITS) == 0L &&
338 >                 U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ?
339 >                next : acquireWrite(false, 0L));
340      }
341  
342      /**
# Line 342 | Line 347 | public class StampedLock implements java
347       */
348      public long tryWriteLock() {
349          long s, next;
350 <        if (((s = state) & ABITS) == 0L &&
351 <            U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
352 <            return next;
348 <        return 0L;
350 >        return ((((s = state) & ABITS) == 0L &&
351 >                 U.compareAndSwapLong(this, STATE, s, next = s + WBIT)) ?
352 >                next : 0L);
353      }
354  
355      /**
356       * Exclusively acquires the lock if it is available within the
357       * given time and the current thread has not been interrupted.
358 +     * Behavior under timeout and interruption matches that specified
359 +     * for method {@link Lock#tryLock(long,TimeUnit)}.
360       *
361       * @return a stamp that can be used to unlock or convert mode,
362       * or zero if the lock is not available
# Line 361 | Line 367 | public class StampedLock implements java
367          throws InterruptedException {
368          long nanos = unit.toNanos(time);
369          if (!Thread.interrupted()) {
370 <            long s, next, deadline;
371 <            if (((s = state) & ABITS) == 0L &&
366 <                U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
370 >            long next, deadline;
371 >            if ((next = tryWriteLock()) != 0L)
372                  return next;
373              if (nanos <= 0L)
374                  return 0L;
375              if ((deadline = System.nanoTime() + nanos) == 0L)
376                  deadline = 1L;
377 <            if ((next = awaitWrite(true, deadline)) != INTERRUPTED)
377 >            if ((next = acquireWrite(true, deadline)) != INTERRUPTED)
378                  return next;
379          }
380          throw new InterruptedException();
# Line 378 | Line 383 | public class StampedLock implements java
383      /**
384       * Exclusively acquires the lock, blocking if necessary
385       * until available or the current thread is interrupted.
386 +     * Behavior under interruption matches that specified
387 +     * for method {@link Lock#lockInterruptibly()}.
388       *
389       * @return a stamp that can be used to unlock or convert mode
390       * @throws InterruptedException if the current thread is interrupted
391       * before acquiring the lock
392       */
393      public long writeLockInterruptibly() throws InterruptedException {
394 <        if (!Thread.interrupted()) {
395 <            long s, next;
396 <            if (((s = state) & ABITS) == 0L &&
397 <                U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
391 <                return next;
392 <            if ((next = awaitWrite(true, 0L)) != INTERRUPTED)
393 <                return next;
394 <        }
394 >        long next;
395 >        if (!Thread.interrupted() &&
396 >            (next = acquireWrite(true, 0L)) != INTERRUPTED)
397 >            return next;
398          throw new InterruptedException();
399      }
400  
# Line 402 | Line 405 | public class StampedLock implements java
405       * @return a stamp that can be used to unlock or convert mode
406       */
407      public long readLock() {
408 <        for (;;) {
409 <            long s, m, next;
410 <            if ((m = (s = state) & ABITS) == 0L ||
411 <                (m < WBIT && whead == wtail)) {
409 <                if (m < RFULL) {
410 <                    if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
411 <                        return next;
412 <                }
413 <                else if ((next = tryIncReaderOverflow(s)) != 0L)
414 <                    return next;
415 <            }
416 <            else
417 <                return awaitRead(s, false, 0L);
418 <        }
408 >        long s, next;  // bypass acquireRead on fully unlocked case only
409 >        return ((((s = state) & ABITS) == 0L &&
410 >                 U.compareAndSwapLong(this, STATE, s, next = s + RUNIT)) ?
411 >                next : acquireRead(false, 0L));
412      }
413  
414      /**
# Line 441 | Line 434 | public class StampedLock implements java
434      /**
435       * Non-exclusively acquires the lock if it is available within the
436       * given time and the current thread has not been interrupted.
437 +     * Behavior under timeout and interruption matches that specified
438 +     * for method {@link Lock#tryLock(long,TimeUnit)}.
439       *
440       * @return a stamp that can be used to unlock or convert mode,
441       * or zero if the lock is not available
# Line 449 | Line 444 | public class StampedLock implements java
444       */
445      public long tryReadLock(long time, TimeUnit unit)
446          throws InterruptedException {
447 +        long s, m, next, deadline;
448          long nanos = unit.toNanos(time);
449          if (!Thread.interrupted()) {
450 <            for (;;) {
451 <                long s, m, next, deadline;
456 <                if ((m = (s = state) & ABITS) == WBIT ||
457 <                    (m != 0L && whead != wtail)) {
458 <                    if (nanos <= 0L)
459 <                        return 0L;
460 <                    if ((deadline = System.nanoTime() + nanos) == 0L)
461 <                        deadline = 1L;
462 <                    if ((next = awaitRead(s, true, deadline)) != INTERRUPTED)
463 <                        return next;
464 <                    break;
465 <                }
466 <                else if (m < RFULL) {
450 >            if ((m = (s = state) & ABITS) != WBIT) {
451 >                if (m < RFULL) {
452                      if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
453                          return next;
454                  }
455                  else if ((next = tryIncReaderOverflow(s)) != 0L)
456                      return next;
457              }
458 +            if (nanos <= 0L)
459 +                return 0L;
460 +            if ((deadline = System.nanoTime() + nanos) == 0L)
461 +                deadline = 1L;
462 +            if ((next = acquireRead(true, deadline)) != INTERRUPTED)
463 +                return next;
464          }
465          throw new InterruptedException();
466      }
# Line 477 | Line 468 | public class StampedLock implements java
468      /**
469       * Non-exclusively acquires the lock, blocking if necessary
470       * until available or the current thread is interrupted.
471 +     * Behavior under interruption matches that specified
472 +     * for method {@link Lock#lockInterruptibly()}.
473       *
474       * @return a stamp that can be used to unlock or convert mode
475       * @throws InterruptedException if the current thread is interrupted
476       * before acquiring the lock
477       */
478      public long readLockInterruptibly() throws InterruptedException {
479 <        if (!Thread.interrupted()) {
480 <            for (;;) {
481 <                long s, next, m;
482 <                if ((m = (s = state) & ABITS) == WBIT ||
490 <                    (m != 0L && whead != wtail)) {
491 <                    if ((next = awaitRead(s, true, 0L)) != INTERRUPTED)
492 <                        return next;
493 <                    break;
494 <                }
495 <                else if (m < RFULL) {
496 <                    if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
497 <                        return next;
498 <                }
499 <                else if ((next = tryIncReaderOverflow(s)) != 0L)
500 <                    return next;
501 <            }
502 <        }
479 >        long next;
480 >        if (!Thread.interrupted() &&
481 >            (next = acquireRead(true, 0L)) != INTERRUPTED)
482 >            return next;
483          throw new InterruptedException();
484      }
485  
# Line 518 | Line 498 | public class StampedLock implements java
498       * Returns true if the lock has not been exclusively acquired
499       * since issuance of the given stamp. Always returns false if the
500       * stamp is zero. Always returns true if the stamp represents a
501 <     * currently held lock.
501 >     * currently held lock. Invoking this method with a value not
502 >     * obtained from {@link #tryOptimisticRead} or a locking method
503 >     * for this lock has no defined effect or result.
504       *
505       * @return true if the lock has not been exclusively acquired
506       * since issuance of the given stamp; else false
# Line 537 | Line 519 | public class StampedLock implements java
519       * not match the current state of this lock
520       */
521      public void unlockWrite(long stamp) {
522 +        WNode h;
523          if (state != stamp || (stamp & WBIT) == 0L)
524              throw new IllegalMonitorStateException();
525          state = (stamp += WBIT) == 0L ? ORIGIN : stamp;
526 <        readerPrefSignal();
526 >        if ((h = whead) != null && h.status != 0)
527 >            release(h);
528      }
529  
530      /**
# Line 552 | Line 536 | public class StampedLock implements java
536       * not match the current state of this lock
537       */
538      public void unlockRead(long stamp) {
539 <        long s, m;
540 <        if ((stamp & RBITS) != 0L) {
541 <            while (((s = state) & SBITS) == (stamp & SBITS)) {
542 <                if ((m = s & ABITS) == 0L)
539 >        long s, m; WNode h;
540 >        for (;;) {
541 >            if (((s = state) & SBITS) != (stamp & SBITS) ||
542 >                (stamp & ABITS) == 0L || (m = s & ABITS) == 0L || m == WBIT)
543 >                throw new IllegalMonitorStateException();
544 >            if (m < RFULL) {
545 >                if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
546 >                    if (m == RUNIT && (h = whead) != null && h.status != 0)
547 >                        release(h);
548                      break;
560                else if (m < RFULL) {
561                    if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
562                        if (m == RUNIT)
563                            writerPrefSignal();
564                        return;
565                    }
549                  }
567                else if (m >= WBIT)
568                    break;
569                else if (tryDecReaderOverflow(s) != 0L)
570                    return;
550              }
551 +            else if (tryDecReaderOverflow(s) != 0L)
552 +                break;
553          }
573        throw new IllegalMonitorStateException();
554      }
555  
556      /**
# Line 582 | Line 562 | public class StampedLock implements java
562       * not match the current state of this lock
563       */
564      public void unlock(long stamp) {
565 <        long a = stamp & ABITS, m, s;
565 >        long a = stamp & ABITS, m, s; WNode h;
566          while (((s = state) & SBITS) == (stamp & SBITS)) {
567              if ((m = s & ABITS) == 0L)
568                  break;
# Line 590 | Line 570 | public class StampedLock implements java
570                  if (a != m)
571                      break;
572                  state = (s += WBIT) == 0L ? ORIGIN : s;
573 <                readerPrefSignal();
573 >                if ((h = whead) != null && h.status != 0)
574 >                    release(h);
575                  return;
576              }
577              else if (a == 0L || a >= WBIT)
578                  break;
579              else if (m < RFULL) {
580                  if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
581 <                    if (m == RUNIT)
582 <                        writerPrefSignal();
581 >                    if (m == RUNIT && (h = whead) != null && h.status != 0)
582 >                        release(h);
583                      return;
584                  }
585              }
# Line 609 | Line 590 | public class StampedLock implements java
590      }
591  
592      /**
593 <     * If the lock state matches the given stamp then performs one of
593 >     * If the lock state matches the given stamp, performs one of
594       * the following actions. If the stamp represents holding a write
595       * lock, returns it.  Or, if a read lock, if the write lock is
596       * available, releases the read lock and returns a write stamp.
# Line 646 | Line 627 | public class StampedLock implements java
627      }
628  
629      /**
630 <     * If the lock state matches the given stamp then performs one of
630 >     * If the lock state matches the given stamp, performs one of
631       * the following actions. If the stamp represents holding a write
632       * lock, releases it and obtains a read lock.  Or, if a read lock,
633       * returns it. Or, if an optimistic read, acquires a read lock and
# Line 657 | Line 638 | public class StampedLock implements java
638       * @return a valid read stamp, or zero on failure
639       */
640      public long tryConvertToReadLock(long stamp) {
641 <        long a = stamp & ABITS, m, s, next;
641 >        long a = stamp & ABITS, m, s, next; WNode h;
642          while (((s = state) & SBITS) == (stamp & SBITS)) {
643              if ((m = s & ABITS) == 0L) {
644                  if (a != 0L)
# Line 673 | Line 654 | public class StampedLock implements java
654                  if (a != m)
655                      break;
656                  state = next = s + (WBIT + RUNIT);
657 <                readerPrefSignal();
657 >                if ((h = whead) != null && h.status != 0)
658 >                    release(h);
659                  return next;
660              }
661              else if (a != 0L && a < WBIT)
# Line 695 | Line 677 | public class StampedLock implements java
677       * @return a valid optimistic read stamp, or zero on failure
678       */
679      public long tryConvertToOptimisticRead(long stamp) {
680 <        long a = stamp & ABITS, m, s, next;
681 <        while (((s = U.getLongVolatile(this, STATE)) &
682 <                SBITS) == (stamp & SBITS)) {
680 >        long a = stamp & ABITS, m, s, next; WNode h;
681 >        for (;;) {
682 >            s = U.getLongVolatile(this, STATE); // see above
683 >            if ((s & SBITS) != (stamp & SBITS))
684 >                break;
685              if ((m = s & ABITS) == 0L) {
686                  if (a != 0L)
687                      break;
# Line 707 | Line 691 | public class StampedLock implements java
691                  if (a != m)
692                      break;
693                  state = next = (s += WBIT) == 0L ? ORIGIN : s;
694 <                readerPrefSignal();
694 >                if ((h = whead) != null && h.status != 0)
695 >                    release(h);
696                  return next;
697              }
698              else if (a == 0L || a >= WBIT)
699                  break;
700              else if (m < RFULL) {
701                  if (U.compareAndSwapLong(this, STATE, s, next = s - RUNIT)) {
702 <                    if (m == RUNIT)
703 <                        writerPrefSignal();
702 >                    if (m == RUNIT && (h = whead) != null && h.status != 0)
703 >                        release(h);
704                      return next & SBITS;
705                  }
706              }
# Line 733 | Line 718 | public class StampedLock implements java
718       * @return true if the lock was held, else false
719       */
720      public boolean tryUnlockWrite() {
721 <        long s;
721 >        long s; WNode h;
722          if (((s = state) & WBIT) != 0L) {
723              state = (s += WBIT) == 0L ? ORIGIN : s;
724 <            readerPrefSignal();
724 >            if ((h = whead) != null && h.status != 0)
725 >                release(h);
726              return true;
727          }
728          return false;
# Line 750 | Line 736 | public class StampedLock implements java
736       * @return true if the read lock was held, else false
737       */
738      public boolean tryUnlockRead() {
739 <        long s, m;
739 >        long s, m; WNode h;
740          while ((m = (s = state) & ABITS) != 0L && m < WBIT) {
741              if (m < RFULL) {
742                  if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
743 <                    if (m == RUNIT)
744 <                        writerPrefSignal();
743 >                    if (m == RUNIT && (h = whead) != null && h.status != 0)
744 >                        release(h);
745                      return true;
746                  }
747              }
# Line 789 | Line 775 | public class StampedLock implements java
775          state = ORIGIN; // reset to unlocked state
776      }
777  
778 +    /**
779 +     * Returns a plain {@link Lock} view of this StampedLock in which
780 +     * the {@link Lock#lock} method is mapped to {@link #readLock},
781 +     * and similarly for other methods. The returned Lock does not
782 +     * support a {@link Condition}; method {@link
783 +     * Lock#newCondition()} throws {@code
784 +     * UnsupportedOperationException}.
785 +     *
786 +     * @return the lock
787 +     */
788 +    public Lock asReadLock() {
789 +        ReadLockView v;
790 +        return ((v = readLockView) != null ? v :
791 +                (readLockView = new ReadLockView()));
792 +    }
793 +
794 +    /**
795 +     * Returns a plain {@link Lock} view of this StampedLock in which
796 +     * the {@link Lock#lock} method is mapped to {@link #writeLock},
797 +     * and similarly for other methods. The returned Lock does not
798 +     * support a {@link Condition}; method {@link
799 +     * Lock#newCondition()} throws {@code
800 +     * UnsupportedOperationException}.
801 +     *
802 +     * @return the lock
803 +     */
804 +    public Lock asWriteLock() {
805 +        WriteLockView v;
806 +        return ((v = writeLockView) != null ? v :
807 +                (writeLockView = new WriteLockView()));
808 +    }
809 +
810 +    /**
811 +     * Returns a {@link ReadWriteLock} view of this StampedLock in
812 +     * which the {@link ReadWriteLock#readLock()} method is mapped to
813 +     * {@link #asReadLock()}, and {@link ReadWriteLock#writeLock()} to
814 +     * {@link #asWriteLock()}.
815 +     *
816 +     * @return the lock
817 +     */
818 +    public ReadWriteLock asReadWriteLock() {
819 +        ReadWriteLockView v;
820 +        return ((v = readWriteLockView) != null ? v :
821 +                (readWriteLockView = new ReadWriteLockView()));
822 +    }
823 +
824 +    // view classes
825 +
826 +    final class ReadLockView implements Lock {
827 +        public void lock() { readLock(); }
828 +        public void lockInterruptibly() throws InterruptedException {
829 +            readLockInterruptibly();
830 +        }
831 +        public boolean tryLock() { return tryReadLock() != 0L; }
832 +        public boolean tryLock(long time, TimeUnit unit)
833 +            throws InterruptedException {
834 +            return tryReadLock(time, unit) != 0L;
835 +        }
836 +        public void unlock() { unstampedUnlockRead(); }
837 +        public Condition newCondition() {
838 +            throw new UnsupportedOperationException();
839 +        }
840 +    }
841 +
842 +    final class WriteLockView implements Lock {
843 +        public void lock() { writeLock(); }
844 +        public void lockInterruptibly() throws InterruptedException {
845 +            writeLockInterruptibly();
846 +        }
847 +        public boolean tryLock() { return tryWriteLock() != 0L; }
848 +        public boolean tryLock(long time, TimeUnit unit)
849 +            throws InterruptedException {
850 +            return tryWriteLock(time, unit) != 0L;
851 +        }
852 +        public void unlock() { unstampedUnlockWrite(); }
853 +        public Condition newCondition() {
854 +            throw new UnsupportedOperationException();
855 +        }
856 +    }
857 +
858 +    final class ReadWriteLockView implements ReadWriteLock {
859 +        public Lock readLock() { return asReadLock(); }
860 +        public Lock writeLock() { return asWriteLock(); }
861 +    }
862 +
863 +    // Unlock methods without stamp argument checks for view classes.
864 +    // Needed because view-class lock methods throw away stamps.
865 +
866 +    final void unstampedUnlockWrite() {
867 +        WNode h; long s;
868 +        if (((s = state) & WBIT) == 0L)
869 +            throw new IllegalMonitorStateException();
870 +        state = (s += WBIT) == 0L ? ORIGIN : s;
871 +        if ((h = whead) != null && h.status != 0)
872 +            release(h);
873 +    }
874 +
875 +    final void unstampedUnlockRead() {
876 +        for (;;) {
877 +            long s, m; WNode h;
878 +            if ((m = (s = state) & ABITS) == 0L || m >= WBIT)
879 +                throw new IllegalMonitorStateException();
880 +            else if (m < RFULL) {
881 +                if (U.compareAndSwapLong(this, STATE, s, s - RUNIT)) {
882 +                    if (m == RUNIT && (h = whead) != null && h.status != 0)
883 +                        release(h);
884 +                    break;
885 +                }
886 +            }
887 +            else if (tryDecReaderOverflow(s) != 0L)
888 +                break;
889 +        }
890 +    }
891 +
892      // internals
893  
894      /**
# Line 839 | Line 939 | public class StampedLock implements java
939          return 0L;
940      }
941  
942 <    /*
943 <     * The two versions of signal implement the phase-fair policy.
944 <     * They include almost the same code, but repacked in different
945 <     * ways.  Integrating the policy with the mechanics eliminates
946 <     * state rechecks that would be needed with separate reader and
947 <     * writer signal methods.  Both methods assume that they are
948 <     * called when the lock is last known to be available, and
949 <     * continue until the lock is unavailable, or at least one thread
950 <     * is signalled, or there are no more waiting threads.  Signalling
951 <     * a reader entails popping (CASing) from rhead and unparking
952 <     * unless the thread already cancelled (indicated by a null waiter
853 <     * field). Signalling a writer requires finding the first node,
854 <     * i.e., the successor of whead. This is normally just head.next,
855 <     * but may require traversal from wtail if next pointers are
856 <     * lagging. These methods may fail to wake up an acquiring thread
857 <     * when one or more have been cancelled, but the cancel methods
858 <     * themselves provide extra safeguards to ensure liveness.
859 <     */
860 <
861 <    private void readerPrefSignal() {
862 <        boolean readers = false;
863 <        RNode p; WNode h, q; long s; Thread w;
864 <        while ((p = rhead) != null) {
865 <            if (((s = state) & WBIT) != 0L)
866 <                return;
867 <            if (p.seq == (s & SBITS))
868 <                break;
869 <            readers = true;
870 <            if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
871 <                (w = p.waiter) != null &&
872 <                U.compareAndSwapObject(p, WAITER, w, null))
873 <                U.unpark(w);
874 <        }
875 <        if (!readers && (h = whead) != null && h.status != 0 &&
876 <            (state & ABITS) == 0L) {
877 <            U.compareAndSwapInt(h, STATUS, WAITING, 0);
878 <            if ((q = h.next) == null || q.status == CANCELLED) {
879 <                for (WNode t = wtail; t != null && t != h; t = t.prev)
880 <                    if (t.status <= 0)
881 <                        q = t;
882 <            }
883 <            if (q != null && (w = q.thread) != null)
884 <                U.unpark(w);
885 <        }
886 <    }
887 <
888 <    private void writerPrefSignal() {
889 <        RNode p; WNode h, q; long s; Thread w;
890 <        if ((h = whead) != null && h.status != 0) {
891 <            U.compareAndSwapInt(h, STATUS, WAITING, 0);
942 >    /**
943 >     * Wakes up the successor of h (normally whead). This is normally
944 >     * just h.next, but may require traversal from wtail if next
945 >     * pointers are lagging. This may fail to wake up an acquiring
946 >     * thread when one or more have been cancelled, but the cancel
947 >     * methods themselves provide extra safeguards to ensure liveness.
948 >     */
949 >    private void release(WNode h) {
950 >        if (h != null) {
951 >            WNode q; Thread w;
952 >            U.compareAndSwapInt(h, WSTATUS, WAITING, 0);
953              if ((q = h.next) == null || q.status == CANCELLED) {
954                  for (WNode t = wtail; t != null && t != h; t = t.prev)
955                      if (t.status <= 0)
956                          q = t;
957              }
958 <            if (q != null && (w = q.thread) != null)
959 <                U.unpark(w);
960 <        }
961 <        else {
962 <            while ((p = rhead) != null && ((s = state) & WBIT) == 0L &&
963 <                   p.seq != (s & SBITS)) {
964 <                if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
965 <                    (w = p.waiter) != null &&
966 <                    U.compareAndSwapObject(p, WAITER, w, null))
967 <                    U.unpark(w);
958 >            if (q != null) {
959 >                for (WNode r = q;;) {  // release co-waiters too
960 >                    if ((w = r.thread) != null) {
961 >                        r.thread = null;
962 >                        U.unpark(w);
963 >                    }
964 >                    if ((r = q.cowait) == null)
965 >                        break;
966 >                    U.compareAndSwapObject(q, WCOWAIT, r, r.cowait);
967 >                }
968              }
969          }
970      }
971  
972      /**
973 <     * RNG for local spins. The first call from await{Read,Write}
913 <     * produces a thread-local value. Unless zero, subsequent calls
914 <     * use an xorShift to further reduce memory traffic.
915 <     */
916 <    private static int nextRandom(int r) {
917 <        if (r == 0)
918 <            return ThreadLocalRandom.current().nextInt();
919 <        r ^= r << 1; // xorshift
920 <        r ^= r >>> 3;
921 <        r ^= r << 10;
922 <        return r;
923 <    }
924 <
925 <    /**
926 <     * Possibly spins trying to obtain write lock, then enqueues and
927 <     * blocks while not head of write queue or cannot acquire lock,
928 <     * possibly spinning when at head; cancelling on timeout or
929 <     * interrupt.
973 >     * See above for explanation.
974       *
975       * @param interruptible true if should check interrupts and if so
976       * return INTERRUPTED
977       * @param deadline if nonzero, the System.nanoTime value to timeout
978       * at (and return zero)
979 +     * @return next state, or INTERRUPTED
980       */
981 <    private long awaitWrite(boolean interruptible, long deadline) {
982 <        WNode node = null;
983 <        for (int r = 0, spins = -1;;) {
984 <            WNode p; long s, next;
981 >    private long acquireWrite(boolean interruptible, long deadline) {
982 >        WNode node = null, p;
983 >        for (int spins = -1;;) { // spin while enqueuing
984 >            long s, ns;
985              if (((s = state) & ABITS) == 0L) {
986 <                if (U.compareAndSwapLong(this, STATE, s, next = s + WBIT))
987 <                    return next;
986 >                if (U.compareAndSwapLong(this, STATE, s, ns = s + WBIT))
987 >                    return ns;
988              }
944            else if (spins < 0)
945                spins = whead == wtail ? SPINS : 0;
989              else if (spins > 0) {
990 <                if ((r = nextRandom(r)) >= 0)
990 >                if (ThreadLocalRandom.current().nextInt() >= 0)
991                      --spins;
992              }
993              else if ((p = wtail) == null) { // initialize queue
994 <                if (U.compareAndSwapObject(this, WHEAD, null,
995 <                                           new WNode(null, null)))
996 <                    wtail = whead;
994 >                WNode h = new WNode(WMODE, null);
995 >                if (U.compareAndSwapObject(this, WHEAD, null, h))
996 >                    wtail = h;
997              }
998 +            else if (spins < 0)
999 +                spins = (p == whead) ? SPINS : 0;
1000              else if (node == null)
1001 <                node = new WNode(Thread.currentThread(), p);
1001 >                node = new WNode(WMODE, p);
1002              else if (node.prev != p)
1003                  node.prev = p;
1004              else if (U.compareAndSwapObject(this, WTAIL, p, node)) {
1005                  p.next = node;
1006 <                for (int headSpins = SPINS;;) {
1007 <                    WNode np, pp; int ps;
1008 <                    while ((np = node.prev) != p && np != null)
1009 <                        (p = np).next = node; // stale
1010 <                    if (p == whead) {
1011 <                        for (int k = headSpins;;) {
1012 <                            if (((s = state) & ABITS) == 0L) {
1013 <                                if (U.compareAndSwapLong(this, STATE,
1014 <                                                         s, next = s + WBIT)) {
1015 <                                    whead = node;
1016 <                                    node.thread = null;
1017 <                                    node.prev = null;
1018 <                                    return next;
1019 <                                }
1020 <                                break;
976 <                            }
977 <                            if ((r = nextRandom(r)) >= 0 && --k <= 0)
978 <                                break;
979 <                        }
980 <                        if (headSpins < MAX_HEAD_SPINS)
981 <                            headSpins <<= 1;
982 <                    }
983 <                    if ((ps = p.status) == 0)
984 <                        U.compareAndSwapInt(p, STATUS, 0, WAITING);
985 <                    else if (ps == CANCELLED) {
986 <                        if ((pp = p.prev) != null) {
987 <                            node.prev = pp;
988 <                            pp.next = node;
1006 >                break;
1007 >            }
1008 >        }
1009 >
1010 >        for (int spins = SPINS;;) {
1011 >            WNode np, pp; int ps; long s, ns; Thread w;
1012 >            while ((np = node.prev) != p && np != null)
1013 >                (p = np).next = node;   // stale
1014 >            if (whead == p) {
1015 >                for (int k = spins;;) { // spin at head
1016 >                    if (((s = state) & ABITS) == 0L) {
1017 >                        if (U.compareAndSwapLong(this, STATE, s, ns = s+WBIT)) {
1018 >                            whead = node;
1019 >                            node.prev = null;
1020 >                            return ns;
1021                          }
1022                      }
1023 <                    else {
1024 <                        long time; // 0 argument to park means no timeout
1025 <                        if (deadline == 0L)
1026 <                            time = 0L;
1027 <                        else if ((time = deadline - System.nanoTime()) <= 0L)
1028 <                            return cancelWriter(node, false);
1029 <                        if (node.prev == p && p.status == WAITING &&
1030 <                            (p != whead || (state & WBIT) != 0L)) // recheck
1031 <                            U.park(false, time);
1032 <                        if (interruptible && Thread.interrupted())
1033 <                            return cancelWriter(node, true);
1034 <                    }
1023 >                    else if (ThreadLocalRandom.current().nextInt() >= 0 &&
1024 >                             --k <= 0)
1025 >                        break;
1026 >                }
1027 >                if (spins < MAX_HEAD_SPINS)
1028 >                    spins <<= 1;
1029 >            }
1030 >            if ((ps = p.status) == 0)
1031 >                U.compareAndSwapInt(p, WSTATUS, 0, WAITING);
1032 >            else if (ps == CANCELLED) {
1033 >                if ((pp = p.prev) != null) {
1034 >                    node.prev = pp;
1035 >                    pp.next = node;
1036                  }
1037              }
1038 +            else {
1039 +                long time; // 0 argument to park means no timeout
1040 +                if (deadline == 0L)
1041 +                    time = 0L;
1042 +                else if ((time = deadline - System.nanoTime()) <= 0L)
1043 +                    return cancelWaiter(node, node, false);
1044 +                node.thread = Thread.currentThread();
1045 +                if (node.prev == p && p.status == WAITING && // recheck
1046 +                    (p != whead || (state & ABITS) != 0L))
1047 +                    U.park(false, time);
1048 +                node.thread = null;
1049 +                if (interruptible && Thread.interrupted())
1050 +                    return cancelWaiter(node, node, true);
1051 +            }
1052          }
1053      }
1054  
1055      /**
1056 <     * If node non-null, forces cancel status and unsplices from queue
1057 <     * if possible. This is a variant of cancellation methods in
1058 <     * AbstractQueuedSynchronizer (see its detailed explanation in AQS
1059 <     * internal documentation) that more conservatively wakes up other
1060 <     * threads that may have had their links changed, so as to preserve
1061 <     * liveness in the main signalling methods.
1056 >     * See above for explanation.
1057 >     *
1058 >     * @param interruptible true if should check interrupts and if so
1059 >     * return INTERRUPTED
1060 >     * @param deadline if nonzero, the System.nanoTime value to timeout
1061 >     * at (and return zero)
1062 >     * @return next state, or INTERRUPTED
1063       */
1064 <    private long cancelWriter(WNode node, boolean interrupted) {
1065 <        if (node != null) {
1066 <            node.thread = null;
1067 <            node.status = CANCELLED;
1068 <            for (WNode pred = node.prev; pred != null; ) {
1069 <                WNode succ, pp; Thread w;
1070 <                while ((succ = node.next) == null || succ.status == CANCELLED) {
1071 <                    WNode q = null;
1072 <                    for (WNode t = wtail; t != null && t != node; t = t.prev)
1073 <                        if (t.status != CANCELLED)
1074 <                            q = t;
1075 <                    if (succ == q ||
1076 <                        U.compareAndSwapObject(node, WNEXT, succ, succ = q)) {
1077 <                        if (succ == null && node == wtail)
1078 <                            U.compareAndSwapObject(this, WTAIL, node, pred);
1079 <                        break;
1064 >    private long acquireRead(boolean interruptible, long deadline) {
1065 >        WNode node = null, group = null, p;
1066 >        for (int spins = -1;;) {
1067 >            for (;;) {
1068 >                long s, m, ns; WNode h, q; Thread w; // anti-barging guard
1069 >                if (group == null && (h = whead) != null &&
1070 >                    (q = h.next) != null && q.mode != RMODE)
1071 >                    break;
1072 >                if ((m = (s = state) & ABITS) < RFULL ?
1073 >                    U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT) :
1074 >                    (m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) {
1075 >                    if (group != null) {  // help release others
1076 >                        for (WNode r = group;;) {
1077 >                            if ((w = r.thread) != null) {
1078 >                                r.thread = null;
1079 >                                U.unpark(w);
1080 >                            }
1081 >                            if ((r = group.cowait) == null)
1082 >                                break;
1083 >                            U.compareAndSwapObject(group, WCOWAIT, r, r.cowait);
1084 >                        }
1085                      }
1086 +                    return ns;
1087                  }
1088 <                if (pred.next == node)
1035 <                    U.compareAndSwapObject(pred, WNEXT, node, succ);
1036 <                if (succ != null && (w = succ.thread) != null)
1037 <                    U.unpark(w);
1038 <                if (pred.status != CANCELLED || (pp = pred.prev) == null)
1088 >                if (m >= WBIT)
1089                      break;
1040                node.prev = pp; // repeat for new pred
1041                U.compareAndSwapObject(pp, WNEXT, pred, succ);
1042                pred = pp;
1090              }
1091 <        }
1092 <        writerPrefSignal();
1093 <        return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L;
1094 <    }
1095 <
1096 <    /**
1097 <     * Waits for read lock or timeout or interrupt. The form of
1098 <     * awaitRead differs from awaitWrite mainly because it must
1099 <     * restart (with a new wait node) if the thread was unqueued and
1100 <     * unparked but could not the obtain lock.  We also need to help
1101 <     * with preference rules by not trying to acquire the lock before
1102 <     * enqueuing if there is a known waiting writer, but also helping
1103 <     * to release those threads that are still queued from the last
1104 <     * release.
1105 <     */
1106 <    private long awaitRead(long stamp, boolean interruptible, long deadline) {
1107 <        long seq = stamp & SBITS;
1108 <        RNode node = null;
1109 <        boolean queued = false;
1110 <        for (int r = 0, headSpins = SPINS, spins = -1;;) {
1111 <            long s, m, next; RNode p; WNode wh; Thread w;
1112 <            if ((m = (s = state) & ABITS) != WBIT &&
1113 <                ((s & SBITS) != seq || (wh = whead) == null ||
1114 <                 wh.status == 0)) {
1115 <                if (m < RFULL ?
1116 <                    U.compareAndSwapLong(this, STATE, s, next = s + RUNIT) :
1117 <                    (next = tryIncReaderOverflow(s)) != 0L) {
1118 <                    if (node != null && (w = node.waiter) != null)
1119 <                        U.compareAndSwapObject(node, WAITER, w, null);
1120 <                    if ((p = rhead) != null && (s & SBITS) != p.seq &&
1121 <                        U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1122 <                        (w = p.waiter) != null &&
1123 <                        U.compareAndSwapObject(p, WAITER, w, null))
1124 <                        U.unpark(w); // help signal other waiters
1125 <                    return next;
1091 >            if (spins > 0) {
1092 >                if (ThreadLocalRandom.current().nextInt() >= 0)
1093 >                    --spins;
1094 >            }
1095 >            else if ((p = wtail) == null) {
1096 >                WNode h = new WNode(WMODE, null);
1097 >                if (U.compareAndSwapObject(this, WHEAD, null, h))
1098 >                    wtail = h;
1099 >            }
1100 >            else if (spins < 0)
1101 >                spins = (p == whead) ? SPINS : 0;
1102 >            else if (node == null)
1103 >                node = new WNode(WMODE, p);
1104 >            else if (node.prev != p)
1105 >                node.prev = p;
1106 >            else if (p.mode == RMODE && p != whead) {
1107 >                WNode pp = p.prev;  // become co-waiter with group p
1108 >                if (pp != null && p == wtail &&
1109 >                    U.compareAndSwapObject(p, WCOWAIT,
1110 >                                           node.cowait = p.cowait, node)) {
1111 >                    node.thread = Thread.currentThread();
1112 >                    for (long time;;) {
1113 >                        if (interruptible && Thread.interrupted())
1114 >                            return cancelWaiter(node, p, true);
1115 >                        if (deadline == 0L)
1116 >                            time = 0L;
1117 >                        else if ((time = deadline - System.nanoTime()) <= 0L)
1118 >                            return cancelWaiter(node, p, false);
1119 >                        if (node.thread == null)
1120 >                            break;
1121 >                        if (p.prev != pp || p.status == CANCELLED ||
1122 >                            p == whead || p.prev != pp) {
1123 >                            node.thread = null;
1124 >                            break;
1125 >                        }
1126 >                        if (node.thread == null) // must recheck
1127 >                            break;
1128 >                        U.park(false, time);
1129 >                    }
1130 >                    group = p;
1131                  }
1132 +                node = null; // throw away
1133              }
1134 <            else if (m != WBIT && (p = rhead) != null &&
1135 <                     (s & SBITS) != p.seq) { // help release old readers
1136 <                if (U.compareAndSwapObject(this, RHEAD, p, p.next) &&
1084 <                    (w = p.waiter) != null &&
1085 <                    U.compareAndSwapObject(p, WAITER, w, null))
1086 <                    U.unpark(w);
1087 <            }
1088 <            else if (queued && node != null && node.waiter == null) {
1089 <                node = null;    // restart
1090 <                queued = false;
1091 <                spins = -1;
1092 <            }
1093 <            else if (spins < 0) {
1094 <                if (rhead != node)
1095 <                    spins = 0;
1096 <                else if ((spins = headSpins) < MAX_HEAD_SPINS && node != null)
1097 <                    headSpins <<= 1;
1134 >            else if (U.compareAndSwapObject(this, WTAIL, p, node)) {
1135 >                p.next = node;
1136 >                break;
1137              }
1138 <            else if (spins > 0) {
1139 <                if ((r = nextRandom(r)) >= 0)
1140 <                    --spins;
1138 >        }
1139 >
1140 >        for (int spins = SPINS;;) {
1141 >            WNode np, pp, r; int ps; long m, s, ns; Thread w;
1142 >            while ((np = node.prev) != p && np != null)
1143 >                (p = np).next = node;
1144 >            if (whead == p) {
1145 >                for (int k = spins;;) {
1146 >                    if ((m = (s = state) & ABITS) != WBIT) {
1147 >                        if (m < RFULL ?
1148 >                            U.compareAndSwapLong(this, STATE, s, ns = s + RUNIT):
1149 >                            (ns = tryIncReaderOverflow(s)) != 0L) {
1150 >                            whead = node;
1151 >                            node.prev = null;
1152 >                            while ((r = node.cowait) != null) {
1153 >                                if (U.compareAndSwapObject(node, WCOWAIT,
1154 >                                                           r, r.cowait) &&
1155 >                                    (w = r.thread) != null) {
1156 >                                    r.thread = null;
1157 >                                    U.unpark(w); // release co-waiter
1158 >                                }
1159 >                            }
1160 >                            return ns;
1161 >                        }
1162 >                    }
1163 >                    else if (ThreadLocalRandom.current().nextInt() >= 0 &&
1164 >                             --k <= 0)
1165 >                        break;
1166 >                }
1167 >                if (spins < MAX_HEAD_SPINS)
1168 >                    spins <<= 1;
1169              }
1170 <            else if (node == null)
1171 <                node = new RNode(seq, Thread.currentThread());
1172 <            else if (!queued) {
1173 <                if (queued = U.compareAndSwapObject(this, RHEAD,
1174 <                                                    node.next = rhead, node))
1175 <                    spins = -1;
1170 >            if ((ps = p.status) == 0)
1171 >                U.compareAndSwapInt(p, WSTATUS, 0, WAITING);
1172 >            else if (ps == CANCELLED) {
1173 >                if ((pp = p.prev) != null) {
1174 >                    node.prev = pp;
1175 >                    pp.next = node;
1176 >                }
1177              }
1178              else {
1179                  long time;
1180                  if (deadline == 0L)
1181                      time = 0L;
1182                  else if ((time = deadline - System.nanoTime()) <= 0L)
1183 <                    return cancelReader(node, false);
1184 <                if ((state & WBIT) != 0L && node.waiter != null) // recheck
1183 >                    return cancelWaiter(node, node, false);
1184 >                node.thread = Thread.currentThread();
1185 >                if (node.prev == p && p.status == WAITING &&
1186 >                    (p != whead || (state & ABITS) != WBIT))
1187                      U.park(false, time);
1188 +                node.thread = null;
1189                  if (interruptible && Thread.interrupted())
1190 <                    return cancelReader(node, true);
1190 >                    return cancelWaiter(node, node, true);
1191              }
1192          }
1193      }
1194  
1195      /**
1196 <     * If node non-null, forces cancel status and unsplices from queue
1197 <     * if possible, by traversing entire queue looking for cancelled
1198 <     * nodes.
1199 <     */
1200 <    private long cancelReader(RNode node, boolean interrupted) {
1201 <        Thread w;
1202 <        if (node != null && (w = node.waiter) != null &&
1203 <            U.compareAndSwapObject(node, WAITER, w, null)) {
1204 <            for (RNode pred = null, p = rhead; p != null;) {
1205 <                RNode q = p.next;
1206 <                if (p.waiter == null) {
1207 <                    if (pred == null) {
1208 <                        U.compareAndSwapObject(this, RHEAD, p, q);
1209 <                        p = rhead;
1210 <                    }
1211 <                    else {
1212 <                        U.compareAndSwapObject(pred, RNEXT, p, q);
1213 <                        p = pred.next;
1196 >     * If node non-null, forces cancel status and unsplices it from
1197 >     * queue if possible and wakes up any cowaiters (of the node, or
1198 >     * group, as applicable), and in any case helps release current
1199 >     * first waiter if lock is free. (Calling with null arguments
1200 >     * serves as a conditional form of release, which is not currently
1201 >     * needed but may be needed under possible future cancellation
1202 >     * policies). This is a variant of cancellation methods in
1203 >     * AbstractQueuedSynchronizer (see its detailed explanation in AQS
1204 >     * internal documentation).
1205 >     *
1206 >     * @param node if nonnull, the waiter
1207 >     * @param group, either node or the group node is cowaiting with
1208 >     * @param interrupted if already interrupted
1209 >     * @return INTERRUPTED if interrupted or Thread.interrupted, else zero
1210 >     */
1211 >    private long cancelWaiter(WNode node, WNode group, boolean interrupted) {
1212 >        if (node != null && group != null) {
1213 >            Thread w;
1214 >            node.status = CANCELLED;
1215 >            node.thread = null;
1216 >            // unsplice cancelled nodes from group
1217 >            for (WNode p = group, q; (q = p.cowait) != null;) {
1218 >                if (q.status == CANCELLED)
1219 >                    U.compareAndSwapObject(p, WNEXT, q, q.next);
1220 >                else
1221 >                    p = q;
1222 >            }
1223 >            if (group == node) {
1224 >                WNode r; // detach and wake up uncancelled co-waiters
1225 >                while ((r = node.cowait) != null) {
1226 >                    if (U.compareAndSwapObject(node, WCOWAIT, r, r.cowait) &&
1227 >                        (w = r.thread) != null) {
1228 >                        r.thread = null;
1229 >                        U.unpark(w);
1230                      }
1231                  }
1232 <                else {
1233 <                    pred = p;
1234 <                    p = q;
1232 >                for (WNode pred = node.prev; pred != null; ) { // unsplice
1233 >                    WNode succ, pp;        // find valid successor
1234 >                    while ((succ = node.next) == null ||
1235 >                           succ.status == CANCELLED) {
1236 >                        WNode q = null;    // find successor the slow way
1237 >                        for (WNode t = wtail; t != null && t != node; t = t.prev)
1238 >                            if (t.status != CANCELLED)
1239 >                                q = t;     // don't link if succ cancelled
1240 >                        if (succ == q ||   // ensure accurate successor
1241 >                            U.compareAndSwapObject(node, WNEXT,
1242 >                                                   succ, succ = q)) {
1243 >                            if (succ == null && node == wtail)
1244 >                                U.compareAndSwapObject(this, WTAIL, node, pred);
1245 >                            break;
1246 >                        }
1247 >                    }
1248 >                    if (pred.next == node) // unsplice pred link
1249 >                        U.compareAndSwapObject(pred, WNEXT, node, succ);
1250 >                    if (succ != null && (w = succ.thread) != null) {
1251 >                        succ.thread = null;
1252 >                        U.unpark(w);       // wake up succ to observe new pred
1253 >                    }
1254 >                    if (pred.status != CANCELLED || (pp = pred.prev) == null)
1255 >                        break;
1256 >                    node.prev = pp;        // repeat if new pred wrong/cancelled
1257 >                    U.compareAndSwapObject(pp, WNEXT, pred, succ);
1258 >                    pred = pp;
1259                  }
1260              }
1261          }
1262 <        readerPrefSignal();
1262 >        WNode h; // Possibly release first waiter
1263 >        while ((h = whead) != null) {
1264 >            long s; WNode q; // similar to release() but check eligibility
1265 >            if ((q = h.next) == null || q.status == CANCELLED) {
1266 >                for (WNode t = wtail; t != null && t != h; t = t.prev)
1267 >                    if (t.status <= 0)
1268 >                        q = t;
1269 >            }
1270 >            if (h == whead) {
1271 >                if (q != null && h.status == 0 &&
1272 >                    ((s = state) & ABITS) != WBIT && // waiter is eligible
1273 >                    (s == 0L || q.mode == RMODE))
1274 >                    release(h);
1275 >                break;
1276 >            }
1277 >        }
1278          return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L;
1279      }
1280  
1281      // Unsafe mechanics
1282      private static final sun.misc.Unsafe U;
1283      private static final long STATE;
1158    private static final long RHEAD;
1284      private static final long WHEAD;
1285      private static final long WTAIL;
1161    private static final long RNEXT;
1286      private static final long WNEXT;
1287 <    private static final long WPREV;
1288 <    private static final long WAITER;
1165 <    private static final long STATUS;
1287 >    private static final long WSTATUS;
1288 >    private static final long WCOWAIT;
1289  
1290      static {
1291          try {
1292              U = getUnsafe();
1293              Class<?> k = StampedLock.class;
1171            Class<?> rk = RNode.class;
1294              Class<?> wk = WNode.class;
1295              STATE = U.objectFieldOffset
1296                  (k.getDeclaredField("state"));
1175            RHEAD = U.objectFieldOffset
1176                (k.getDeclaredField("rhead"));
1297              WHEAD = U.objectFieldOffset
1298                  (k.getDeclaredField("whead"));
1299              WTAIL = U.objectFieldOffset
1300                  (k.getDeclaredField("wtail"));
1301 <            RNEXT = U.objectFieldOffset
1182 <                (rk.getDeclaredField("next"));
1183 <            WAITER = U.objectFieldOffset
1184 <                (rk.getDeclaredField("waiter"));
1185 <            STATUS = U.objectFieldOffset
1301 >            WSTATUS = U.objectFieldOffset
1302                  (wk.getDeclaredField("status"));
1303              WNEXT = U.objectFieldOffset
1304                  (wk.getDeclaredField("next"));
1305 <            WPREV = U.objectFieldOffset
1306 <                (wk.getDeclaredField("prev"));
1305 >            WCOWAIT = U.objectFieldOffset
1306 >                (wk.getDeclaredField("cowait"));
1307  
1308          } catch (Exception e) {
1309              throw new Error(e);
# Line 1204 | Line 1320 | public class StampedLock implements java
1320      private static sun.misc.Unsafe getUnsafe() {
1321          try {
1322              return sun.misc.Unsafe.getUnsafe();
1323 <        } catch (SecurityException se) {
1324 <            try {
1325 <                return java.security.AccessController.doPrivileged
1326 <                    (new java.security
1327 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1328 <                        public sun.misc.Unsafe run() throws Exception {
1329 <                            java.lang.reflect.Field f = sun.misc
1330 <                                .Unsafe.class.getDeclaredField("theUnsafe");
1331 <                            f.setAccessible(true);
1332 <                            return (sun.misc.Unsafe) f.get(null);
1333 <                        }});
1334 <            } catch (java.security.PrivilegedActionException e) {
1335 <                throw new RuntimeException("Could not initialize intrinsics",
1336 <                                           e.getCause());
1337 <            }
1323 >        } catch (SecurityException tryReflectionInstead) {}
1324 >        try {
1325 >            return java.security.AccessController.doPrivileged
1326 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1327 >                public sun.misc.Unsafe run() throws Exception {
1328 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
1329 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
1330 >                        f.setAccessible(true);
1331 >                        Object x = f.get(null);
1332 >                        if (k.isInstance(x))
1333 >                            return k.cast(x);
1334 >                    }
1335 >                    throw new NoSuchFieldError("the Unsafe");
1336 >                }});
1337 >        } catch (java.security.PrivilegedActionException e) {
1338 >            throw new RuntimeException("Could not initialize intrinsics",
1339 >                                       e.getCause());
1340          }
1341      }
1224
1342   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines