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.6 by dl, Tue Oct 28 23:03:24 2008 UTC vs.
Revision 1.21 by jsr166, Sun Jul 26 05:55:34 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 +
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
10 >
11 > import java.util.concurrent.atomic.AtomicReference;
12   import java.util.concurrent.locks.LockSupport;
11 import sun.misc.Unsafe;
12 import java.lang.reflect.*;
13  
14   /**
15   * A reusable synchronization barrier, similar in functionality to a
16 < * {@link java.util.concurrent.CyclicBarrier} and {@link
17 < * java.util.concurrent.CountDownLatch} but supporting more flexible
18 < * usage.
16 > * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
17 > * {@link java.util.concurrent.CountDownLatch CountDownLatch}
18 > * but supporting more flexible usage.
19   *
20   * <ul>
21   *
# Line 25 | Line 25 | import java.lang.reflect.*;
25   * basic synchronization constructs, registration and deregistration
26   * affect only internal counts; they do not establish any further
27   * internal bookkeeping, so tasks cannot query whether they are
28 < * registered. (However, you can introduce such bookkeeping in by
28 > * registered. (However, you can introduce such bookkeeping by
29   * subclassing this class.)
30   *
31   * <li> Each generation has an associated phase value, starting at
32   * zero, and advancing when all parties reach the barrier (wrapping
33 < * around to zero after reaching <tt>Integer.MAX_VALUE</tt>).
33 > * around to zero after reaching {@code Integer.MAX_VALUE}).
34   *
35   * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
36 < * Method <tt>arriveAndAwaitAdvance</tt> has effect analogous to
37 < * <tt>CyclicBarrier.await</tt>.  However, Phasers separate two
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:
39   *
40   * <ul>
41   *
42 < *   <li> Arriving at a barrier. Methods <tt>arrive</tt> and
43 < *       <tt>arriveAndDeregister</tt> do not block, but return
42 > *   <li> Arriving at a barrier. Methods {@code arrive} and
43 > *       {@code arriveAndDeregister} do not block, but return
44   *       the phase value current upon entry to the method.
45   *
46 < *   <li> Awaiting others. Method <tt>awaitAdvance</tt> requires an
46 > *   <li> Awaiting others. Method {@code awaitAdvance} requires an
47   *       argument indicating the entry phase, and returns when the
48   *       barrier advances to a new phase.
49   * </ul>
# Line 51 | Line 51 | import java.lang.reflect.*;
51   *
52   * <li> Barrier actions, performed by the task triggering a phase
53   * advance while others may be waiting, are arranged by overriding
54 < * method <tt>onAdvance</tt>, that also controls termination.
54 > * method {@code onAdvance}, that also controls termination.
55   * Overriding this method may be used to similar but more flexible
56   * effect as providing a barrier action to a CyclicBarrier.
57   *
58   * <li> Phasers may enter a <em>termination</em> state in which all
59 < * await actions immediately return, indicating (via a negative phase
60 < * value) that execution is complete.  Termination is triggered by
61 < * executing the overridable <tt>onAdvance</tt> method that is invoked
62 < * each time the barrier is about to be tripped. When a Phaser is
63 < * controlling an action with a fixed number of iterations, it is
64 < * often convenient to override this method to cause termination when
65 < * the current phase number reaches a threshold. Method
66 < * <tt>forceTermination</tt> is also available to abruptly release
67 < * waiting threads and allow them to terminate.
59 > * actions immediately return without updating phaser state or waiting
60 > * for advance, and indicating (via a negative phase value) that
61 > * execution is complete.  Termination is triggered by executing the
62 > * overridable {@code onAdvance} method that is invoked each time the
63 > * barrier is about to be tripped. When a Phaser is controlling an
64 > * action with a fixed number of iterations, it is often convenient to
65 > * override this method to cause termination when the current phase
66 > * number reaches a threshold. Method {@code forceTermination} is also
67 > * available to abruptly release waiting threads and allow them to
68 > * terminate.
69   *
70   * <li> Phasers may be tiered to reduce contention. Phasers with large
71   * numbers of parties that would otherwise experience heavy
# Line 72 | Line 73 | import java.lang.reflect.*;
73   * This will typically greatly increase throughput even though it
74   * incurs somewhat greater per-operation overhead.
75   *
76 < * <li> By default, <tt>awaitAdvance</tt> continues to wait even if
76 > * <li> By default, {@code awaitAdvance} continues to wait even if
77   * the waiting thread is interrupted. And unlike the case in
78   * CyclicBarriers, exceptions encountered while tasks wait
79   * interruptibly or with timeout do not change the state of the
80   * barrier. If necessary, you can perform any associated recovery
81   * within handlers of those exceptions, often after invoking
82 < * <tt>forceTermination</tt>.
82 > * {@code forceTermination}.
83 > *
84 > * <li>Phasers ensure lack of starvation when used by ForkJoinTasks.
85   *
86   * </ul>
87   *
88   * <p><b>Sample usages:</b>
89   *
90 < * <p>A Phaser may be used instead of a <tt>CountdownLatch</tt> to control
90 > * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
91   * a one-shot action serving a variable number of parties. The typical
92   * idiom is for the method setting this up to first register, then
93   * start the actions, then deregister, as in:
94   *
95 < * <pre>
96 < *  void runTasks(List&lt;Runnable&gt; list) {
97 < *    final Phaser phaser = new Phaser(1); // "1" to register self
98 < *    for (Runnable r : list) {
99 < *      phaser.register();
100 < *      new Thread() {
101 < *        public void run() {
102 < *          phaser.arriveAndAwaitAdvance(); // await all creation
103 < *          r.run();
104 < *          phaser.arriveAndDeregister();   // signal completion
105 < *        }
106 < *      }.start();
95 > *  <pre> {@code
96 > * void runTasks(List<Runnable> list) {
97 > *   final Phaser phaser = new Phaser(1); // "1" to register self
98 > *   for (Runnable r : list) {
99 > *     phaser.register();
100 > *     new Thread() {
101 > *       public void run() {
102 > *         phaser.arriveAndAwaitAdvance(); // await all creation
103 > *         r.run();
104 > *         phaser.arriveAndDeregister();   // signal completion
105 > *       }
106 > *     }.start();
107   *   }
108   *
109   *   doSomethingOnBehalfOfWorkers();
# Line 108 | Line 111 | import java.lang.reflect.*;
111   *   int p = phaser.arriveAndDeregister(); // deregister self  ...
112   *   p = phaser.awaitAdvance(p); // ... and await arrival
113   *   otherActions(); // do other things while tasks execute
114 < *   phaser.awaitAdvance(p); // awit final completion
115 < * }
113 < * </pre>
114 > *   phaser.awaitAdvance(p); // await final completion
115 > * }}</pre>
116   *
117   * <p>One way to cause a set of threads to repeatedly perform actions
118 < * for a given number of iterations is to override <tt>onAdvance</tt>:
118 > * for a given number of iterations is to override {@code onAdvance}:
119   *
120 < * <pre>
121 < *  void startTasks(List&lt;Runnable&gt; list, final int iterations) {
122 < *    final Phaser phaser = new Phaser() {
123 < *       public boolean onAdvance(int phase, int registeredParties) {
124 < *         return phase &gt;= iterations || registeredParties == 0;
120 > *  <pre> {@code
121 > * void startTasks(List<Runnable> list, final int iterations) {
122 > *   final Phaser phaser = new Phaser() {
123 > *     public boolean onAdvance(int phase, int registeredParties) {
124 > *       return phase >= iterations || registeredParties == 0;
125 > *     }
126 > *   };
127 > *   phaser.register();
128 > *   for (Runnable r : list) {
129 > *     phaser.register();
130 > *     new Thread() {
131 > *       public void run() {
132 > *         do {
133 > *           r.run();
134 > *           phaser.arriveAndAwaitAdvance();
135 > *         } while(!phaser.isTerminated();
136   *       }
137 < *    };
125 < *    phaser.register();
126 < *    for (Runnable r : list) {
127 < *      phaser.register();
128 < *      new Thread() {
129 < *        public void run() {
130 < *           do {
131 < *             r.run();
132 < *             phaser.arriveAndAwaitAdvance();
133 < *           } while(!phaser.isTerminated();
134 < *        }
135 < *      }.start();
137 > *     }.start();
138   *   }
139   *   phaser.arriveAndDeregister(); // deregister self, don't wait
140 < * }
139 < * </pre>
140 > * }}</pre>
141   *
142   * <p> To create a set of tasks using a tree of Phasers,
143   * you could use code of the following form, assuming a
144   * Task class with a constructor accepting a Phaser that
145   * it registers for upon construction:
146 < * <pre>
147 < *  void build(Task[] actions, int lo, int hi, Phaser b) {
148 < *    int step = (hi - lo) / TASKS_PER_PHASER;
149 < *    if (step &gt; 1) {
150 < *       int i = lo;
151 < *       while (i &lt; hi) {
152 < *         int r = Math.min(i + step, hi);
153 < *         build(actions, i, r, new Phaser(b));
154 < *         i = r;
155 < *       }
156 < *    }
157 < *    else {
158 < *      for (int i = lo; i &lt; hi; ++i)
159 < *        actions[i] = new Task(b);
160 < *        // assumes new Task(b) performs b.register()
161 < *    }
162 < *  }
163 < *  // .. initially called, for n tasks via
163 < *  build(new Task[n], 0, n, new Phaser());
164 < * </pre>
146 > *  <pre> {@code
147 > * void build(Task[] actions, int lo, int hi, Phaser b) {
148 > *   int step = (hi - lo) / TASKS_PER_PHASER;
149 > *   if (step > 1) {
150 > *     int i = lo;
151 > *     while (i < hi) {
152 > *       int r = Math.min(i + step, hi);
153 > *       build(actions, i, r, new Phaser(b));
154 > *       i = r;
155 > *     }
156 > *   } else {
157 > *     for (int i = lo; i < hi; ++i)
158 > *       actions[i] = new Task(b);
159 > *       // assumes new Task(b) performs b.register()
160 > *   }
161 > * }
162 > * // .. initially called, for n tasks via
163 > * build(new Task[n], 0, n, new Phaser());}</pre>
164   *
165 < * The best value of <tt>TASKS_PER_PHASER</tt> depends mainly on
165 > * The best value of {@code TASKS_PER_PHASER} depends mainly on
166   * expected barrier synchronization rates. A value as low as four may
167   * be appropriate for extremely small per-barrier task bodies (thus
168   * high rates), or up to hundreds for extremely large ones.
# Line 175 | Line 174 | import java.lang.reflect.*;
174   * parties result in IllegalStateExceptions. However, you can and
175   * should create tiered phasers to accommodate arbitrarily large sets
176   * of participants.
177 + *
178 + * @since 1.7
179 + * @author Doug Lea
180   */
181   public class Phaser {
182      /*
# Line 195 | Line 197 | public class Phaser {
197       * However, to efficiently maintain atomicity, these values are
198       * packed into a single (atomic) long. Termination uses the sign
199       * bit of 32 bit representation of phase, so phase is set to -1 on
200 <     * termination. Good performace relies on keeping state decoding
200 >     * termination. Good performance relies on keeping state decoding
201       * and encoding simple, and keeping race windows short.
202       *
203       * Note: there are some cheats in arrive() that rely on unarrived
204 <     * being lowest 16 bits.
204 >     * count being lowest 16 bits.
205       */
206      private volatile long state;
207  
208      private static final int ushortBits = 16;
209 <    private static final int ushortMask =  (1 << ushortBits) - 1;
210 <    private static final int phaseMask = 0x7fffffff;
209 >    private static final int ushortMask = 0xffff;
210 >    private static final int phaseMask  = 0x7fffffff;
211  
212      private static int unarrivedOf(long s) {
213 <        return (int)(s & ushortMask);
213 >        return (int) (s & ushortMask);
214      }
215  
216      private static int partiesOf(long s) {
217 <        return (int)(s & (ushortMask << 16)) >>> 16;
217 >        return ((int) s) >>> 16;
218      }
219  
220      private static int phaseOf(long s) {
221 <        return (int)(s >>> 32);
221 >        return (int) (s >>> 32);
222      }
223  
224      private static int arrivedOf(long s) {
# Line 224 | Line 226 | public class Phaser {
226      }
227  
228      private static long stateFor(int phase, int parties, int unarrived) {
229 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
229 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
230 >                (long) unarrived);
231      }
232  
233      private static long trippedStateFor(int phase, int parties) {
234 <        return (((long)phase) << 32) | ((parties << 16) | parties);
234 >        long lp = (long) parties;
235 >        return (((long) phase) << 32) | (lp << 16) | lp;
236      }
237  
238 <    private static IllegalStateException badBounds(int parties, int unarrived) {
239 <        return new IllegalStateException
240 <            ("Attempt to set " + unarrived +
241 <             " unarrived of " + parties + " parties");
238 >    /**
239 >     * Returns message string for bad bounds exceptions.
240 >     */
241 >    private static String badBounds(int parties, int unarrived) {
242 >        return ("Attempt to set " + unarrived +
243 >                " unarrived of " + parties + " parties");
244      }
245  
246      /**
# Line 251 | Line 257 | public class Phaser {
257      // Wait queues
258  
259      /**
260 <     * Heads of Treiber stacks waiting for nonFJ threads. To eliminate
260 >     * Heads of Treiber stacks for waiting threads. To eliminate
261       * contention while releasing some threads while adding others, we
262       * use two of them, alternating across even and odd phases.
263       */
# Line 259 | Line 265 | public class Phaser {
265      private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
266  
267      private AtomicReference<QNode> queueFor(int phase) {
268 <        return (phase & 1) == 0? evenQ : oddQ;
268 >        return ((phase & 1) == 0) ? evenQ : oddQ;
269      }
270  
271      /**
# Line 267 | Line 273 | public class Phaser {
273       * root if necessary.
274       */
275      private long getReconciledState() {
276 <        return parent == null? state : reconcileState();
276 >        return (parent == null) ? state : reconcileState();
277      }
278  
279      /**
# Line 295 | Line 301 | public class Phaser {
301  
302      /**
303       * Creates a new Phaser without any initially registered parties,
304 <     * initial phase number 0, and no parent.
304 >     * initial phase number 0, and no parent. Any thread using this
305 >     * Phaser will need to first register for it.
306       */
307      public Phaser() {
308          this(null);
# Line 304 | Line 311 | public class Phaser {
311      /**
312       * Creates a new Phaser with the given numbers of registered
313       * unarrived parties, initial phase number 0, and no parent.
314 <     * @param parties the number of parties required to trip barrier.
314 >     *
315 >     * @param parties the number of parties required to trip barrier
316       * @throws IllegalArgumentException if parties less than zero
317 <     * or greater than the maximum number of parties supported.
317 >     * or greater than the maximum number of parties supported
318       */
319      public Phaser(int parties) {
320          this(null, parties);
# Line 317 | Line 325 | public class Phaser {
325       * initially registered parties. If parent is non-null this phaser
326       * is registered with the parent and its initial phase number is
327       * the same as that of parent phaser.
328 <     * @param parent the parent phaser.
328 >     *
329 >     * @param parent the parent phaser
330       */
331      public Phaser(Phaser parent) {
332          int phase = 0;
# Line 333 | Line 342 | public class Phaser {
342  
343      /**
344       * Creates a new Phaser with the given parent and numbers of
345 <     * registered unarrived parties. If parent is non-null this phaser
345 >     * registered unarrived parties. If parent is non-null, this phaser
346       * is registered with the parent and its initial phase number is
347       * the same as that of parent phaser.
348 <     * @param parent the parent phaser.
349 <     * @param parties the number of parties required to trip barrier.
348 >     *
349 >     * @param parent the parent phaser
350 >     * @param parties the number of parties required to trip barrier
351       * @throws IllegalArgumentException if parties less than zero
352 <     * or greater than the maximum number of parties supported.
352 >     * or greater than the maximum number of parties supported
353       */
354      public Phaser(Phaser parent, int parties) {
355          if (parties < 0 || parties > ushortMask)
# Line 357 | Line 367 | public class Phaser {
367  
368      /**
369       * Adds a new unarrived party to this phaser.
370 +     *
371       * @return the current barrier phase number upon registration
372       * @throws IllegalStateException if attempting to register more
373 <     * than the maximum supported number of parties.
373 >     * than the maximum supported number of parties
374       */
375      public int register() {
376          return doRegister(1);
# Line 367 | Line 378 | public class Phaser {
378  
379      /**
380       * Adds the given number of new unarrived parties to this phaser.
381 <     * @param parties the number of parties required to trip barrier.
381 >     *
382 >     * @param parties the number of parties required to trip barrier
383       * @return the current barrier phase number upon registration
384       * @throws IllegalStateException if attempting to register more
385 <     * than the maximum supported number of parties.
385 >     * than the maximum supported number of parties
386       */
387      public int bulkRegister(int parties) {
388          if (parties < 0)
# Line 393 | Line 405 | public class Phaser {
405              if (phase < 0)
406                  break;
407              if (parties > ushortMask || unarrived > ushortMask)
408 <                throw badBounds(parties, unarrived);
408 >                throw new IllegalStateException(badBounds(parties, unarrived));
409              if (phase == phaseOf(root.state) &&
410                  casState(s, stateFor(phase, parties, unarrived)))
411                  break;
# Line 406 | Line 418 | public class Phaser {
418       * in turn wait for others via {@link #awaitAdvance}).
419       *
420       * @return the barrier phase number upon entry to this method, or a
421 <     * negative value if terminated;
421 >     * negative value if terminated
422       * @throws IllegalStateException if not terminated and the number
423 <     * of unarrived parties would become negative.
423 >     * of unarrived parties would become negative
424       */
425      public int arrive() {
426          int phase;
427          for (;;) {
428              long s = state;
429              phase = phaseOf(s);
430 +            if (phase < 0)
431 +                break;
432              int parties = partiesOf(s);
433              int unarrived = unarrivedOf(s) - 1;
434              if (unarrived > 0) {        // Not the last arrival
# Line 426 | Line 440 | public class Phaser {
440                  if (par == null) {      // directly trip
441                      if (casState
442                          (s,
443 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
443 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
444                                           ((phase + 1) & phaseMask), parties))) {
445                          releaseWaiters(phase);
446                          break;
# Line 440 | Line 454 | public class Phaser {
454                      }
455                  }
456              }
443            else if (phase < 0) // Don't throw exception if terminated
444                break;
457              else if (phase != phaseOf(root.state)) // or if unreconciled
458                  reconcileState();
459              else
460 <                throw badBounds(parties, unarrived);
460 >                throw new IllegalStateException(badBounds(parties, unarrived));
461          }
462          return phase;
463      }
# Line 458 | Line 470 | public class Phaser {
470       * zero parties, this phaser is also deregistered from its parent.
471       *
472       * @return the current barrier phase number upon entry to
473 <     * this method, or a negative value if terminated;
473 >     * this method, or a negative value if terminated
474       * @throws IllegalStateException if not terminated and the number
475 <     * of registered or unarrived parties would become negative.
475 >     * of registered or unarrived parties would become negative
476       */
477      public int arriveAndDeregister() {
478          // similar code to arrive, but too different to merge
# Line 469 | Line 481 | public class Phaser {
481          for (;;) {
482              long s = state;
483              phase = phaseOf(s);
484 +            if (phase < 0)
485 +                break;
486              int parties = partiesOf(s) - 1;
487              int unarrived = unarrivedOf(s) - 1;
488              if (parties >= 0) {
# Line 487 | Line 501 | public class Phaser {
501                  if (unarrived == 0) {
502                      if (casState
503                          (s,
504 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
504 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
505                                           ((phase + 1) & phaseMask), parties))) {
506                          releaseWaiters(phase);
507                          break;
508                      }
509                      continue;
510                  }
497                if (phase < 0)
498                    break;
511                  if (par != null && phase != phaseOf(root.state)) {
512                      reconcileState();
513                      continue;
514                  }
515              }
516 <            throw badBounds(parties, unarrived);
516 >            throw new IllegalStateException(badBounds(parties, unarrived));
517          }
518          return phase;
519      }
520  
521      /**
522       * Arrives at the barrier and awaits others. Equivalent in effect
523 <     * to <tt>awaitAdvance(arrive())</tt>.  If you instead need to
523 >     * to {@code awaitAdvance(arrive())}.  If you instead need to
524       * await with interruption of timeout, and/or deregister upon
525       * arrival, you can arrange them using analogous constructions.
526 +     *
527       * @return the phase on entry to this method
528       * @throws IllegalStateException if not terminated and the number
529 <     * of unarrived parties would become negative.
529 >     * of unarrived parties would become negative
530       */
531      public int arriveAndAwaitAdvance() {
532          return awaitAdvance(arrive());
# Line 523 | Line 536 | public class Phaser {
536       * Awaits the phase of the barrier to advance from the given
537       * value, or returns immediately if argument is negative or this
538       * barrier is terminated.
539 +     *
540       * @param phase the phase on entry to this method
541       * @return the phase on exit from this method
542       */
# Line 533 | Line 547 | public class Phaser {
547          int p = phaseOf(s);
548          if (p != phase)
549              return p;
550 <        if (unarrivedOf(s) == 0)
550 >        if (unarrivedOf(s) == 0 && parent != null)
551              parent.awaitAdvance(phase);
552          // Fall here even if parent waited, to reconcile and help release
553          return untimedWait(phase);
# Line 541 | Line 555 | public class Phaser {
555  
556      /**
557       * Awaits the phase of the barrier to advance from the given
558 <     * value, or returns immediately if argumet is negative or this
558 >     * value, or returns immediately if argument is negative or this
559       * barrier is terminated, or throws InterruptedException if
560       * interrupted while waiting.
561 +     *
562       * @param phase the phase on entry to this method
563       * @return the phase on exit from this method
564       * @throws InterruptedException if thread interrupted while waiting
565       */
566 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
566 >    public int awaitAdvanceInterruptibly(int phase)
567 >        throws InterruptedException {
568          if (phase < 0)
569              return phase;
570          long s = getReconciledState();
571          int p = phaseOf(s);
572          if (p != phase)
573              return p;
574 <        if (unarrivedOf(s) != 0)
574 >        if (unarrivedOf(s) == 0 && parent != null)
575              parent.awaitAdvanceInterruptibly(phase);
576          return interruptibleWait(phase);
577      }
# Line 564 | Line 580 | public class Phaser {
580       * Awaits the phase of the barrier to advance from the given value
581       * or the given timeout elapses, or returns immediately if
582       * argument is negative or this barrier is terminated.
583 +     *
584       * @param phase the phase on entry to this method
585       * @return the phase on exit from this method
586       * @throws InterruptedException if thread interrupted while waiting
587       * @throws TimeoutException if timed out while waiting
588       */
589 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
589 >    public int awaitAdvanceInterruptibly(int phase,
590 >                                         long timeout, TimeUnit unit)
591          throws InterruptedException, TimeoutException {
592          if (phase < 0)
593              return phase;
# Line 577 | Line 595 | public class Phaser {
595          int p = phaseOf(s);
596          if (p != phase)
597              return p;
598 <        if (unarrivedOf(s) == 0)
598 >        if (unarrivedOf(s) == 0 && parent != null)
599              parent.awaitAdvanceInterruptibly(phase, timeout, unit);
600          return timedWait(phase, unit.toNanos(timeout));
601      }
# Line 608 | Line 626 | public class Phaser {
626  
627      /**
628       * Returns the current phase number. The maximum phase number is
629 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
629 >     * {@code Integer.MAX_VALUE}, after which it restarts at
630       * zero. Upon termination, the phase number is negative.
631 +     *
632       * @return the phase number, or a negative value if terminated
633       */
634      public final int getPhase() {
# Line 617 | Line 636 | public class Phaser {
636      }
637  
638      /**
639 <     * Returns true if the current phase number equals the given phase.
639 >     * Returns {@code true} if the current phase number equals the given phase.
640 >     *
641       * @param phase the phase
642 <     * @return true if the current phase number equals the given phase.
642 >     * @return {@code true} if the current phase number equals the given phase
643       */
644      public final boolean hasPhase(int phase) {
645          return phaseOf(getReconciledState()) == phase;
# Line 627 | Line 647 | public class Phaser {
647  
648      /**
649       * Returns the number of parties registered at this barrier.
650 +     *
651       * @return the number of parties
652       */
653      public int getRegisteredParties() {
# Line 636 | Line 657 | public class Phaser {
657      /**
658       * Returns the number of parties that have arrived at the current
659       * phase of this barrier.
660 +     *
661       * @return the number of arrived parties
662       */
663      public int getArrivedParties() {
# Line 645 | Line 667 | public class Phaser {
667      /**
668       * Returns the number of registered parties that have not yet
669       * arrived at the current phase of this barrier.
670 +     *
671       * @return the number of unarrived parties
672       */
673      public int getUnarrivedParties() {
# Line 653 | Line 676 | public class Phaser {
676  
677      /**
678       * Returns the parent of this phaser, or null if none.
679 <     * @return the parent of this phaser, or null if none.
679 >     *
680 >     * @return the parent of this phaser, or null if none
681       */
682      public Phaser getParent() {
683          return parent;
# Line 662 | Line 686 | public class Phaser {
686      /**
687       * Returns the root ancestor of this phaser, which is the same as
688       * this phaser if it has no parent.
689 <     * @return the root ancestor of this phaser.
689 >     *
690 >     * @return the root ancestor of this phaser
691       */
692      public Phaser getRoot() {
693          return root;
694      }
695  
696      /**
697 <     * Returns true if this barrier has been terminated.
698 <     * @return true if this barrier has been terminated
697 >     * Returns {@code true} if this barrier has been terminated.
698 >     *
699 >     * @return {@code true} if this barrier has been terminated
700       */
701      public boolean isTerminated() {
702          return getPhase() < 0;
# Line 682 | Line 708 | public class Phaser {
708       * barrier is tripped (and thus all other waiting parties are
709       * dormant). If it returns true, then, rather than advance the
710       * phase number, this barrier will be set to a final termination
711 <     * state, and subsequent calls to <tt>isTerminated</tt> will
711 >     * state, and subsequent calls to {@code isTerminated} will
712       * return true.
713       *
714       * <p> The default version returns true when the number of
# Line 693 | Line 719 | public class Phaser {
719       * <p> You may override this method to perform an action with side
720       * effects visible to participating tasks, but it is in general
721       * only sensible to do so in designs where all parties register
722 <     * before any arrive, and all <tt>awaitAdvance</tt> at each phase.
722 >     * before any arrive, and all {@code awaitAdvance} at each phase.
723       * Otherwise, you cannot ensure lack of interference. In
724       * particular, this method may be invoked more than once per
725       * transition if other parties successfully register while the
# Line 702 | Line 728 | public class Phaser {
728       * method.
729       *
730       * @param phase the phase number on entering the barrier
731 <     * @param registeredParties the current number of registered
732 <     * parties.
707 <     * @return true if this barrier should terminate
731 >     * @param registeredParties the current number of registered parties
732 >     * @return {@code true} if this barrier should terminate
733       */
734      protected boolean onAdvance(int phase, int registeredParties) {
735          return registeredParties <= 0;
# Line 713 | Line 738 | public class Phaser {
738      /**
739       * Returns a string identifying this phaser, as well as its
740       * state.  The state, in brackets, includes the String {@code
741 <     * "phase ="} followed by the phase number, {@code "parties ="}
741 >     * "phase = "} followed by the phase number, {@code "parties = "}
742       * followed by the number of registered parties, and {@code
743 <     * "arrived ="} followed by the number of arrived parties
743 >     * "arrived = "} followed by the number of arrived parties.
744       *
745       * @return a string identifying this barrier, as well as its state
746       */
747      public String toString() {
748          long s = getReconciledState();
749 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
749 >        return super.toString() +
750 >            "[phase = " + phaseOf(s) +
751 >            " parties = " + partiesOf(s) +
752 >            " arrived = " + arrivedOf(s) + "]";
753      }
754  
755      // methods for waiting
756  
729    /** The number of CPUs, for spin control */
730    static final int NCPUS = Runtime.getRuntime().availableProcessors();
731
732    /**
733     * The number of times to spin before blocking in timed waits.
734     * The value is empirically derived.
735     */
736    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
737
738    /**
739     * The number of times to spin before blocking in untimed waits.
740     * This is greater than timed value because untimed waits spin
741     * faster since they don't need to check times on each spin.
742     */
743    static final int maxUntimedSpins = maxTimedSpins * 32;
744
745    /**
746     * The number of nanoseconds for which it is faster to spin
747     * rather than to use timed park. A rough estimate suffices.
748     */
749    static final long spinForTimeoutThreshold = 1000L;
750
757      /**
758 <     * Wait nodes for Treiber stack representing wait queue for non-FJ
753 <     * tasks.
758 >     * Wait nodes for Treiber stack representing wait queue
759       */
760 <    static final class QNode {
761 <        QNode next;
760 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
761 >        final Phaser phaser;
762 >        final int phase;
763 >        final long startTime;
764 >        final long nanos;
765 >        final boolean timed;
766 >        final boolean interruptible;
767 >        volatile boolean wasInterrupted = false;
768          volatile Thread thread; // nulled to cancel wait
769 <        QNode() {
769 >        QNode next;
770 >        QNode(Phaser phaser, int phase, boolean interruptible,
771 >              boolean timed, long startTime, long nanos) {
772 >            this.phaser = phaser;
773 >            this.phase = phase;
774 >            this.timed = timed;
775 >            this.interruptible = interruptible;
776 >            this.startTime = startTime;
777 >            this.nanos = nanos;
778              thread = Thread.currentThread();
779          }
780 +        public boolean isReleasable() {
781 +            return (thread == null ||
782 +                    phaser.getPhase() != phase ||
783 +                    (interruptible && wasInterrupted) ||
784 +                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
785 +        }
786 +        public boolean block() {
787 +            if (Thread.interrupted()) {
788 +                wasInterrupted = true;
789 +                if (interruptible)
790 +                    return true;
791 +            }
792 +            if (!timed)
793 +                LockSupport.park(this);
794 +            else {
795 +                long waitTime = nanos - (System.nanoTime() - startTime);
796 +                if (waitTime <= 0)
797 +                    return true;
798 +                LockSupport.parkNanos(this, waitTime);
799 +            }
800 +            return isReleasable();
801 +        }
802          void signal() {
803              Thread t = thread;
804              if (t != null) {
# Line 765 | Line 806 | public class Phaser {
806                  LockSupport.unpark(t);
807              }
808          }
809 +        boolean doWait() {
810 +            if (thread != null) {
811 +                try {
812 +                    ForkJoinPool.managedBlock(this, false);
813 +                } catch (InterruptedException ie) {
814 +                }
815 +            }
816 +            return wasInterrupted;
817 +        }
818 +
819      }
820  
821      /**
822 <     * Removes and signals waiting threads from wait queue
822 >     * Removes and signals waiting threads from wait queue.
823       */
824      private void releaseWaiters(int phase) {
825          AtomicReference<QNode> head = queueFor(phase);
# Line 780 | Line 831 | public class Phaser {
831      }
832  
833      /**
834 +     * Tries to enqueue given node in the appropriate wait queue.
835 +     *
836 +     * @return true if successful
837 +     */
838 +    private boolean tryEnqueue(QNode node) {
839 +        AtomicReference<QNode> head = queueFor(node.phase);
840 +        return head.compareAndSet(node.next = head.get(), node);
841 +    }
842 +
843 +    /**
844       * Enqueues node and waits unless aborted or signalled.
845 +     *
846 +     * @return current phase
847       */
848      private int untimedWait(int phase) {
786        int spins = maxUntimedSpins;
849          QNode node = null;
788        boolean interrupted = false;
850          boolean queued = false;
851 +        boolean interrupted = false;
852          int p;
853          while ((p = getPhase()) == phase) {
854 <            interrupted = Thread.interrupted();
855 <            if (node != null) {
856 <                if (!queued) {
857 <                    AtomicReference<QNode> head = queueFor(phase);
858 <                    queued = head.compareAndSet(node.next = head.get(), node);
859 <                }
798 <                else if (node.thread != null)
799 <                    LockSupport.park(this);
800 <            }
801 <            else if (spins <= 0)
802 <                node = new QNode();
854 >            if (Thread.interrupted())
855 >                interrupted = true;
856 >            else if (node == null)
857 >                node = new QNode(this, phase, false, false, 0, 0);
858 >            else if (!queued)
859 >                queued = tryEnqueue(node);
860              else
861 <                --spins;
861 >                interrupted = node.doWait();
862          }
863          if (node != null)
864              node.thread = null;
865 +        releaseWaiters(phase);
866          if (interrupted)
867              Thread.currentThread().interrupt();
810        releaseWaiters(phase);
868          return p;
869      }
870  
871      /**
872 <     * Messier interruptible version
872 >     * Interruptible version
873 >     * @return current phase
874       */
875      private int interruptibleWait(int phase) throws InterruptedException {
818        int spins = maxUntimedSpins;
876          QNode node = null;
877          boolean queued = false;
878          boolean interrupted = false;
879          int p;
880 <        while ((p = getPhase()) == phase) {
881 <            if (interrupted = Thread.interrupted())
882 <                break;
883 <            if (node != null) {
884 <                if (!queued) {
885 <                    AtomicReference<QNode> head = queueFor(phase);
886 <                    queued = head.compareAndSet(node.next = head.get(), node);
830 <                }
831 <                else if (node.thread != null)
832 <                    LockSupport.park(this);
833 <            }
834 <            else if (spins <= 0)
835 <                node = new QNode();
880 >        while ((p = getPhase()) == phase && !interrupted) {
881 >            if (Thread.interrupted())
882 >                interrupted = true;
883 >            else if (node == null)
884 >                node = new QNode(this, phase, true, false, 0, 0);
885 >            else if (!queued)
886 >                queued = tryEnqueue(node);
887              else
888 <                --spins;
888 >                interrupted = node.doWait();
889          }
890          if (node != null)
891              node.thread = null;
892 +        if (p != phase || (p = getPhase()) != phase)
893 +            releaseWaiters(phase);
894          if (interrupted)
895              throw new InterruptedException();
843        releaseWaiters(phase);
896          return p;
897      }
898  
899      /**
900 <     * Even messier timeout version.
900 >     * Timeout version.
901 >     * @return current phase
902       */
903      private int timedWait(int phase, long nanos)
904          throws InterruptedException, TimeoutException {
905 +        long startTime = System.nanoTime();
906 +        QNode node = null;
907 +        boolean queued = false;
908 +        boolean interrupted = false;
909          int p;
910 <        if ((p = getPhase()) == phase) {
911 <            long lastTime = System.nanoTime();
912 <            int spins = maxTimedSpins;
913 <            QNode node = null;
914 <            boolean queued = false;
915 <            boolean interrupted = false;
916 <            while ((p = getPhase()) == phase) {
917 <                if (interrupted = Thread.interrupted())
918 <                    break;
919 <                long now = System.nanoTime();
920 <                if ((nanos -= now - lastTime) <= 0)
864 <                    break;
865 <                lastTime = now;
866 <                if (node != null) {
867 <                    if (!queued) {
868 <                        AtomicReference<QNode> head = queueFor(phase);
869 <                        queued = head.compareAndSet(node.next = head.get(), node);
870 <                    }
871 <                    else if (node.thread != null &&
872 <                             nanos > spinForTimeoutThreshold) {
873 <                        LockSupport.parkNanos(this, nanos);
874 <                    }
875 <                }
876 <                else if (spins <= 0)
877 <                    node = new QNode();
878 <                else
879 <                    --spins;
880 <            }
881 <            if (node != null)
882 <                node.thread = null;
883 <            if (interrupted)
884 <                throw new InterruptedException();
885 <            if (p == phase && (p = getPhase()) == phase)
886 <                throw new TimeoutException();
910 >        while ((p = getPhase()) == phase && !interrupted) {
911 >            if (Thread.interrupted())
912 >                interrupted = true;
913 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
914 >                break;
915 >            else if (node == null)
916 >                node = new QNode(this, phase, true, true, startTime, nanos);
917 >            else if (!queued)
918 >                queued = tryEnqueue(node);
919 >            else
920 >                interrupted = node.doWait();
921          }
922 <        releaseWaiters(phase);
922 >        if (node != null)
923 >            node.thread = null;
924 >        if (p != phase || (p = getPhase()) != phase)
925 >            releaseWaiters(phase);
926 >        if (interrupted)
927 >            throw new InterruptedException();
928 >        if (p == phase)
929 >            throw new TimeoutException();
930          return p;
931      }
932  
933 <    // Temporary Unsafe mechanics for preliminary release
933 >    // Unsafe mechanics for jsr166y 3rd party package.
934 >    private static sun.misc.Unsafe getUnsafe() {
935 >        try {
936 >            return sun.misc.Unsafe.getUnsafe();
937 >        } catch (SecurityException se) {
938 >            try {
939 >                return java.security.AccessController.doPrivileged
940 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
941 >                        public sun.misc.Unsafe run() throws Exception {
942 >                            return getUnsafeByReflection();
943 >                        }});
944 >            } catch (java.security.PrivilegedActionException e) {
945 >                throw new RuntimeException("Could not initialize intrinsics",
946 >                                           e.getCause());
947 >            }
948 >        }
949 >    }
950  
951 <    static final Unsafe _unsafe;
952 <    static final long stateOffset;
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 <    static {
959 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
960          try {
961 <            if (Phaser.class.getClassLoader() != null) {
962 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
963 <                f.setAccessible(true);
964 <                _unsafe = (Unsafe)f.get(null);
965 <            }
966 <            else
905 <                _unsafe = Unsafe.getUnsafe();
906 <            stateOffset = _unsafe.objectFieldOffset
907 <                (Phaser.class.getDeclaredField("state"));
908 <        } catch (Exception e) {
909 <            throw new RuntimeException("Could not initialize intrinsics", e);
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 <    final boolean casState(long cmp, long val) {
971 <        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
970 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
971 >    private static final long stateOffset =
972 >        fieldOffset("state", Phaser.class);
973 >
974 >    private final boolean casState(long cmp, long val) {
975 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
976      }
977   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines