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.4 by dl, Sat Sep 6 13:19:17 2008 UTC vs.
Revision 1.19 by jsr166, Fri Jul 24 23:47:01 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines