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.17 by jsr166, Mon Oct 15 04:32:41 2012 UTC vs.
Revision 1.27 by jsr166, Mon Jan 14 19:00:01 2013 UTC

# Line 61 | Line 61 | import java.util.concurrent.TimeUnit;
61   * help reduce some of the code bloat that otherwise occurs in
62   * retry-based designs.
63   *
64 < * <p>StampedLocks are designed for use in a different (and generally
65 < * narrower) range of contexts than most other locks: They are not
66 < * reentrant, so locked bodies should not call other unknown methods
67 < * that may try to re-acquire locks (although you may pass a stamp to
68 < * other methods that can use or convert it). Unvalidated optimistic
69 < * read sections should further not call methods that are not known to
64 > * <p>StampedLocks are designed for use as internal utilities in the
65 > * development of thread-safe components. Their use relies on
66 > * knowledge of the internal properties of the data, objects, and
67 > * methods they are protecting.  They are not reentrant, so locked
68 > * bodies should not call other unknown methods that may try to
69 > * re-acquire locks (although you may pass a stamp to other methods
70 > * that can use or convert it).  The use of read lock modes relies on
71 > * the associated code sections being side-effect-free.  Unvalidated
72 > * optimistic read sections cannot call methods that are not known to
73   * tolerate potential inconsistencies.  Stamps use finite
74   * representations, and are not cryptographically secure (i.e., a
75   * valid stamp may be guessable). Stamp values may recycle after (no
# Line 122 | Line 125 | import java.util.concurrent.TimeUnit;
125   *   }
126   *
127   *   double distanceFromOriginV2() { // combines code paths
128 + *     double currentX = 0.0, currentY = 0.0;
129   *     for (long stamp = sl.tryOptimisticRead(); ; stamp = sl.readLock()) {
126 *       double currentX, currentY;
130   *       try {
131   *         currentX = x;
132   *         currentY = y;
133   *       } finally {
134   *         if (sl.tryConvertToOptimisticRead(stamp) != 0L) // unlock or validate
135 < *           return Math.sqrt(currentX * currentX + currentY * currentY);
135 > *           break;
136   *       }
137   *     }
138 + *     return Math.sqrt(currentX * currentX + currentY * currentY);
139   *   }
140   *
141   *   void moveIfAtOrigin(double newX, double newY) { // upgrade
# Line 139 | Line 143 | import java.util.concurrent.TimeUnit;
143   *     long stamp = sl.readLock();
144   *     try {
145   *       while (x == 0.0 && y == 0.0) {
146 < *         long ws = tryConvertToWriteLock(stamp);
146 > *         long ws = sl.tryConvertToWriteLock(stamp);
147   *         if (ws != 0L) {
148   *           stamp = ws;
149   *           x = newX;
# Line 152 | Line 156 | import java.util.concurrent.TimeUnit;
156   *         }
157   *       }
158   *     } finally {
159 < *        sl.unlock(stamp);
159 > *       sl.unlock(stamp);
160   *     }
161   *   }
162   * }}</pre>
# Line 222 | Line 226 | public class StampedLock implements java
226       * threads.  Both await methods use a similar spin strategy: If
227       * the associated queue appears to be empty, then the thread
228       * spin-waits up to SPINS times (where each iteration decreases
229 <     * spin count with 50% probablility) before enqueing, and then, if
229 >     * spin count with 50% probability) before enqueuing, 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
# Line 248 | Line 252 | public class StampedLock implements java
252       * be subject to future improvements.
253       */
254  
255 +    private static final long serialVersionUID = -6001602636862214147L;
256 +
257      /** Number of processors, for spin control */
258      private static final int NCPU = Runtime.getRuntime().availableProcessors();
259  
# Line 511 | Line 517 | public class StampedLock implements java
517      }
518  
519      /**
520 <     * Returns true if the lock has not been exclusively held since
521 <     * issuance of the given stamp. Always returns false if the stamp
522 <     * is zero. Always returns true if the stamp represents a
520 >     * Returns true if the lock has not been exclusively acquired
521 >     * since issuance of the given stamp. Always returns false if the
522 >     * stamp is zero. Always returns true if the stamp represents a
523       * currently held lock.
524       *
525 <     * @return true if the lock has not been exclusively held since
526 <     * issuance of the given stamp; else false
525 >     * @return true if the lock has not been exclusively acquired
526 >     * since issuance of the given stamp; else false
527       */
528      public boolean validate(long stamp) {
529 +        // See above about current use of getLongVolatile here
530          return (stamp & SBITS) == (U.getLongVolatile(this, STATE) & SBITS);
531      }
532  
# Line 629 | Line 636 | public class StampedLock implements java
636                      break;
637                  return stamp;
638              }
639 <            else if (m == RUNIT && a != 0L && a < WBIT) {
639 >            else if (m == RUNIT && a != 0L) {
640                  if (U.compareAndSwapLong(this, STATE, s,
641                                           next = s - RUNIT + WBIT))
642                      return next;
# Line 667 | Line 674 | public class StampedLock implements java
674              else if (m == WBIT) {
675                  if (a != m)
676                      break;
677 <                next = state = s + (WBIT + RUNIT);
677 >                state = next = s + (WBIT + RUNIT);
678                  readerPrefSignal();
679                  return next;
680              }
# Line 775 | Line 782 | public class StampedLock implements java
782       * @return true if the lock is currently held non-exclusively
783       */
784      public boolean isReadLocked() {
785 <        long m;
779 <        return (m = state & ABITS) > 0L && m < WBIT;
785 >        return (state & RBITS) != 0L;
786      }
787  
788      private void readObject(java.io.ObjectInputStream s)
# Line 792 | Line 798 | public class StampedLock implements java
798       * access bits value to RBITS, indicating hold of spinlock,
799       * then updating, then releasing.
800       *
801 <     * @param stamp, assumed that (stamp & ABITS) >= RFULL
801 >     * @param s, assumed that (s & ABITS) >= RFULL
802       * @return new stamp on success, else zero
803       */
804      private long tryIncReaderOverflow(long s) {
# Line 812 | Line 818 | public class StampedLock implements java
818      /**
819       * Tries to decrement readerOverflow.
820       *
821 <     * @param stamp, assumed that (stamp & ABITS) >= RFULL
821 >     * @param s, assumed that (s & ABITS) >= RFULL
822       * @return new stamp on success, else zero
823       */
824      private long tryDecReaderOverflow(long s) {
# Line 868 | Line 874 | public class StampedLock implements java
874                  U.compareAndSwapObject(p, WAITER, w, null))
875                  U.unpark(w);
876          }
877 <        if (!readers && (state & ABITS) == 0L &&
878 <            (h = whead) != null && h.status != 0) {
877 >        if (!readers && (h = whead) != null && h.status != 0 &&
878 >            (state & ABITS) == 0L) {
879              U.compareAndSwapInt(h, STATUS, WAITING, 0);
880              if ((q = h.next) == null || q.status == CANCELLED) {
875                q = null;
881                  for (WNode t = wtail; t != null && t != h; t = t.prev)
882                      if (t.status <= 0)
883                          q = t;
# Line 887 | Line 892 | public class StampedLock implements java
892          if ((h = whead) != null && h.status != 0) {
893              U.compareAndSwapInt(h, STATUS, WAITING, 0);
894              if ((q = h.next) == null || q.status == CANCELLED) {
890                q = null;
895                  for (WNode t = wtail; t != null && t != h; t = t.prev)
896                      if (t.status <= 0)
897                          q = t;
# Line 957 | Line 961 | public class StampedLock implements java
961              else if (U.compareAndSwapObject(this, WTAIL, p, node)) {
962                  p.next = node;
963                  for (int headSpins = SPINS;;) {
964 <                    WNode np; int ps;
965 <                    if ((np = node.prev) != p && np != null &&
966 <                        (p = np).next != node)
963 <                        p.next = node; // stale
964 >                    WNode np, pp; int ps;
965 >                    while ((np = node.prev) != p && np != null)
966 >                        (p = np).next = node; // stale
967                      if (p == whead) {
968                          for (int k = headSpins;;) {
969                              if (((s = state) & ABITS) == 0L) {
# Line 981 | Line 984 | public class StampedLock implements java
984                      }
985                      if ((ps = p.status) == 0)
986                          U.compareAndSwapInt(p, STATUS, 0, WAITING);
987 <                    else if (ps == CANCELLED)
988 <                        node.prev = p.prev;
987 >                    else if (ps == CANCELLED) {
988 >                        if ((pp = p.prev) != null) {
989 >                            node.prev = pp;
990 >                            pp.next = node;
991 >                        }
992 >                    }
993                      else {
994                          long time; // 0 argument to park means no timeout
995                          if (deadline == 0L)
# Line 990 | Line 997 | public class StampedLock implements java
997                          else if ((time = deadline - System.nanoTime()) <= 0L)
998                              return cancelWriter(node, false);
999                          if (node.prev == p && p.status == WAITING &&
1000 <                            (p != whead || (state & WBIT) != 0L)) { // recheck
1000 >                            (p != whead || (state & ABITS) != 0L)) // recheck
1001                              U.park(false, time);
1002 <                            if (interruptible && Thread.interrupted())
1003 <                                return cancelWriter(node, true);
997 <                        }
1002 >                        if (interruptible && Thread.interrupted())
1003 >                            return cancelWriter(node, true);
1004                      }
1005                  }
1006              }
# Line 1003 | Line 1009 | public class StampedLock implements java
1009  
1010      /**
1011       * If node non-null, forces cancel status and unsplices from queue
1012 <     * if possible. This is a streamlined variant of cancellation
1013 <     * methods in AbstractQueuedSynchronizer that includes a detailed
1014 <     * explanation.
1012 >     * if possible. This is a variant of cancellation methods in
1013 >     * AbstractQueuedSynchronizer (see its detailed explanation in AQS
1014 >     * internal documentation) that more conservatively wakes up other
1015 >     * threads that may have had their links changed, so as to preserve
1016 >     * liveness in the main signalling methods.
1017       */
1018      private long cancelWriter(WNode node, boolean interrupted) {
1019 <        WNode pred;
1012 <        if (node != null && (pred = node.prev) != null) {
1013 <            WNode pp;
1019 >        if (node != null) {
1020              node.thread = null;
1015            while (pred.status == CANCELLED && (pp = pred.prev) != null)
1016                pred = node.prev = pp;
1017            WNode predNext = pred.next;
1021              node.status = CANCELLED;
1022 <            if (predNext != null) {
1023 <                Thread w;
1024 <                WNode succ = node.next;
1025 <                if (succ == null || succ.status == CANCELLED) {
1023 <                    succ = null;
1022 >            for (WNode pred = node.prev; pred != null; ) {
1023 >                WNode succ, pp; Thread w;
1024 >                while ((succ = node.next) == null || succ.status == CANCELLED) {
1025 >                    WNode q = null;
1026                      for (WNode t = wtail; t != null && t != node; t = t.prev)
1027 <                        if (t.status <= 0)
1028 <                            succ = t;
1029 <                    if (succ == null && node == wtail)
1030 <                        U.compareAndSwapObject(this, WTAIL, node, pred);
1027 >                        if (t.status != CANCELLED)
1028 >                            q = t;
1029 >                    if (succ == q ||
1030 >                        U.compareAndSwapObject(node, WNEXT, succ, succ = q)) {
1031 >                        if (succ == null && node == wtail)
1032 >                            U.compareAndSwapObject(this, WTAIL, node, pred);
1033 >                        break;
1034 >                    }
1035                  }
1036 <                U.compareAndSwapObject(pred, WNEXT, predNext, succ);
1036 >                if (pred.next == node)
1037 >                    U.compareAndSwapObject(pred, WNEXT, node, succ);
1038                  if (succ != null && (w = succ.thread) != null)
1039                      U.unpark(w);
1040 +                if (pred.status != CANCELLED || (pp = pred.prev) == null)
1041 +                    break;
1042 +                node.prev = pp; // repeat for new pred
1043 +                U.compareAndSwapObject(pp, WNEXT, pred, succ);
1044 +                pred = pp;
1045              }
1046          }
1047          writerPrefSignal();
# Line 1103 | Line 1115 | public class StampedLock implements java
1115                      time = 0L;
1116                  else if ((time = deadline - System.nanoTime()) <= 0L)
1117                      return cancelReader(node, false);
1118 <                if ((state & WBIT) != 0L && node.waiter != null) { // recheck
1118 >                if ((state & WBIT) != 0L && node.waiter != null) // recheck
1119                      U.park(false, time);
1120 <                    if (interruptible && Thread.interrupted())
1121 <                        return cancelReader(node, true);
1110 <                }
1120 >                if (interruptible && Thread.interrupted())
1121 >                    return cancelReader(node, true);
1122              }
1123          }
1124      }
# Line 1195 | Line 1206 | public class StampedLock implements java
1206      private static sun.misc.Unsafe getUnsafe() {
1207          try {
1208              return sun.misc.Unsafe.getUnsafe();
1209 <        } catch (SecurityException se) {
1210 <            try {
1211 <                return java.security.AccessController.doPrivileged
1212 <                    (new java.security
1213 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1214 <                        public sun.misc.Unsafe run() throws Exception {
1215 <                            java.lang.reflect.Field f = sun.misc
1216 <                                .Unsafe.class.getDeclaredField("theUnsafe");
1217 <                            f.setAccessible(true);
1218 <                            return (sun.misc.Unsafe) f.get(null);
1219 <                        }});
1220 <            } catch (java.security.PrivilegedActionException e) {
1221 <                throw new RuntimeException("Could not initialize intrinsics",
1222 <                                           e.getCause());
1223 <            }
1209 >        } catch (SecurityException tryReflectionInstead) {}
1210 >        try {
1211 >            return java.security.AccessController.doPrivileged
1212 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1213 >                public sun.misc.Unsafe run() throws Exception {
1214 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
1215 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
1216 >                        f.setAccessible(true);
1217 >                        Object x = f.get(null);
1218 >                        if (k.isInstance(x))
1219 >                            return k.cast(x);
1220 >                    }
1221 >                    throw new NoSuchFieldError("the Unsafe");
1222 >                }});
1223 >        } catch (java.security.PrivilegedActionException e) {
1224 >            throw new RuntimeException("Could not initialize intrinsics",
1225 >                                       e.getCause());
1226          }
1227      }
1215
1228   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines