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.39 by dl, Mon Aug 24 12:15:46 2009 UTC vs.
Revision 1.48 by dl, Sun Oct 24 21:45:39 2010 UTC

# Line 97 | Line 97 | import java.util.concurrent.locks.LockSu
97   * <p><b>Monitoring.</b> While synchronization methods may be invoked
98   * only by registered parties, the current state of a phaser may be
99   * monitored by any caller.  At any given moment there are {@link
100 < * #getRegisteredParties}, where {@link #getArrivedParties} have
101 < * arrived at the current phase ({@link #getPhase}). When the
102 < * remaining {@link #getUnarrivedParties}) arrive, the phase
103 < * advances. Method {@link #toString} returns snapshots of these state
104 < * queries in a form convenient for informal monitoring.
100 > * #getRegisteredParties} parties in total, of which {@link
101 > * #getArrivedParties} have arrived at the current phase ({@link
102 > * #getPhase}).  When the remaining ({@link #getUnarrivedParties})
103 > * parties arrive, the phase advances.  The values returned by these
104 > * methods may reflect transient states and so are not in general
105 > * useful for synchronization control.  Method {@link #toString}
106 > * returns snapshots of these state queries in a form convenient for
107 > * informal monitoring.
108   *
109   * <p><b>Sample usages:</b>
110   *
111   * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
112 < * to control a one-shot action serving a variable number of
113 < * parties. The typical idiom is for the method setting this up to
114 < * first register, then start the actions, then deregister, as in:
112 > * to control a one-shot action serving a variable number of parties.
113 > * The typical idiom is for the method setting this up to first
114 > * register, then start the actions, then deregister, as in:
115   *
116   *  <pre> {@code
117   * void runTasks(List<Runnable> tasks) {
# Line 139 | Line 142 | import java.util.concurrent.locks.LockSu
142   *     }
143   *   };
144   *   phaser.register();
145 < *   for (Runnable task : tasks) {
145 > *   for (final Runnable task : tasks) {
146   *     phaser.register();
147   *     new Thread() {
148   *       public void run() {
149   *         do {
150   *           task.run();
151   *           phaser.arriveAndAwaitAdvance();
152 < *         } while(!phaser.isTerminated();
152 > *         } while (!phaser.isTerminated());
153   *       }
154   *     }.start();
155   *   }
# Line 155 | Line 158 | import java.util.concurrent.locks.LockSu
158   *
159   * If the main task must later await termination, it
160   * may re-register and then execute a similar loop:
161 < * <pre> {@code
161 > *  <pre> {@code
162   *   // ...
163   *   phaser.register();
164   *   while (!phaser.isTerminated())
165 < *     phaser.arriveAndAwaitAdvance();
163 < * }</pre>
165 > *     phaser.arriveAndAwaitAdvance();}</pre>
166   *
167 < * Related constructions may be used to await particular phase numbers
167 > * <p>Related constructions may be used to await particular phase numbers
168   * in contexts where you are sure that the phase will never wrap around
169   * {@code Integer.MAX_VALUE}. For example:
170   *
171 < * <pre> {@code
172 < *   void awaitPhase(Phaser phaser, int phase) {
173 < *     int p = phaser.register(); // assumes caller not already registered
174 < *     while (p < phase) {
175 < *       if (phaser.isTerminated())
176 < *         // ... deal with unexpected termination
177 < *       else
178 < *         p = phaser.arriveAndAwaitAdvance();
177 < *     }
178 < *     phaser.arriveAndDeregister();
171 > *  <pre> {@code
172 > * void awaitPhase(Phaser phaser, int phase) {
173 > *   int p = phaser.register(); // assumes caller not already registered
174 > *   while (p < phase) {
175 > *     if (phaser.isTerminated())
176 > *       // ... deal with unexpected termination
177 > *     else
178 > *       p = phaser.arriveAndAwaitAdvance();
179   *   }
180 < * }</pre>
180 > *   phaser.arriveAndDeregister();
181 > * }}</pre>
182   *
183   *
184   * <p>To create a set of tasks using a tree of phasers,
185   * you could use code of the following form, assuming a
186   * Task class with a constructor accepting a phaser that
187 < * it registers for upon construction:
187 > * it registers with upon construction:
188 > *
189   *  <pre> {@code
190 < * void build(Task[] actions, int lo, int hi, Phaser b) {
191 < *   int step = (hi - lo) / TASKS_PER_PHASER;
192 < *   if (step > 1) {
193 < *     int i = lo;
194 < *     while (i < hi) {
193 < *       int r = Math.min(i + step, hi);
194 < *       build(actions, i, r, new Phaser(b));
195 < *       i = r;
190 > * void build(Task[] actions, int lo, int hi, Phaser ph) {
191 > *   if (hi - lo > TASKS_PER_PHASER) {
192 > *     for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
193 > *       int j = Math.min(i + TASKS_PER_PHASER, hi);
194 > *       build(actions, i, j, new Phaser(ph));
195   *     }
196   *   } else {
197   *     for (int i = lo; i < hi; ++i)
198 < *       actions[i] = new Task(b);
199 < *       // assumes new Task(b) performs b.register()
198 > *       actions[i] = new Task(ph);
199 > *       // assumes new Task(ph) performs ph.register()
200   *   }
201   * }
202   * // .. initially called, for n tasks via
# Line 208 | Line 207 | import java.util.concurrent.locks.LockSu
207   * be appropriate for extremely small per-barrier task bodies (thus
208   * high rates), or up to hundreds for extremely large ones.
209   *
211 * </pre>
212 *
210   * <p><b>Implementation notes</b>: This implementation restricts the
211   * maximum number of parties to 65535. Attempts to register additional
212   * parties result in {@code IllegalStateException}. However, you can and
# Line 246 | Line 243 | public class Phaser {
243       */
244      private volatile long state;
245  
249    private static final int ushortBits = 16;
246      private static final int ushortMask = 0xffff;
247      private static final int phaseMask  = 0x7fffffff;
248  
# Line 350 | Line 346 | public class Phaser {
346      }
347  
348      /**
349 <     * Creates a new phaser with the given numbers of registered
349 >     * Creates a new phaser with the given number of registered
350       * unarrived parties, initial phase number 0, and no parent.
351       *
352       * @param parties the number of parties required to trip barrier
# Line 382 | Line 378 | public class Phaser {
378      }
379  
380      /**
381 <     * Creates a new phaser with the given parent and numbers of
381 >     * Creates a new phaser with the given parent and number of
382       * registered unarrived parties. If parent is non-null, this phaser
383       * is registered with the parent and its initial phase number is
384       * the same as that of parent phaser.
# Line 420 | Line 416 | public class Phaser {
416      /**
417       * Adds the given number of new unarrived parties to this phaser.
418       *
419 <     * @param parties the number of parties required to trip barrier
419 >     * @param parties the number of additional parties required to trip barrier
420       * @return the arrival phase number to which this registration applied
421       * @throws IllegalStateException if attempting to register more
422       * than the maximum supported number of parties
423 +     * @throws IllegalArgumentException if {@code parties < 0}
424       */
425      public int bulkRegister(int parties) {
426          if (parties < 0)
# Line 565 | Line 562 | public class Phaser {
562       * Arrives at the barrier and awaits others. Equivalent in effect
563       * to {@code awaitAdvance(arrive())}.  If you need to await with
564       * interruption or timeout, you can arrange this with an analogous
565 <     * construction using one of the other forms of the awaitAdvance
566 <     * method.  If instead you need to deregister upon arrival use
567 <     * {@code arriveAndDeregister}. It is an unenforced usage error
568 <     * for an unregistered party to invoke this method.
565 >     * construction using one of the other forms of the {@code
566 >     * awaitAdvance} method.  If instead you need to deregister upon
567 >     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
568 >     * usage error for an unregistered party to invoke this method.
569       *
570       * @return the arrival phase number, or a negative number if terminated
571       * @throws IllegalStateException if not terminated and the number
# Line 760 | Line 757 | public class Phaser {
757      }
758  
759      /**
760 <     * Overridable method to perform an action upon phase advance, and
761 <     * to control termination. This method is invoked whenever the
762 <     * barrier is tripped (and thus all other waiting parties are
763 <     * dormant). If it returns {@code true}, then, rather than advance
764 <     * the phase number, this barrier will be set to a final
765 <     * termination state, and subsequent calls to {@link #isTerminated}
766 <     * will return true.
760 >     * Overridable method to perform an action upon impending phase
761 >     * advance, and to control termination. This method is invoked
762 >     * upon arrival of the party tripping the barrier (when all other
763 >     * waiting parties are dormant).  If this method returns {@code
764 >     * true}, then, rather than advance the phase number, this barrier
765 >     * will be set to a final termination state, and subsequent calls
766 >     * to {@link #isTerminated} will return true. Any (unchecked)
767 >     * Exception or Error thrown by an invocation of this method is
768 >     * propagated to the party attempting to trip the barrier, in
769 >     * which case no advance occurs.
770 >     *
771 >     * <p>The arguments to this method provide the state of the phaser
772 >     * prevailing for the current transition. (When called from within
773 >     * an implementation of {@code onAdvance} the values returned by
774 >     * methods such as {@code getPhase} may or may not reliably
775 >     * indicate the state to which this transition applies.)
776       *
777       * <p>The default version returns {@code true} when the number of
778       * registered parties is zero. Normally, overrides that arrange
# Line 774 | Line 780 | public class Phaser {
780       * property.
781       *
782       * <p>You may override this method to perform an action with side
783 <     * effects visible to participating tasks, but it is in general
784 <     * only sensible to do so in designs where all parties register
785 <     * before any arrive, and all {@link #awaitAdvance} at each phase.
783 >     * effects visible to participating tasks, but it is only sensible
784 >     * to do so in designs where all parties register before any
785 >     * arrive, and all {@link #awaitAdvance} at each phase.
786       * Otherwise, you cannot ensure lack of interference from other
787 <     * parties during the invocation of this method.
787 >     * parties during the invocation of this method. Additionally,
788 >     * method {@code onAdvance} may be invoked more than once per
789 >     * transition if registrations are intermixed with arrivals.
790       *
791       * @param phase the phase number on entering the barrier
792       * @param registeredParties the current number of registered parties
# Line 820 | Line 828 | public class Phaser {
828          volatile boolean wasInterrupted = false;
829          volatile Thread thread; // nulled to cancel wait
830          QNode next;
831 +
832          QNode(Phaser phaser, int phase, boolean interruptible,
833                boolean timed, long startTime, long nanos) {
834              this.phaser = phaser;
# Line 830 | Line 839 | public class Phaser {
839              this.nanos = nanos;
840              thread = Thread.currentThread();
841          }
842 +
843          public boolean isReleasable() {
844              return (thread == null ||
845                      phaser.getPhase() != phase ||
846                      (interruptible && wasInterrupted) ||
847                      (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
848          }
849 +
850          public boolean block() {
851              if (Thread.interrupted()) {
852                  wasInterrupted = true;
# Line 852 | Line 863 | public class Phaser {
863              }
864              return isReleasable();
865          }
866 +
867          void signal() {
868              Thread t = thread;
869              if (t != null) {
# Line 859 | Line 871 | public class Phaser {
871                  LockSupport.unpark(t);
872              }
873          }
874 +
875          boolean doWait() {
876              if (thread != null) {
877                  try {
878 <                    ForkJoinPool.managedBlock(this, false);
878 >                    ForkJoinPool.managedBlock(this);
879                  } catch (InterruptedException ie) {
880 +                    wasInterrupted = true; // can't currently happen
881                  }
882              }
883              return wasInterrupted;
884          }
871
885      }
886  
887      /**
# Line 910 | Line 923 | public class Phaser {
923                  node = new QNode(this, phase, false, false, 0, 0);
924              else if (!queued)
925                  queued = tryEnqueue(node);
926 <            else
927 <                interrupted = node.doWait();
926 >            else if (node.doWait())
927 >                interrupted = true;
928          }
929          if (node != null)
930              node.thread = null;
# Line 937 | Line 950 | public class Phaser {
950                  node = new QNode(this, phase, true, false, 0, 0);
951              else if (!queued)
952                  queued = tryEnqueue(node);
953 <            else
954 <                interrupted = node.doWait();
953 >            else if (node.doWait())
954 >                interrupted = true;
955          }
956          if (node != null)
957              node.thread = null;
# Line 969 | Line 982 | public class Phaser {
982                  node = new QNode(this, phase, true, true, startTime, nanos);
983              else if (!queued)
984                  queued = tryEnqueue(node);
985 <            else
986 <                interrupted = node.doWait();
985 >            else if (node.doWait())
986 >                interrupted = true;
987          }
988          if (node != null)
989              node.thread = null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines