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

Comparing jsr166/src/jsr166y/Phaser.java (file contents):
Revision 1.20 by jsr166, Sat Jul 25 00:34:00 2009 UTC vs.
Revision 1.26 by jsr166, Wed Aug 5 00:54:11 2009 UTC

# Line 32 | Line 32 | import java.util.concurrent.locks.LockSu
32   * zero, and advancing when all parties reach the barrier (wrapping
33   * around to zero after reaching {@code Integer.MAX_VALUE}).
34   *
35 < * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
36 < * Method {@code arriveAndAwaitAdvance} has effect analogous to
37 < * {@code CyclicBarrier.await}.  However, Phasers separate two
38 < * aspects of coordination, that may also be invoked independently:
35 > * <li> Like a {@code CyclicBarrier}, a phaser may be repeatedly
36 > * awaited.  Method {@link #arriveAndAwaitAdvance} has effect
37 > * analogous to {@link java.util.concurrent.CyclicBarrier#await
38 > * CyclicBarrier.await}.  However, phasers separate two aspects of
39 > * coordination, that may also be invoked independently:
40   *
41   * <ul>
42   *
43 < *   <li> Arriving at a barrier. Methods {@code arrive} and
44 < *       {@code arriveAndDeregister} do not block, but return
43 > *   <li> Arriving at a barrier. Methods {@link #arrive} and
44 > *       {@link #arriveAndDeregister} do not block, but return
45   *       the phase value current upon entry to the method.
46   *
47 < *   <li> Awaiting others. Method {@code awaitAdvance} requires an
47 > *   <li> Awaiting others. Method {@link #awaitAdvance} requires an
48   *       argument indicating the entry phase, and returns when the
49   *       barrier advances to a new phase.
50   * </ul>
# Line 51 | Line 52 | import java.util.concurrent.locks.LockSu
52   *
53   * <li> Barrier actions, performed by the task triggering a phase
54   * advance while others may be waiting, are arranged by overriding
55 < * method {@code onAdvance}, that also controls termination.
55 > * method {@link #onAdvance}, that also controls termination.
56   * Overriding this method may be used to similar but more flexible
57 < * effect as providing a barrier action to a CyclicBarrier.
57 > * effect as providing a barrier action to a {@code CyclicBarrier}.
58   *
59   * <li> Phasers may enter a <em>termination</em> state in which all
60   * actions immediately return without updating phaser state or waiting
61   * for advance, and indicating (via a negative phase value) that
62   * execution is complete.  Termination is triggered by executing the
63   * overridable {@code onAdvance} method that is invoked each time the
64 < * barrier is about to be tripped. When a Phaser is controlling an
64 > * barrier is about to be tripped. When a phaser is controlling an
65   * action with a fixed number of iterations, it is often convenient to
66   * override this method to cause termination when the current phase
67 < * number reaches a threshold. Method {@code forceTermination} is also
67 > * number reaches a threshold. Method {@link #forceTermination} is also
68   * available to abruptly release waiting threads and allow them to
69   * terminate.
70   *
# Line 75 | Line 76 | import java.util.concurrent.locks.LockSu
76   *
77   * <li> By default, {@code awaitAdvance} continues to wait even if
78   * the waiting thread is interrupted. And unlike the case in
79 < * CyclicBarriers, exceptions encountered while tasks wait
79 > * {@code CyclicBarrier}, exceptions encountered while tasks wait
80   * interruptibly or with timeout do not change the state of the
81   * barrier. If necessary, you can perform any associated recovery
82   * within handlers of those exceptions, often after invoking
# Line 87 | Line 88 | import java.util.concurrent.locks.LockSu
88   *
89   * <p><b>Sample usages:</b>
90   *
91 < * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
92 < * a one-shot action serving a variable number of parties. The typical
93 < * idiom is for the method setting this up to first register, then
94 < * start the actions, then deregister, as in:
91 > * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
92 > * to control a one-shot action serving a variable number of
93 > * parties. The typical idiom is for the method setting this up to
94 > * first register, then start the actions, then deregister, as in:
95   *
96   *  <pre> {@code
97   * void runTasks(List<Runnable> list) {
# Line 139 | Line 140 | import java.util.concurrent.locks.LockSu
140   *   phaser.arriveAndDeregister(); // deregister self, don't wait
141   * }}</pre>
142   *
143 < * <p> To create a set of tasks using a tree of Phasers,
143 > * <p>To create a set of tasks using a tree of phasers,
144   * you could use code of the following form, assuming a
145 < * Task class with a constructor accepting a Phaser that
145 > * Task class with a constructor accepting a phaser that
146   * it registers for upon construction:
147   *  <pre> {@code
148   * void build(Task[] actions, int lo, int hi, Phaser b) {
# Line 249 | Line 250 | public class Phaser {
250      private final Phaser parent;
251  
252      /**
253 <     * The root of Phaser tree. Equals this if not in a tree.  Used to
253 >     * The root of phaser tree. Equals this if not in a tree.  Used to
254       * support faster state push-down.
255       */
256      private final Phaser root;
# Line 300 | Line 301 | public class Phaser {
301      }
302  
303      /**
304 <     * Creates a new Phaser without any initially registered parties,
304 >     * Creates a new phaser without any initially registered parties,
305       * initial phase number 0, and no parent. Any thread using this
306 <     * Phaser will need to first register for it.
306 >     * phaser will need to first register for it.
307       */
308      public Phaser() {
309          this(null);
310      }
311  
312      /**
313 <     * Creates a new Phaser with the given numbers of registered
313 >     * Creates a new phaser with the given numbers of registered
314       * unarrived parties, initial phase number 0, and no parent.
315       *
316       * @param parties the number of parties required to trip barrier
# Line 321 | Line 322 | public class Phaser {
322      }
323  
324      /**
325 <     * Creates a new Phaser with the given parent, without any
325 >     * Creates a new phaser with the given parent, without any
326       * initially registered parties. If parent is non-null this phaser
327       * is registered with the parent and its initial phase number is
328       * the same as that of parent phaser.
# Line 341 | Line 342 | public class Phaser {
342      }
343  
344      /**
345 <     * Creates a new Phaser with the given parent and numbers of
345 >     * Creates a new phaser with the given parent and numbers of
346       * registered unarrived parties. If parent is non-null, this phaser
347       * is registered with the parent and its initial phase number is
348       * the same as that of parent phaser.
# Line 675 | Line 676 | public class Phaser {
676      }
677  
678      /**
679 <     * Returns the parent of this phaser, or null if none.
679 >     * Returns the parent of this phaser, or {@code null} if none.
680       *
681 <     * @return the parent of this phaser, or null if none
681 >     * @return the parent of this phaser, or {@code null} if none
682       */
683      public Phaser getParent() {
684          return parent;
# Line 706 | Line 707 | public class Phaser {
707       * Overridable method to perform an action upon phase advance, and
708       * to control termination. This method is invoked whenever the
709       * barrier is tripped (and thus all other waiting parties are
710 <     * dormant). If it returns true, then, rather than advance the
711 <     * phase number, this barrier will be set to a final termination
712 <     * state, and subsequent calls to {@code isTerminated} will
713 <     * return true.
710 >     * dormant). If it returns {@code true}, then, rather than advance
711 >     * the phase number, this barrier will be set to a final
712 >     * termination state, and subsequent calls to {@link #isTerminated}
713 >     * will return true.
714       *
715 <     * <p> The default version returns true when the number of
715 >     * <p>The default version returns {@code true} when the number of
716       * registered parties is zero. Normally, overrides that arrange
717       * termination for other reasons should also preserve this
718       * property.
719       *
720 <     * <p> You may override this method to perform an action with side
720 >     * <p>You may override this method to perform an action with side
721       * effects visible to participating tasks, but it is in general
722       * only sensible to do so in designs where all parties register
723 <     * before any arrive, and all {@code awaitAdvance} at each phase.
723 >     * before any arrive, and all {@link #awaitAdvance} at each phase.
724       * Otherwise, you cannot ensure lack of interference. In
725       * particular, this method may be invoked more than once per
726       * transition if other parties successfully register while the
# Line 930 | Line 931 | public class Phaser {
931          return p;
932      }
933  
934 <    // Unsafe mechanics for jsr166y 3rd party package.
934 >    // Unsafe mechanics
935 >
936 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
937 >    private static final long stateOffset =
938 >        objectFieldOffset("state", Phaser.class);
939 >
940 >    private final boolean casState(long cmp, long val) {
941 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
942 >    }
943 >
944 >    private static long objectFieldOffset(String field, Class<?> klazz) {
945 >        try {
946 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
947 >        } catch (NoSuchFieldException e) {
948 >            // Convert Exception to corresponding Error
949 >            NoSuchFieldError error = new NoSuchFieldError(field);
950 >            error.initCause(e);
951 >            throw error;
952 >        }
953 >    }
954 >
955 >    /**
956 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
957 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
958 >     * into a jdk.
959 >     *
960 >     * @return a sun.misc.Unsafe
961 >     */
962      private static sun.misc.Unsafe getUnsafe() {
963          try {
964              return sun.misc.Unsafe.getUnsafe();
965          } catch (SecurityException se) {
966              try {
967                  return java.security.AccessController.doPrivileged
968 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
968 >                    (new java.security
969 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
970                          public sun.misc.Unsafe run() throws Exception {
971 <                            return getUnsafeByReflection();
971 >                            java.lang.reflect.Field f = sun.misc
972 >                                .Unsafe.class.getDeclaredField("theUnsafe");
973 >                            f.setAccessible(true);
974 >                            return (sun.misc.Unsafe) f.get(null);
975                          }});
976              } catch (java.security.PrivilegedActionException e) {
977                  throw new RuntimeException("Could not initialize intrinsics",
# Line 947 | Line 979 | public class Phaser {
979              }
980          }
981      }
950
951    private static sun.misc.Unsafe getUnsafeByReflection()
952            throws NoSuchFieldException, IllegalAccessException {
953        java.lang.reflect.Field f =
954            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
955        f.setAccessible(true);
956        return (sun.misc.Unsafe) f.get(null);
957    }
958
959    private static long fieldOffset(String fieldName, Class<?> klazz) {
960        try {
961            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
962        } catch (NoSuchFieldException e) {
963            // Convert Exception to Error
964            NoSuchFieldError error = new NoSuchFieldError(fieldName);
965            error.initCause(e);
966            throw error;
967        }
968    }
969
970    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
971    static final long stateOffset =
972        fieldOffset("state", Phaser.class);
973
974    final boolean casState(long cmp, long val) {
975        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
976    }
982   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines