--- jsr166/src/jsr166y/Phaser.java 2009/08/19 23:05:32 1.34 +++ jsr166/src/jsr166y/Phaser.java 2009/08/30 11:08:25 1.46 @@ -12,80 +12,99 @@ import java.util.concurrent.atomic.Atomi import java.util.concurrent.locks.LockSupport; /** - * A reusable synchronization barrier, similar in functionality to a + * A reusable synchronization barrier, similar in functionality to * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and * {@link java.util.concurrent.CountDownLatch CountDownLatch} * but supporting more flexible usage. * - * * - *
  • Barrier actions, performed by the task triggering a phase - * advance, are arranged by overriding method {@link #onAdvance(int, - * int)}, which also controls termination. Overriding this method is - * similar to, but more flexible than, providing a barrier action to a - * {@code CyclicBarrier}. - * - *
  • Phasers may enter a termination state in which all - * actions immediately return without updating phaser state or waiting - * for advance, and indicating (via a negative phase value) that - * execution is complete. Termination is triggered when an invocation - * of {@code onAdvance} returns {@code true}. When a phaser is - * controlling an action with a fixed number of iterations, it is + *

    Termination. A {@code Phaser} may enter a + * termination state in which all synchronization methods + * immediately return without updating phaser state or waiting for + * advance, and indicating (via a negative phase value) that execution + * is complete. Termination is triggered when an invocation of {@code + * onAdvance} returns {@code true}. As illustrated below, when + * phasers control actions with a fixed number of iterations, it is * often convenient to override this method to cause termination when * the current phase number reaches a threshold. Method {@link * #forceTermination} is also available to abruptly release waiting * threads and allow them to terminate. * - *

  • Phasers may be tiered to reduce contention. Phasers with large + *

    Tiering. Phasers may be tiered (i.e., arranged + * in tree structures) to reduce contention. Phasers with large * numbers of parties that would otherwise experience heavy - * synchronization contention costs may instead be arranged in trees. - * This will typically greatly increase throughput even though it - * incurs somewhat greater per-operation overhead. - * - *

  • By default, {@code awaitAdvance} continues to wait even if - * the waiting thread is interrupted. And unlike the case in - * {@code CyclicBarrier}, exceptions encountered while tasks wait - * interruptibly or with timeout do not change the state of the - * barrier. If necessary, you can perform any associated recovery - * within handlers of those exceptions, often after invoking - * {@code forceTermination}. - * - *
  • Phasers may be used to coordinate tasks executing in a {@link - * ForkJoinPool}, which will ensure sufficient parallelism to execute - * tasks when others are blocked waiting for a phase to advance. - * - * + * synchronization contention costs may instead be set up so that + * groups of sub-phasers share a common parent. This may greatly + * increase throughput even though it incurs greater per-operation + * overhead. + * + *

    Monitoring. While synchronization methods may be invoked + * only by registered parties, the current state of a phaser may be + * monitored by any caller. At any given moment there are {@link + * #getRegisteredParties} parties in total, of which {@link + * #getArrivedParties} have arrived at the current phase ({@link + * #getPhase}). When the remaining ({@link #getUnarrivedParties}) + * parties arrive, the phase advances. The values returned by these + * methods may reflect transient states and so are not in general + * useful for synchronization control. Method {@link #toString} + * returns snapshots of these state queries in a form convenient for + * informal monitoring. * *

    Sample usages: * @@ -118,43 +137,66 @@ import java.util.concurrent.locks.LockSu *

     {@code
      * void startTasks(List tasks, final int iterations) {
      *   final Phaser phaser = new Phaser() {
    - *     public boolean onAdvance(int phase, int registeredParties) {
    + *     protected boolean onAdvance(int phase, int registeredParties) {
      *       return phase >= iterations || registeredParties == 0;
      *     }
      *   };
      *   phaser.register();
    - *   for (Runnable task : tasks) {
    + *   for (final Runnable task : tasks) {
      *     phaser.register();
      *     new Thread() {
      *       public void run() {
      *         do {
      *           task.run();
      *           phaser.arriveAndAwaitAdvance();
    - *         } while(!phaser.isTerminated();
    + *         } while (!phaser.isTerminated());
      *       }
      *     }.start();
      *   }
      *   phaser.arriveAndDeregister(); // deregister self, don't wait
      * }}
    * + * If the main task must later await termination, it + * may re-register and then execute a similar loop: + *
     {@code
    + *   // ...
    + *   phaser.register();
    + *   while (!phaser.isTerminated())
    + *     phaser.arriveAndAwaitAdvance();}
    + * + *

    Related constructions may be used to await particular phase numbers + * in contexts where you are sure that the phase will never wrap around + * {@code Integer.MAX_VALUE}. For example: + * + *

     {@code
    + * void awaitPhase(Phaser phaser, int phase) {
    + *   int p = phaser.register(); // assumes caller not already registered
    + *   while (p < phase) {
    + *     if (phaser.isTerminated())
    + *       // ... deal with unexpected termination
    + *     else
    + *       p = phaser.arriveAndAwaitAdvance();
    + *   }
    + *   phaser.arriveAndDeregister();
    + * }}
    + * + * *

    To create a set of tasks using a tree of phasers, * you could use code of the following form, assuming a * Task class with a constructor accepting a phaser that * it registers for upon construction: + * *

     {@code
    - * void build(Task[] actions, int lo, int hi, Phaser b) {
    - *   int step = (hi - lo) / TASKS_PER_PHASER;
    - *   if (step > 1) {
    - *     int i = lo;
    - *     while (i < hi) {
    - *       int r = Math.min(i + step, hi);
    - *       build(actions, i, r, new Phaser(b));
    - *       i = r;
    + * void build(Task[] actions, int lo, int hi, Phaser ph) {
    + *   if (hi - lo > TASKS_PER_PHASER) {
    + *     for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
    + *       int j = Math.min(i + TASKS_PER_PHASER, hi);
    + *       build(actions, i, j, new Phaser(ph));
      *     }
      *   } else {
      *     for (int i = lo; i < hi; ++i)
    - *       actions[i] = new Task(b);
    - *       // assumes new Task(b) performs b.register()
    + *       actions[i] = new Task(ph);
    + *       // assumes new Task(ph) performs ph.register()
      *   }
      * }
      * // .. initially called, for n tasks via
    @@ -203,7 +245,6 @@ public class Phaser {
          */
         private volatile long state;
     
    -    private static final int ushortBits = 16;
         private static final int ushortMask = 0xffff;
         private static final int phaseMask  = 0x7fffffff;
     
    @@ -366,7 +407,7 @@ public class Phaser {
         /**
          * Adds a new unarrived party to this phaser.
          *
    -     * @return the current barrier phase number upon registration
    +     * @return the arrival phase number to which this registration applied
          * @throws IllegalStateException if attempting to register more
          * than the maximum supported number of parties
          */
    @@ -378,7 +419,7 @@ public class Phaser {
          * Adds the given number of new unarrived parties to this phaser.
          *
          * @param parties the number of parties required to trip barrier
    -     * @return the current barrier phase number upon registration
    +     * @return the arrival phase number to which this registration applied
          * @throws IllegalStateException if attempting to register more
          * than the maximum supported number of parties
          */
    @@ -413,10 +454,11 @@ public class Phaser {
     
         /**
          * Arrives at the barrier, but does not wait for others.  (You can
    -     * in turn wait for others via {@link #awaitAdvance}).
    +     * in turn wait for others via {@link #awaitAdvance}).  It is an
    +     * unenforced usage error for an unregistered party to invoke this
    +     * method.
          *
    -     * @return the barrier phase number upon entry to this method, or a
    -     * negative value if terminated
    +     * @return the arrival phase number, or a negative value if terminated
          * @throws IllegalStateException if not terminated and the number
          * of unarrived parties would become negative
          */
    @@ -466,10 +508,10 @@ public class Phaser {
          * required to trip the barrier in future phases.  If this phaser
          * has a parent, and deregistration causes this phaser to have
          * zero parties, this phaser also arrives at and is deregistered
    -     * from its parent.
    +     * from its parent.  It is an unenforced usage error for an
    +     * unregistered party to invoke this method.
          *
    -     * @return the current barrier phase number upon entry to
    -     * this method, or a negative value if terminated
    +     * @return the arrival phase number, or a negative value if terminated
          * @throws IllegalStateException if not terminated and the number
          * of registered or unarrived parties would become negative
          */
    @@ -523,9 +565,10 @@ public class Phaser {
          * interruption or timeout, you can arrange this with an analogous
          * construction using one of the other forms of the awaitAdvance
          * method.  If instead you need to deregister upon arrival use
    -     * {@code arriveAndDeregister}.
    +     * {@code arriveAndDeregister}. It is an unenforced usage error
    +     * for an unregistered party to invoke this method.
          *
    -     * @return the phase on entry to this method
    +     * @return the arrival phase number, or a negative number if terminated
          * @throws IllegalStateException if not terminated and the number
          * of unarrived parties would become negative
          */
    @@ -537,12 +580,14 @@ public class Phaser {
          * Awaits the phase of the barrier to advance from the given phase
          * value, returning immediately if the current phase of the
          * barrier is not equal to the given phase value or this barrier
    -     * is terminated.
    +     * is terminated.  It is an unenforced usage error for an
    +     * unregistered party to invoke this method.
          *
    -     * @param phase the phase on entry to this method
    -     * @return the current barrier phase number upon exit of
    -     * this method, or a negative value if terminated or
    -     * argument is negative
    +     * @param phase an arrival phase number, or negative value if
    +     * terminated; this argument is normally the value returned by a
    +     * previous call to {@code arrive} or its variants
    +     * @return the next arrival phase number, or a negative value
    +     * if terminated or argument is negative
          */
         public int awaitAdvance(int phase) {
             if (phase < 0)
    @@ -559,15 +604,17 @@ public class Phaser {
     
         /**
          * Awaits the phase of the barrier to advance from the given phase
    -     * value, throwing {@code InterruptedException} if interrupted while
    -     * waiting, or returning immediately if the current phase of the
    -     * barrier is not equal to the given phase value or this barrier
    -     * is terminated.
    -     *
    -     * @param phase the phase on entry to this method
    -     * @return the current barrier phase number upon exit of
    -     * this method, or a negative value if terminated or
    -     * argument is negative
    +     * value, throwing {@code InterruptedException} if interrupted
    +     * while waiting, or returning immediately if the current phase of
    +     * the barrier is not equal to the given phase value or this
    +     * barrier is terminated. It is an unenforced usage error for an
    +     * unregistered party to invoke this method.
    +     *
    +     * @param phase an arrival phase number, or negative value if
    +     * terminated; this argument is normally the value returned by a
    +     * previous call to {@code arrive} or its variants
    +     * @return the next arrival phase number, or a negative value
    +     * if terminated or argument is negative
          * @throws InterruptedException if thread interrupted while waiting
          */
         public int awaitAdvanceInterruptibly(int phase)
    @@ -585,19 +632,22 @@ public class Phaser {
     
         /**
          * Awaits the phase of the barrier to advance from the given phase
    -     * value or the given timeout to elapse, throwing
    -     * {@code InterruptedException} if interrupted while waiting, or
    -     * returning immediately if the current phase of the barrier is not
    -     * equal to the given phase value or this barrier is terminated.
    -     *
    -     * @param phase the phase on entry to this method
    +     * value or the given timeout to elapse, throwing {@code
    +     * InterruptedException} if interrupted while waiting, or
    +     * returning immediately if the current phase of the barrier is
    +     * not equal to the given phase value or this barrier is
    +     * terminated.  It is an unenforced usage error for an
    +     * unregistered party to invoke this method.
    +     *
    +     * @param phase an arrival phase number, or negative value if
    +     * terminated; this argument is normally the value returned by a
    +     * previous call to {@code arrive} or its variants
          * @param timeout how long to wait before giving up, in units of
          *        {@code unit}
          * @param unit a {@code TimeUnit} determining how to interpret the
          *        {@code timeout} parameter
    -     * @return the current barrier phase number upon exit of
    -     * this method, or a negative value if terminated or
    -     * argument is negative
    +     * @return the next arrival phase number, or a negative value
    +     * if terminated or argument is negative
          * @throws InterruptedException if thread interrupted while waiting
          * @throws TimeoutException if timed out while waiting
          */
    @@ -660,8 +710,8 @@ public class Phaser {
         }
     
         /**
    -     * Returns the number of parties that have arrived at the current
    -     * phase of this barrier.
    +     * Returns the number of registered parties that have arrived at
    +     * the current phase of this barrier.
          *
          * @return the number of arrived parties
          */
    @@ -708,13 +758,22 @@ public class Phaser {
         }
     
         /**
    -     * Overridable method to perform an action upon phase advance, and
    -     * to control termination. This method is invoked whenever the
    -     * barrier is tripped (and thus all other waiting parties are
    -     * dormant). If it returns {@code true}, then, rather than advance
    -     * the phase number, this barrier will be set to a final
    -     * termination state, and subsequent calls to {@link #isTerminated}
    -     * will return true.
    +     * Overridable method to perform an action upon impending phase
    +     * advance, and to control termination. This method is invoked
    +     * upon arrival of the party tripping the barrier (when all other
    +     * waiting parties are dormant).  If this method returns {@code
    +     * true}, then, rather than advance the phase number, this barrier
    +     * will be set to a final termination state, and subsequent calls
    +     * to {@link #isTerminated} will return true. Any (unchecked)
    +     * Exception or Error thrown by an invocation of this method is
    +     * propagated to the party attempting to trip the barrier, in
    +     * which case no advance occurs.
    +     *
    +     * 

    The arguments to this method provide the state of the phaser + * prevailing for the current transition. (When called from within + * an implementation of {@code onAdvance} the values returned by + * methods such as {@code getPhase} may or may not reliably + * indicate the state to which this transition applies.) * *

    The default version returns {@code true} when the number of * registered parties is zero. Normally, overrides that arrange @@ -722,11 +781,13 @@ public class Phaser { * property. * *

    You may override this method to perform an action with side - * effects visible to participating tasks, but it is in general - * only sensible to do so in designs where all parties register - * before any arrive, and all {@link #awaitAdvance} at each phase. + * effects visible to participating tasks, but it is only sensible + * to do so in designs where all parties register before any + * arrive, and all {@link #awaitAdvance} at each phase. * Otherwise, you cannot ensure lack of interference from other - * parties during the invocation of this method. + * parties during the invocation of this method. Additionally, + * method {@code onAdvance} may be invoked more than once per + * transition if registrations are intermixed with arrivals. * * @param phase the phase number on entering the barrier * @param registeredParties the current number of registered parties