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.31 by dl, Thu Jan 24 21:35:03 2013 UTC vs.
Revision 1.37 by jsr166, Sun Jul 14 19:55:05 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166e;
8
9 import java.util.concurrent.ThreadLocalRandom;
8   import java.util.concurrent.TimeUnit;
9   import java.util.concurrent.locks.Lock;
10   import java.util.concurrent.locks.Condition;
# Line 40 | Line 38 | import java.util.concurrent.locks.LockSu
38   *  <li><b>Optimistic Reading.</b> Method {@link #tryOptimisticRead}
39   *   returns a non-zero stamp only if the lock is not currently held
40   *   in write mode. Method {@link #validate} returns true if the lock
41 < *   has not since been acquired in write mode. This mode can be
42 < *   thought of as an extremely weak version of a read-lock, that can
43 < *   be broken by a writer at any time.  The use of optimistic mode
44 < *   for short read-only code segments often reduces contention and
45 < *   improves throughput.  However, its use is inherently fragile.
46 < *   Optimistic read sections should only read fields and hold them in
47 < *   local variables for later use after validation. Fields read while
48 < *   in optimistic mode may be wildly inconsistent, so usage applies
49 < *   only when you are familiar enough with data representations to
50 < *   check consistency and/or repeatedly invoke method {@code
51 < *   validate()}.  For example, such steps are typically required when
52 < *   first reading an object or array reference, and then accessing
53 < *   one of its fields, elements or methods. </li>
41 > *   has not been acquired in write mode since obtaining a given
42 > *   stamp.  This mode can be thought of as an extremely weak version
43 > *   of a read-lock, that can be broken by a writer at any time.  The
44 > *   use of optimistic mode for short read-only code segments often
45 > *   reduces contention and improves throughput.  However, its use is
46 > *   inherently fragile.  Optimistic read sections should only read
47 > *   fields and hold them in local variables for later use after
48 > *   validation. Fields read while in optimistic mode may be wildly
49 > *   inconsistent, so usage applies only when you are familiar enough
50 > *   with data representations to check consistency and/or repeatedly
51 > *   invoke method {@code validate()}.  For example, such steps are
52 > *   typically required when first reading an object or array
53 > *   reference, and then accessing one of its fields, elements or
54 > *   methods. </li>
55   *
56   * </ul>
57   *
# Line 118 | Line 117 | import java.util.concurrent.locks.LockSu
117   *     }
118   *   }
119   *
120 < *   double distanceFromOriginV1() { // A read-only method
121 < *     long stamp;
122 < *     if ((stamp = sl.tryOptimisticRead()) != 0L) { // optimistic
123 < *       double currentX = x;
124 < *       double currentY = y;
125 < *       if (sl.validate(stamp))
126 < *         return Math.sqrt(currentX * currentX + currentY * currentY);
127 < *     }
128 < *     stamp = sl.readLock(); // fall back to read lock
129 < *     try {
130 < *       double currentX = x;
132 < *       double currentY = y;
133 < *         return Math.sqrt(currentX * currentX + currentY * currentY);
134 < *     } finally {
135 < *       sl.unlockRead(stamp);
136 < *     }
137 < *   }
138 < *
139 < *   double distanceFromOriginV2() { // combines code paths
140 < *     double currentX = 0.0, currentY = 0.0;
141 < *     for (long stamp = sl.tryOptimisticRead(); ; stamp = sl.readLock()) {
142 < *       try {
143 < *         currentX = x;
144 < *         currentY = y;
145 < *       } finally {
146 < *         if (sl.tryConvertToOptimisticRead(stamp) != 0L) // unlock or validate
147 < *           break;
148 < *       }
120 > *   double distanceFromOrigin() { // A read-only method
121 > *     long stamp = sl.tryOptimisticRead();
122 > *     double currentX = x, currentY = y;
123 > *     if (!sl.validate(stamp)) {
124 > *        stamp = sl.readLock();
125 > *        try {
126 > *          currentX = x;
127 > *          currentY = y;
128 > *        } finally {
129 > *           sl.unlockRead(stamp);
130 > *        }
131   *     }
132   *     return Math.sqrt(currentX * currentX + currentY * currentY);
133   *   }
# Line 252 | Line 234 | public class StampedLock implements java
234       * motivation to further spread out contended locations, but might
235       * be subject to future improvements.
236       */
237 +
238      private static final long serialVersionUID = -6001602636862214147L;
239  
240      /** Number of processors, for spin control */
# Line 356 | Line 339 | public class StampedLock implements java
339       * Behavior under timeout and interruption matches that specified
340       * for method {@link Lock#tryLock(long,TimeUnit)}.
341       *
342 +     * @param time the maximum time to wait for the lock
343 +     * @param unit the time unit of the {@code time} argument
344       * @return a stamp that can be used to unlock or convert mode,
345       * or zero if the lock is not available
346       * @throws InterruptedException if the current thread is interrupted
# Line 435 | Line 420 | public class StampedLock implements java
420       * Behavior under timeout and interruption matches that specified
421       * for method {@link Lock#tryLock(long,TimeUnit)}.
422       *
423 +     * @param time the maximum time to wait for the lock
424 +     * @param unit the time unit of the {@code time} argument
425       * @return a stamp that can be used to unlock or convert mode,
426       * or zero if the lock is not available
427       * @throws InterruptedException if the current thread is interrupted
# Line 442 | Line 429 | public class StampedLock implements java
429       */
430      public long tryReadLock(long time, TimeUnit unit)
431          throws InterruptedException {
432 <        long next, deadline;
432 >        long s, m, next, deadline;
433          long nanos = unit.toNanos(time);
434          if (!Thread.interrupted()) {
435 <            if ((next = tryReadLock()) != 0L)
436 <                return next;
435 >            if ((m = (s = state) & ABITS) != WBIT) {
436 >                if (m < RFULL) {
437 >                    if (U.compareAndSwapLong(this, STATE, s, next = s + RUNIT))
438 >                        return next;
439 >                }
440 >                else if ((next = tryIncReaderOverflow(s)) != 0L)
441 >                    return next;
442 >            }
443              if (nanos <= 0L)
444                  return 0L;
445              if ((deadline = System.nanoTime() + nanos) == 0L)
# Line 490 | Line 483 | public class StampedLock implements java
483       * Returns true if the lock has not been exclusively acquired
484       * since issuance of the given stamp. Always returns false if the
485       * stamp is zero. Always returns true if the stamp represents a
486 <     * currently held lock.
486 >     * currently held lock. Invoking this method with a value not
487 >     * obtained from {@link #tryOptimisticRead} or a locking method
488 >     * for this lock has no defined effect or result.
489       *
490 <     * @return true if the lock has not been exclusively acquired
490 >     * @param stamp a stamp
491 >     * @return {@code true} if the lock has not been exclusively acquired
492       * since issuance of the given stamp; else false
493       */
494      public boolean validate(long stamp) {
# Line 705 | Line 701 | public class StampedLock implements java
701       * stamp value. This method may be useful for recovery after
702       * errors.
703       *
704 <     * @return true if the lock was held, else false
704 >     * @return {@code true} if the lock was held, else false
705       */
706      public boolean tryUnlockWrite() {
707          long s; WNode h;
# Line 723 | Line 719 | public class StampedLock implements java
719       * requiring a stamp value. This method may be useful for recovery
720       * after errors.
721       *
722 <     * @return true if the read lock was held, else false
722 >     * @return {@code true} if the read lock was held, else false
723       */
724      public boolean tryUnlockRead() {
725          long s, m; WNode h;
# Line 741 | Line 737 | public class StampedLock implements java
737          return false;
738      }
739  
740 +    // status monitoring methods
741 +
742 +    /**
743 +     * Returns combined state-held and overflow read count for given
744 +     * state s.
745 +     */
746 +    private int getReadLockCount(long s) {
747 +        long readers;
748 +        if ((readers = s & RBITS) >= RFULL)
749 +            readers = RFULL + readerOverflow;
750 +        return (int) readers;
751 +    }
752 +
753      /**
754 <     * Returns true if the lock is currently held exclusively.
754 >     * Returns {@code true} if the lock is currently held exclusively.
755       *
756 <     * @return true if the lock is currently held exclusively
756 >     * @return {@code true} if the lock is currently held exclusively
757       */
758      public boolean isWriteLocked() {
759          return (state & WBIT) != 0L;
760      }
761  
762      /**
763 <     * Returns true if the lock is currently held non-exclusively.
763 >     * Returns {@code true} if the lock is currently held non-exclusively.
764       *
765 <     * @return true if the lock is currently held non-exclusively
765 >     * @return {@code true} if the lock is currently held non-exclusively
766       */
767      public boolean isReadLocked() {
768          return (state & RBITS) != 0L;
769      }
770  
771 <    private void readObject(java.io.ObjectInputStream s)
772 <        throws java.io.IOException, ClassNotFoundException {
773 <        s.defaultReadObject();
774 <        state = ORIGIN; // reset to unlocked state
771 >    /**
772 >     * Queries the number of read locks held for this lock. This
773 >     * method is designed for use in monitoring system state, not for
774 >     * synchronization control.
775 >     * @return the number of read locks held
776 >     */
777 >    public int getReadLockCount() {
778 >        return getReadLockCount(state);
779      }
780  
781      /**
782 +     * Returns a string identifying this lock, as well as its lock
783 +     * state.  The state, in brackets, includes the String {@code
784 +     * "Unlocked"} or the String {@code "Write-locked"} or the String
785 +     * {@code "Read-locks:"} followed by the current number of
786 +     * read-locks held.
787 +     *
788 +     * @return a string identifying this lock, as well as its lock state
789 +     */
790 +    public String toString() {
791 +        long s = state;
792 +        return super.toString() +
793 +            ((s & ABITS) == 0L ? "[Unlocked]" :
794 +             (s & WBIT) != 0L ? "[Write-locked]" :
795 +             "[Read-locks:" + getReadLockCount(s) + "]");
796 +    }
797 +
798 +    // views
799 +
800 +    /**
801       * Returns a plain {@link Lock} view of this StampedLock in which
802       * the {@link Lock#lock} method is mapped to {@link #readLock},
803       * and similarly for other methods. The returned Lock does not
# Line 879 | Line 911 | public class StampedLock implements java
911          }
912      }
913  
914 +    private void readObject(java.io.ObjectInputStream s)
915 +        throws java.io.IOException, ClassNotFoundException {
916 +        s.defaultReadObject();
917 +        state = ORIGIN; // reset to unlocked state
918 +    }
919 +
920      // internals
921  
922      /**
# Line 886 | Line 924 | public class StampedLock implements java
924       * access bits value to RBITS, indicating hold of spinlock,
925       * then updating, then releasing.
926       *
927 <     * @param s, assumed that (s & ABITS) >= RFULL
927 >     * @param s a reader overflow stamp: (s & ABITS) >= RFULL
928       * @return new stamp on success, else zero
929       */
930      private long tryIncReaderOverflow(long s) {
931 +        // assert (s & ABITS) >= RFULL;
932          if ((s & ABITS) == RFULL) {
933              if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
934                  ++readerOverflow;
# Line 906 | Line 945 | public class StampedLock implements java
945      /**
946       * Tries to decrement readerOverflow.
947       *
948 <     * @param s, assumed that (s & ABITS) >= RFULL
948 >     * @param s a reader overflow stamp: (s & ABITS) >= RFULL
949       * @return new stamp on success, else zero
950       */
951      private long tryDecReaderOverflow(long s) {
952 +        // assert (s & ABITS) >= RFULL;
953          if ((s & ABITS) == RFULL) {
954              if (U.compareAndSwapLong(this, STATE, s, s | RBITS)) {
955                  int r; long next;
# Line 929 | Line 969 | public class StampedLock implements java
969          return 0L;
970      }
971  
972 <    /*
972 >    /**
973       * Wakes up the successor of h (normally whead). This is normally
974       * just h.next, but may require traversal from wtail if next
975       * pointers are lagging. This may fail to wake up an acquiring
# Line 1030 | Line 1070 | public class StampedLock implements java
1070                  if (deadline == 0L)
1071                      time = 0L;
1072                  else if ((time = deadline - System.nanoTime()) <= 0L)
1073 <                    return cancelWaiter(node, null, false);
1074 <                node.thread = Thread.currentThread();
1073 >                    return cancelWaiter(node, node, false);
1074 >                Thread wt = Thread.currentThread();
1075 >                U.putObject(wt, PARKBLOCKER, this); // emulate LockSupport.park
1076 >                node.thread = wt;
1077                  if (node.prev == p && p.status == WAITING && // recheck
1078                      (p != whead || (state & ABITS) != 0L))
1079                      U.park(false, time);
1080                  node.thread = null;
1081 +                U.putObject(wt, PARKBLOCKER, null);
1082                  if (interruptible && Thread.interrupted())
1083 <                    return cancelWaiter(node, null, true);
1083 >                    return cancelWaiter(node, node, true);
1084              }
1085          }
1086      }
# Line 1100 | Line 1143 | public class StampedLock implements java
1143                                             node.cowait = p.cowait, node)) {
1144                      node.thread = Thread.currentThread();
1145                      for (long time;;) {
1103                        if (interruptible && Thread.interrupted())
1104                            return cancelWaiter(node, p, true);
1146                          if (deadline == 0L)
1147                              time = 0L;
1148                          else if ((time = deadline - System.nanoTime()) <= 0L)
# Line 1113 | Line 1154 | public class StampedLock implements java
1154                              node.thread = null;
1155                              break;
1156                          }
1157 +                        Thread wt = Thread.currentThread();
1158 +                        U.putObject(wt, PARKBLOCKER, this);
1159                          if (node.thread == null) // must recheck
1160                              break;
1161                          U.park(false, time);
1162 +                        U.putObject(wt, PARKBLOCKER, null);
1163 +                        if (interruptible && Thread.interrupted())
1164 +                            return cancelWaiter(node, p, true);
1165                      }
1166                      group = p;
1167                  }
# Line 1170 | Line 1216 | public class StampedLock implements java
1216                  if (deadline == 0L)
1217                      time = 0L;
1218                  else if ((time = deadline - System.nanoTime()) <= 0L)
1219 <                    return cancelWaiter(node, null, false);
1220 <                node.thread = Thread.currentThread();
1219 >                    return cancelWaiter(node, node, false);
1220 >                Thread wt = Thread.currentThread();
1221 >                U.putObject(wt, PARKBLOCKER, this);
1222 >                node.thread = wt;
1223                  if (node.prev == p && p.status == WAITING &&
1224                      (p != whead || (state & ABITS) != WBIT))
1225                      U.park(false, time);
1226                  node.thread = null;
1227 +                U.putObject(wt, PARKBLOCKER, null);
1228                  if (interruptible && Thread.interrupted())
1229 <                    return cancelWaiter(node, null, true);
1229 >                    return cancelWaiter(node, node, true);
1230 >            }
1231 >        }
1232 >    }
1233 >
1234 >    /**
1235 >     * If node non-null, forces cancel status and unsplices it from
1236 >     * queue if possible and wakes up any cowaiters (of the node, or
1237 >     * group, as applicable), and in any case helps release current
1238 >     * first waiter if lock is free. (Calling with null arguments
1239 >     * serves as a conditional form of release, which is not currently
1240 >     * needed but may be needed under possible future cancellation
1241 >     * policies). This is a variant of cancellation methods in
1242 >     * AbstractQueuedSynchronizer (see its detailed explanation in AQS
1243 >     * internal documentation).
1244 >     *
1245 >     * @param node if nonnull, the waiter
1246 >     * @param group either node or the group node is cowaiting with
1247 >     * @param interrupted if already interrupted
1248 >     * @return INTERRUPTED if interrupted or Thread.interrupted, else zero
1249 >     */
1250 >    private long cancelWaiter(WNode node, WNode group, boolean interrupted) {
1251 >        if (node != null && group != null) {
1252 >            Thread w;
1253 >            node.status = CANCELLED;
1254 >            node.thread = null;
1255 >            // unsplice cancelled nodes from group
1256 >            for (WNode p = group, q; (q = p.cowait) != null;) {
1257 >                if (q.status == CANCELLED)
1258 >                    U.compareAndSwapObject(p, WNEXT, q, q.next);
1259 >                else
1260 >                    p = q;
1261 >            }
1262 >            if (group == node) {
1263 >                WNode r; // detach and wake up uncancelled co-waiters
1264 >                while ((r = node.cowait) != null) {
1265 >                    if (U.compareAndSwapObject(node, WCOWAIT, r, r.cowait) &&
1266 >                        (w = r.thread) != null) {
1267 >                        r.thread = null;
1268 >                        U.unpark(w);
1269 >                    }
1270 >                }
1271 >                for (WNode pred = node.prev; pred != null; ) { // unsplice
1272 >                    WNode succ, pp;        // find valid successor
1273 >                    while ((succ = node.next) == null ||
1274 >                           succ.status == CANCELLED) {
1275 >                        WNode q = null;    // find successor the slow way
1276 >                        for (WNode t = wtail; t != null && t != node; t = t.prev)
1277 >                            if (t.status != CANCELLED)
1278 >                                q = t;     // don't link if succ cancelled
1279 >                        if (succ == q ||   // ensure accurate successor
1280 >                            U.compareAndSwapObject(node, WNEXT,
1281 >                                                   succ, succ = q)) {
1282 >                            if (succ == null && node == wtail)
1283 >                                U.compareAndSwapObject(this, WTAIL, node, pred);
1284 >                            break;
1285 >                        }
1286 >                    }
1287 >                    if (pred.next == node) // unsplice pred link
1288 >                        U.compareAndSwapObject(pred, WNEXT, node, succ);
1289 >                    if (succ != null && (w = succ.thread) != null) {
1290 >                        succ.thread = null;
1291 >                        U.unpark(w);       // wake up succ to observe new pred
1292 >                    }
1293 >                    if (pred.status != CANCELLED || (pp = pred.prev) == null)
1294 >                        break;
1295 >                    node.prev = pp;        // repeat if new pred wrong/cancelled
1296 >                    U.compareAndSwapObject(pp, WNEXT, pred, succ);
1297 >                    pred = pp;
1298 >                }
1299              }
1300          }
1301 +        WNode h; // Possibly release first waiter
1302 +        while ((h = whead) != null) {
1303 +            long s; WNode q; // similar to release() but check eligibility
1304 +            if ((q = h.next) == null || q.status == CANCELLED) {
1305 +                for (WNode t = wtail; t != null && t != h; t = t.prev)
1306 +                    if (t.status <= 0)
1307 +                        q = t;
1308 +            }
1309 +            if (h == whead) {
1310 +                if (q != null && h.status == 0 &&
1311 +                    ((s = state) & ABITS) != WBIT && // waiter is eligible
1312 +                    (s == 0L || q.mode == RMODE))
1313 +                    release(h);
1314 +                break;
1315 +            }
1316 +        }
1317 +        return (interrupted || Thread.interrupted()) ? INTERRUPTED : 0L;
1318 +    }
1319 +
1320 +    // Unsafe mechanics
1321 +    private static final sun.misc.Unsafe U;
1322 +    private static final long STATE;
1323 +    private static final long WHEAD;
1324 +    private static final long WTAIL;
1325 +    private static final long WNEXT;
1326 +    private static final long WSTATUS;
1327 +    private static final long WCOWAIT;
1328 +    private static final long PARKBLOCKER;
1329 +
1330 +    static {
1331 +        try {
1332 +            U = getUnsafe();
1333 +            Class<?> k = StampedLock.class;
1334 +            Class<?> wk = WNode.class;
1335 +            STATE = U.objectFieldOffset
1336 +                (k.getDeclaredField("state"));
1337 +            WHEAD = U.objectFieldOffset
1338 +                (k.getDeclaredField("whead"));
1339 +            WTAIL = U.objectFieldOffset
1340 +                (k.getDeclaredField("wtail"));
1341 +            WSTATUS = U.objectFieldOffset
1342 +                (wk.getDeclaredField("status"));
1343 +            WNEXT = U.objectFieldOffset
1344 +                (wk.getDeclaredField("next"));
1345 +            WCOWAIT = U.objectFieldOffset
1346 +                (wk.getDeclaredField("cowait"));
1347 +            Class<?> tk = Thread.class;
1348 +            PARKBLOCKER = U.objectFieldOffset
1349 +                (tk.getDeclaredField("parkBlocker"));
1350 +
1351 +        } catch (Exception e) {
1352 +            throw new Error(e);
1353 +        }
1354      }
1355  
1356      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines