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.8 by jsr166, Mon Jan 5 05:50:47 2009 UTC vs.
Revision 1.35 by dl, Sun Aug 23 13:37:08 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   *
22 < * <li> The number of parties synchronizing on a phaser may vary over
23 < * time.  A task may register to be a party at any time, and may
24 < * deregister upon arriving at the barrier.  As is the case with most
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
22 > * <li> The number of parties <em>registered</em> to synchronize on a
23 > * phaser may vary over time.  Tasks may be registered at any time
24 > * (using methods {@link #register}, {@link #bulkRegister}, or forms
25 > * of constructors establishing initial numbers of parties), and may
26 > * optionally be deregistered upon any arrival (using {@link
27 > * #arriveAndDeregister}).  As is the case with most basic
28 > * synchronization constructs, registration and deregistration affect
29 > * only internal counts; they do not establish any further internal
30 > * bookkeeping, so tasks cannot query whether they are
31 > * registered. (However, you can introduce such bookkeeping by
32   * subclassing this class.)
33   *
34   * <li> Each generation has an associated phase value, starting at
35 < * zero, and advancing when all parties reach the barrier (wrapping
36 < * around to zero after reaching {@code Integer.MAX_VALUE}).
35 > * zero, and advancing when all parties arrive at the barrier
36 > * (wrapping around to zero after reaching {@code Integer.MAX_VALUE}).
37   *
38 < * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
39 < * Method {@code arriveAndAwaitAdvance} has effect analogous to
40 < * {@code CyclicBarrier.await}.  However, Phasers separate two
41 < * aspects of coordination, that may also be invoked independently:
38 > * <li> Like a {@code CyclicBarrier}, a phaser may be repeatedly
39 > * awaited.  Method {@link #arriveAndAwaitAdvance} has effect
40 > * analogous to {@link java.util.concurrent.CyclicBarrier#await
41 > * CyclicBarrier.await}.  However, phasers separate two aspects of
42 > * coordination, which may also be invoked independently:
43   *
44   * <ul>
45   *
46 < *   <li> Arriving at a barrier. Methods {@code arrive} and
47 < *       {@code arriveAndDeregister} do not block, but return
48 < *       the phase value current upon entry to the method.
49 < *
50 < *   <li> Awaiting others. Method {@code awaitAdvance} requires an
51 < *       argument indicating the entry phase, and returns when the
52 < *       barrier advances to a new phase.
46 > *   <li> Arriving at a barrier. Methods {@link #arrive} and
47 > *       {@link #arriveAndDeregister} do not block, but return
48 > *       an associated <em>arrival phase number</em>;
49 > *       that is, the phase number of the barrier to which the
50 > *       arrival applied.
51 > *
52 > *   <li> Awaiting others. Method {@link #awaitAdvance} requires an
53 > *       argument indicating an arrival phase number, and returns
54 > *       when the barrier advances to a new phase.
55   * </ul>
56   *
57   *
58   * <li> Barrier actions, performed by the task triggering a phase
59 < * advance while others may be waiting, are arranged by overriding
60 < * method {@code onAdvance}, that also controls termination.
61 < * Overriding this method may be used to similar but more flexible
62 < * effect as providing a barrier action to a CyclicBarrier.
59 > * advance, are arranged by overriding method {@link #onAdvance(int,
60 > * int)}, which also controls termination. Overriding this method is
61 > * similar to, but more flexible than, providing a barrier action to a
62 > * {@code CyclicBarrier}.
63   *
64   * <li> Phasers may enter a <em>termination</em> state in which all
65 < * await actions immediately return, indicating (via a negative phase
66 < * value) that execution is complete.  Termination is triggered by
67 < * executing the overridable {@code onAdvance} method that is invoked
68 < * each time the barrier is about to be tripped. When a Phaser is
65 > * actions immediately return without updating phaser state or waiting
66 > * for advance, and indicating (via a negative phase value) that
67 > * execution is complete.  Termination is triggered when an invocation
68 > * of {@code onAdvance} returns {@code true}.  When a phaser is
69   * controlling an action with a fixed number of iterations, it is
70   * often convenient to override this method to cause termination when
71 < * the current phase number reaches a threshold. Method
72 < * {@code forceTermination} is also available to abruptly release
73 < * waiting threads and allow them to terminate.
71 > * the current phase number reaches a threshold. Method {@link
72 > * #forceTermination} is also available to abruptly release waiting
73 > * threads and allow them to terminate.
74   *
75   * <li> Phasers may be tiered to reduce contention. Phasers with large
76   * numbers of parties that would otherwise experience heavy
# Line 74 | Line 80 | import java.lang.reflect.*;
80   *
81   * <li> By default, {@code awaitAdvance} continues to wait even if
82   * the waiting thread is interrupted. And unlike the case in
83 < * CyclicBarriers, exceptions encountered while tasks wait
83 > * {@code CyclicBarrier}, exceptions encountered while tasks wait
84   * interruptibly or with timeout do not change the state of the
85   * barrier. If necessary, you can perform any associated recovery
86   * within handlers of those exceptions, often after invoking
87   * {@code forceTermination}.
88   *
89 + * <li>Phasers may be used to coordinate tasks executing in a {@link
90 + * ForkJoinPool}, which will ensure sufficient parallelism to execute
91 + * tasks when others are blocked waiting for a phase to advance.
92 + *
93   * </ul>
94   *
95   * <p><b>Sample usages:</b>
96   *
97 < * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
98 < * a one-shot action serving a variable number of parties. The typical
99 < * idiom is for the method setting this up to first register, then
100 < * start the actions, then deregister, as in:
101 < *
102 < * <pre>
103 < *  void runTasks(List&lt;Runnable&gt; list) {
104 < *    final Phaser phaser = new Phaser(1); // "1" to register self
105 < *    for (Runnable r : list) {
106 < *      phaser.register();
107 < *      new Thread() {
108 < *        public void run() {
109 < *          phaser.arriveAndAwaitAdvance(); // await all creation
110 < *          r.run();
111 < *          phaser.arriveAndDeregister();   // signal completion
112 < *        }
113 < *      }.start();
97 > * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
98 > * to control a one-shot action serving a variable number of
99 > * parties. The typical idiom is for the method setting this up to
100 > * first register, then start the actions, then deregister, as in:
101 > *
102 > *  <pre> {@code
103 > * void runTasks(List<Runnable> tasks) {
104 > *   final Phaser phaser = new Phaser(1); // "1" to register self
105 > *   // create and start threads
106 > *   for (Runnable task : tasks) {
107 > *     phaser.register();
108 > *     new Thread() {
109 > *       public void run() {
110 > *         phaser.arriveAndAwaitAdvance(); // await all creation
111 > *         task.run();
112 > *       }
113 > *     }.start();
114   *   }
115   *
116 < *   doSomethingOnBehalfOfWorkers();
117 < *   phaser.arrive(); // allow threads to start
118 < *   int p = phaser.arriveAndDeregister(); // deregister self  ...
109 < *   p = phaser.awaitAdvance(p); // ... and await arrival
110 < *   otherActions(); // do other things while tasks execute
111 < *   phaser.awaitAdvance(p); // await final completion
112 < * }
113 < * </pre>
116 > *   // allow threads to start and deregister self
117 > *   phaser.arriveAndDeregister();
118 > * }}</pre>
119   *
120   * <p>One way to cause a set of threads to repeatedly perform actions
121   * for a given number of iterations is to override {@code onAdvance}:
122   *
123 < * <pre>
124 < *  void startTasks(List&lt;Runnable&gt; list, final int iterations) {
125 < *    final Phaser phaser = new Phaser() {
126 < *       public boolean onAdvance(int phase, int registeredParties) {
127 < *         return phase &gt;= iterations || registeredParties == 0;
123 > *  <pre> {@code
124 > * void startTasks(List<Runnable> tasks, final int iterations) {
125 > *   final Phaser phaser = new Phaser() {
126 > *     public boolean onAdvance(int phase, int registeredParties) {
127 > *       return phase >= iterations || registeredParties == 0;
128 > *     }
129 > *   };
130 > *   phaser.register();
131 > *   for (Runnable task : tasks) {
132 > *     phaser.register();
133 > *     new Thread() {
134 > *       public void run() {
135 > *         do {
136 > *           task.run();
137 > *           phaser.arriveAndAwaitAdvance();
138 > *         } while(!phaser.isTerminated();
139   *       }
140 < *    };
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();
140 > *     }.start();
141   *   }
142   *   phaser.arriveAndDeregister(); // deregister self, don't wait
143 < * }
139 < * </pre>
143 > * }}</pre>
144   *
145 < * <p> To create a set of tasks using a tree of Phasers,
145 > * <p>To create a set of tasks using a tree of phasers,
146   * you could use code of the following form, assuming a
147 < * Task class with a constructor accepting a Phaser that
147 > * Task class with a constructor accepting a phaser that
148   * it registers for upon construction:
149 < * <pre>
150 < *  void build(Task[] actions, int lo, int hi, Phaser b) {
151 < *    int step = (hi - lo) / TASKS_PER_PHASER;
152 < *    if (step &gt; 1) {
153 < *       int i = lo;
154 < *       while (i &lt; hi) {
155 < *         int r = Math.min(i + step, hi);
156 < *         build(actions, i, r, new Phaser(b));
157 < *         i = r;
158 < *       }
159 < *    }
160 < *    else {
161 < *      for (int i = lo; i &lt; hi; ++i)
162 < *        actions[i] = new Task(b);
163 < *        // assumes new Task(b) performs b.register()
164 < *    }
165 < *  }
166 < *  // .. initially called, for n tasks via
163 < *  build(new Task[n], 0, n, new Phaser());
164 < * </pre>
149 > *  <pre> {@code
150 > * void build(Task[] actions, int lo, int hi, Phaser b) {
151 > *   int step = (hi - lo) / TASKS_PER_PHASER;
152 > *   if (step > 1) {
153 > *     int i = lo;
154 > *     while (i < hi) {
155 > *       int r = Math.min(i + step, hi);
156 > *       build(actions, i, r, new Phaser(b));
157 > *       i = r;
158 > *     }
159 > *   } else {
160 > *     for (int i = lo; i < hi; ++i)
161 > *       actions[i] = new Task(b);
162 > *       // assumes new Task(b) performs b.register()
163 > *   }
164 > * }
165 > * // .. initially called, for n tasks via
166 > * build(new Task[n], 0, n, new Phaser());}</pre>
167   *
168   * The best value of {@code TASKS_PER_PHASER} depends mainly on
169   * expected barrier synchronization rates. A value as low as four may
# Line 172 | Line 174 | import java.lang.reflect.*;
174   *
175   * <p><b>Implementation notes</b>: This implementation restricts the
176   * maximum number of parties to 65535. Attempts to register additional
177 < * parties result in IllegalStateExceptions. However, you can and
177 > * parties result in {@code IllegalStateException}. However, you can and
178   * should create tiered phasers to accommodate arbitrarily large sets
179   * of participants.
180 + *
181 + * @since 1.7
182 + * @author Doug Lea
183   */
184   public class Phaser {
185      /*
# Line 199 | Line 204 | public class Phaser {
204       * and encoding simple, and keeping race windows short.
205       *
206       * Note: there are some cheats in arrive() that rely on unarrived
207 <     * being lowest 16 bits.
207 >     * count being lowest 16 bits.
208       */
209      private volatile long state;
210  
211      private static final int ushortBits = 16;
212 <    private static final int ushortMask =  (1 << ushortBits) - 1;
213 <    private static final int phaseMask = 0x7fffffff;
212 >    private static final int ushortMask = 0xffff;
213 >    private static final int phaseMask  = 0x7fffffff;
214  
215      private static int unarrivedOf(long s) {
216 <        return (int)(s & ushortMask);
216 >        return (int) (s & ushortMask);
217      }
218  
219      private static int partiesOf(long s) {
220 <        return (int)(s & (ushortMask << 16)) >>> 16;
220 >        return ((int) s) >>> 16;
221      }
222  
223      private static int phaseOf(long s) {
224 <        return (int)(s >>> 32);
224 >        return (int) (s >>> 32);
225      }
226  
227      private static int arrivedOf(long s) {
# Line 224 | Line 229 | public class Phaser {
229      }
230  
231      private static long stateFor(int phase, int parties, int unarrived) {
232 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
232 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
233 >                (long) unarrived);
234      }
235  
236      private static long trippedStateFor(int phase, int parties) {
237 <        return (((long)phase) << 32) | ((parties << 16) | parties);
237 >        long lp = (long) parties;
238 >        return (((long) phase) << 32) | (lp << 16) | lp;
239      }
240  
241 <    private static IllegalStateException badBounds(int parties, int unarrived) {
242 <        return new IllegalStateException
243 <            ("Attempt to set " + unarrived +
244 <             " unarrived of " + parties + " parties");
241 >    /**
242 >     * Returns message string for bad bounds exceptions.
243 >     */
244 >    private static String badBounds(int parties, int unarrived) {
245 >        return ("Attempt to set " + unarrived +
246 >                " unarrived of " + parties + " parties");
247      }
248  
249      /**
# Line 243 | Line 252 | public class Phaser {
252      private final Phaser parent;
253  
254      /**
255 <     * The root of Phaser tree. Equals this if not in a tree.  Used to
255 >     * The root of phaser tree. Equals this if not in a tree.  Used to
256       * support faster state push-down.
257       */
258      private final Phaser root;
# Line 251 | Line 260 | public class Phaser {
260      // Wait queues
261  
262      /**
263 <     * Heads of Treiber stacks waiting for nonFJ threads. To eliminate
263 >     * Heads of Treiber stacks for waiting threads. To eliminate
264       * contention while releasing some threads while adding others, we
265       * use two of them, alternating across even and odd phases.
266       */
# Line 259 | Line 268 | public class Phaser {
268      private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
269  
270      private AtomicReference<QNode> queueFor(int phase) {
271 <        return (phase & 1) == 0? evenQ : oddQ;
271 >        return ((phase & 1) == 0) ? evenQ : oddQ;
272      }
273  
274      /**
# Line 267 | Line 276 | public class Phaser {
276       * root if necessary.
277       */
278      private long getReconciledState() {
279 <        return parent == null? state : reconcileState();
279 >        return (parent == null) ? state : reconcileState();
280      }
281  
282      /**
# Line 294 | Line 303 | public class Phaser {
303      }
304  
305      /**
306 <     * Creates a new Phaser without any initially registered parties,
307 <     * initial phase number 0, and no parent.
306 >     * Creates a new phaser without any initially registered parties,
307 >     * initial phase number 0, and no parent. Any thread using this
308 >     * phaser will need to first register for it.
309       */
310      public Phaser() {
311          this(null);
312      }
313  
314      /**
315 <     * Creates a new Phaser with the given numbers of registered
315 >     * Creates a new phaser with the given numbers of registered
316       * unarrived parties, initial phase number 0, and no parent.
317 <     * @param parties the number of parties required to trip barrier.
317 >     *
318 >     * @param parties the number of parties required to trip barrier
319       * @throws IllegalArgumentException if parties less than zero
320 <     * or greater than the maximum number of parties supported.
320 >     * or greater than the maximum number of parties supported
321       */
322      public Phaser(int parties) {
323          this(null, parties);
324      }
325  
326      /**
327 <     * Creates a new Phaser with the given parent, without any
327 >     * Creates a new phaser with the given parent, without any
328       * initially registered parties. If parent is non-null this phaser
329       * is registered with the parent and its initial phase number is
330       * the same as that of parent phaser.
331 <     * @param parent the parent phaser.
331 >     *
332 >     * @param parent the parent phaser
333       */
334      public Phaser(Phaser parent) {
335          int phase = 0;
# Line 332 | Line 344 | public class Phaser {
344      }
345  
346      /**
347 <     * Creates a new Phaser with the given parent and numbers of
348 <     * registered unarrived parties. If parent is non-null this phaser
347 >     * Creates a new phaser with the given parent and numbers of
348 >     * registered unarrived parties. If parent is non-null, this phaser
349       * is registered with the parent and its initial phase number is
350       * the same as that of parent phaser.
351 <     * @param parent the parent phaser.
352 <     * @param parties the number of parties required to trip barrier.
351 >     *
352 >     * @param parent the parent phaser
353 >     * @param parties the number of parties required to trip barrier
354       * @throws IllegalArgumentException if parties less than zero
355 <     * or greater than the maximum number of parties supported.
355 >     * or greater than the maximum number of parties supported
356       */
357      public Phaser(Phaser parent, int parties) {
358          if (parties < 0 || parties > ushortMask)
# Line 357 | Line 370 | public class Phaser {
370  
371      /**
372       * Adds a new unarrived party to this phaser.
373 <     * @return the current barrier phase number upon registration
373 >     *
374 >     * @return the arrival phase number to which this registration applied
375       * @throws IllegalStateException if attempting to register more
376 <     * than the maximum supported number of parties.
376 >     * than the maximum supported number of parties
377       */
378      public int register() {
379          return doRegister(1);
# Line 367 | Line 381 | public class Phaser {
381  
382      /**
383       * Adds the given number of new unarrived parties to this phaser.
384 <     * @param parties the number of parties required to trip barrier.
385 <     * @return the current barrier phase number upon registration
384 >     *
385 >     * @param parties the number of parties required to trip barrier
386 >     * @return the arrival phase number to which this registration applied
387       * @throws IllegalStateException if attempting to register more
388 <     * than the maximum supported number of parties.
388 >     * than the maximum supported number of parties
389       */
390      public int bulkRegister(int parties) {
391          if (parties < 0)
# Line 393 | Line 408 | public class Phaser {
408              if (phase < 0)
409                  break;
410              if (parties > ushortMask || unarrived > ushortMask)
411 <                throw badBounds(parties, unarrived);
411 >                throw new IllegalStateException(badBounds(parties, unarrived));
412              if (phase == phaseOf(root.state) &&
413                  casState(s, stateFor(phase, parties, unarrived)))
414                  break;
# Line 405 | Line 420 | public class Phaser {
420       * Arrives at the barrier, but does not wait for others.  (You can
421       * in turn wait for others via {@link #awaitAdvance}).
422       *
423 <     * @return the barrier phase number upon entry to this method, or a
409 <     * negative value if terminated;
423 >     * @return the arrival phase number, or a negative value if terminated
424       * @throws IllegalStateException if not terminated and the number
425 <     * of unarrived parties would become negative.
425 >     * of unarrived parties would become negative
426       */
427      public int arrive() {
428          int phase;
429          for (;;) {
430              long s = state;
431              phase = phaseOf(s);
432 +            if (phase < 0)
433 +                break;
434              int parties = partiesOf(s);
435              int unarrived = unarrivedOf(s) - 1;
436              if (unarrived > 0) {        // Not the last arrival
# Line 426 | Line 442 | public class Phaser {
442                  if (par == null) {      // directly trip
443                      if (casState
444                          (s,
445 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
445 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
446                                           ((phase + 1) & phaseMask), parties))) {
447                          releaseWaiters(phase);
448                          break;
# Line 440 | Line 456 | public class Phaser {
456                      }
457                  }
458              }
443            else if (phase < 0) // Don't throw exception if terminated
444                break;
459              else if (phase != phaseOf(root.state)) // or if unreconciled
460                  reconcileState();
461              else
462 <                throw badBounds(parties, unarrived);
462 >                throw new IllegalStateException(badBounds(parties, unarrived));
463          }
464          return phase;
465      }
466  
467      /**
468 <     * Arrives at the barrier, and deregisters from it, without
469 <     * waiting for others. Deregistration reduces number of parties
468 >     * Arrives at the barrier and deregisters from it without waiting
469 >     * for others. Deregistration reduces the number of parties
470       * required to trip the barrier in future phases.  If this phaser
471       * has a parent, and deregistration causes this phaser to have
472 <     * zero parties, this phaser is also deregistered from its parent.
472 >     * zero parties, this phaser also arrives at and is deregistered
473 >     * from its parent.
474       *
475 <     * @return the current barrier phase number upon entry to
461 <     * this method, or a negative value if terminated;
475 >     * @return the arrival phase number, or a negative value if terminated
476       * @throws IllegalStateException if not terminated and the number
477 <     * of registered or unarrived parties would become negative.
477 >     * of registered or unarrived parties would become negative
478       */
479      public int arriveAndDeregister() {
480          // similar code to arrive, but too different to merge
# Line 469 | Line 483 | public class Phaser {
483          for (;;) {
484              long s = state;
485              phase = phaseOf(s);
486 +            if (phase < 0)
487 +                break;
488              int parties = partiesOf(s) - 1;
489              int unarrived = unarrivedOf(s) - 1;
490              if (parties >= 0) {
# Line 487 | Line 503 | public class Phaser {
503                  if (unarrived == 0) {
504                      if (casState
505                          (s,
506 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
506 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
507                                           ((phase + 1) & phaseMask), parties))) {
508                          releaseWaiters(phase);
509                          break;
510                      }
511                      continue;
512                  }
497                if (phase < 0)
498                    break;
513                  if (par != null && phase != phaseOf(root.state)) {
514                      reconcileState();
515                      continue;
516                  }
517              }
518 <            throw badBounds(parties, unarrived);
518 >            throw new IllegalStateException(badBounds(parties, unarrived));
519          }
520          return phase;
521      }
522  
523      /**
524       * Arrives at the barrier and awaits others. Equivalent in effect
525 <     * to {@code awaitAdvance(arrive())}.  If you instead need to
526 <     * await with interruption of timeout, and/or deregister upon
527 <     * arrival, you can arrange them using analogous constructions.
528 <     * @return the phase on entry to this method
525 >     * to {@code awaitAdvance(arrive())}.  If you need to await with
526 >     * interruption or timeout, you can arrange this with an analogous
527 >     * construction using one of the other forms of the awaitAdvance
528 >     * method.  If instead you need to deregister upon arrival use
529 >     * {@code arriveAndDeregister}.
530 >     *
531 >     * @return the arrival phase number, or a negative number if terminated
532       * @throws IllegalStateException if not terminated and the number
533 <     * of unarrived parties would become negative.
533 >     * of unarrived parties would become negative
534       */
535      public int arriveAndAwaitAdvance() {
536          return awaitAdvance(arrive());
537      }
538  
539      /**
540 <     * Awaits the phase of the barrier to advance from the given
541 <     * value, or returns immediately if argument is negative or this
542 <     * barrier is terminated.
543 <     * @param phase the phase on entry to this method
544 <     * @return the phase on exit from this method
540 >     * Awaits the phase of the barrier to advance from the given phase
541 >     * value, returning immediately if the current phase of the
542 >     * barrier is not equal to the given phase value or this barrier
543 >     * is terminated.
544 >     *
545 >     * @param phase an arrival phase number, or negative value if
546 >     * terminated; this argument is normally the value returned by a
547 >     * previous call to {@code arrive} or its variants
548 >     * @return the next arrival phase number, or a negative value
549 >     * if terminated or argument is negative
550       */
551      public int awaitAdvance(int phase) {
552          if (phase < 0)
# Line 533 | Line 555 | public class Phaser {
555          int p = phaseOf(s);
556          if (p != phase)
557              return p;
558 <        if (unarrivedOf(s) == 0)
558 >        if (unarrivedOf(s) == 0 && parent != null)
559              parent.awaitAdvance(phase);
560          // Fall here even if parent waited, to reconcile and help release
561          return untimedWait(phase);
562      }
563  
564      /**
565 <     * Awaits the phase of the barrier to advance from the given
566 <     * value, or returns immediately if argument is negative or this
567 <     * barrier is terminated, or throws InterruptedException if
568 <     * interrupted while waiting.
569 <     * @param phase the phase on entry to this method
570 <     * @return the phase on exit from this method
565 >     * Awaits the phase of the barrier to advance from the given phase
566 >     * value, throwing {@code InterruptedException} if interrupted while
567 >     * waiting, or returning immediately if the current phase of the
568 >     * barrier is not equal to the given phase value or this barrier
569 >     * is terminated.
570 >     *
571 >     * @param phase an arrival phase number, or negative value if
572 >     * terminated; this argument is normally the value returned by a
573 >     * previous call to {@code arrive} or its variants
574 >     * @return the next arrival phase number, or a negative value
575 >     * if terminated or argument is negative
576       * @throws InterruptedException if thread interrupted while waiting
577       */
578 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
578 >    public int awaitAdvanceInterruptibly(int phase)
579 >        throws InterruptedException {
580          if (phase < 0)
581              return phase;
582          long s = getReconciledState();
583          int p = phaseOf(s);
584          if (p != phase)
585              return p;
586 <        if (unarrivedOf(s) != 0)
586 >        if (unarrivedOf(s) == 0 && parent != null)
587              parent.awaitAdvanceInterruptibly(phase);
588          return interruptibleWait(phase);
589      }
590  
591      /**
592 <     * Awaits the phase of the barrier to advance from the given value
593 <     * or the given timeout elapses, or returns immediately if
594 <     * argument is negative or this barrier is terminated.
595 <     * @param phase the phase on entry to this method
596 <     * @return the phase on exit from this method
592 >     * Awaits the phase of the barrier to advance from the given phase
593 >     * value or the given timeout to elapse, throwing
594 >     * {@code InterruptedException} if interrupted while waiting, or
595 >     * returning immediately if the current phase of the barrier is not
596 >     * equal to the given phase value or this barrier is terminated.
597 >     *
598 >     * @param phase an arrival phase number, or negative value if
599 >     * terminated; this argument is normally the value returned by a
600 >     * previous call to {@code arrive} or its variants
601 >     * @param timeout how long to wait before giving up, in units of
602 >     *        {@code unit}
603 >     * @param unit a {@code TimeUnit} determining how to interpret the
604 >     *        {@code timeout} parameter
605 >     * @return the next arrival phase number, or a negative value
606 >     * if terminated or argument is negative
607       * @throws InterruptedException if thread interrupted while waiting
608       * @throws TimeoutException if timed out while waiting
609       */
610 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
610 >    public int awaitAdvanceInterruptibly(int phase,
611 >                                         long timeout, TimeUnit unit)
612          throws InterruptedException, TimeoutException {
613          if (phase < 0)
614              return phase;
# Line 577 | Line 616 | public class Phaser {
616          int p = phaseOf(s);
617          if (p != phase)
618              return p;
619 <        if (unarrivedOf(s) == 0)
619 >        if (unarrivedOf(s) == 0 && parent != null)
620              parent.awaitAdvanceInterruptibly(phase, timeout, unit);
621          return timedWait(phase, unit.toNanos(timeout));
622      }
# Line 610 | Line 649 | public class Phaser {
649       * Returns the current phase number. The maximum phase number is
650       * {@code Integer.MAX_VALUE}, after which it restarts at
651       * zero. Upon termination, the phase number is negative.
652 +     *
653       * @return the phase number, or a negative value if terminated
654       */
655      public final int getPhase() {
# Line 617 | Line 657 | public class Phaser {
657      }
658  
659      /**
620     * Returns true if the current phase number equals the given phase.
621     * @param phase the phase
622     * @return true if the current phase number equals the given phase.
623     */
624    public final boolean hasPhase(int phase) {
625        return phaseOf(getReconciledState()) == phase;
626    }
627
628    /**
660       * Returns the number of parties registered at this barrier.
661 +     *
662       * @return the number of parties
663       */
664      public int getRegisteredParties() {
# Line 636 | Line 668 | public class Phaser {
668      /**
669       * Returns the number of parties that have arrived at the current
670       * phase of this barrier.
671 +     *
672       * @return the number of arrived parties
673       */
674      public int getArrivedParties() {
# Line 645 | Line 678 | public class Phaser {
678      /**
679       * Returns the number of registered parties that have not yet
680       * arrived at the current phase of this barrier.
681 +     *
682       * @return the number of unarrived parties
683       */
684      public int getUnarrivedParties() {
# Line 652 | Line 686 | public class Phaser {
686      }
687  
688      /**
689 <     * Returns the parent of this phaser, or null if none.
690 <     * @return the parent of this phaser, or null if none.
689 >     * Returns the parent of this phaser, or {@code null} if none.
690 >     *
691 >     * @return the parent of this phaser, or {@code null} if none
692       */
693      public Phaser getParent() {
694          return parent;
# Line 662 | Line 697 | public class Phaser {
697      /**
698       * Returns the root ancestor of this phaser, which is the same as
699       * this phaser if it has no parent.
700 <     * @return the root ancestor of this phaser.
700 >     *
701 >     * @return the root ancestor of this phaser
702       */
703      public Phaser getRoot() {
704          return root;
705      }
706  
707      /**
708 <     * Returns true if this barrier has been terminated.
709 <     * @return true if this barrier has been terminated
708 >     * Returns {@code true} if this barrier has been terminated.
709 >     *
710 >     * @return {@code true} if this barrier has been terminated
711       */
712      public boolean isTerminated() {
713          return getPhase() < 0;
# Line 680 | Line 717 | public class Phaser {
717       * Overridable method to perform an action upon phase advance, and
718       * to control termination. This method is invoked whenever the
719       * barrier is tripped (and thus all other waiting parties are
720 <     * dormant). If it returns true, then, rather than advance the
721 <     * phase number, this barrier will be set to a final termination
722 <     * state, and subsequent calls to {@code isTerminated} will
723 <     * return true.
720 >     * dormant). If it returns {@code true}, then, rather than advance
721 >     * the phase number, this barrier will be set to a final
722 >     * termination state, and subsequent calls to {@link #isTerminated}
723 >     * will return true.
724       *
725 <     * <p> The default version returns true when the number of
725 >     * <p>The default version returns {@code true} when the number of
726       * registered parties is zero. Normally, overrides that arrange
727       * termination for other reasons should also preserve this
728       * property.
729       *
730 <     * <p> You may override this method to perform an action with side
730 >     * <p>You may override this method to perform an action with side
731       * effects visible to participating tasks, but it is in general
732       * only sensible to do so in designs where all parties register
733 <     * before any arrive, and all {@code awaitAdvance} at each phase.
734 <     * Otherwise, you cannot ensure lack of interference. In
735 <     * particular, this method may be invoked more than once per
699 <     * transition if other parties successfully register while the
700 <     * invocation of this method is in progress, thus postponing the
701 <     * transition until those parties also arrive, re-triggering this
702 <     * method.
733 >     * before any arrive, and all {@link #awaitAdvance} at each phase.
734 >     * Otherwise, you cannot ensure lack of interference from other
735 >     * parties during the invocation of this method.
736       *
737       * @param phase the phase number on entering the barrier
738 <     * @param registeredParties the current number of registered
739 <     * parties.
707 <     * @return true if this barrier should terminate
738 >     * @param registeredParties the current number of registered parties
739 >     * @return {@code true} if this barrier should terminate
740       */
741      protected boolean onAdvance(int phase, int registeredParties) {
742          return registeredParties <= 0;
# Line 713 | Line 745 | public class Phaser {
745      /**
746       * Returns a string identifying this phaser, as well as its
747       * state.  The state, in brackets, includes the String {@code
748 <     * "phase ="} followed by the phase number, {@code "parties ="}
748 >     * "phase = "} followed by the phase number, {@code "parties = "}
749       * followed by the number of registered parties, and {@code
750 <     * "arrived ="} followed by the number of arrived parties
750 >     * "arrived = "} followed by the number of arrived parties.
751       *
752       * @return a string identifying this barrier, as well as its state
753       */
754      public String toString() {
755          long s = getReconciledState();
756 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
756 >        return super.toString() +
757 >            "[phase = " + phaseOf(s) +
758 >            " parties = " + partiesOf(s) +
759 >            " arrived = " + arrivedOf(s) + "]";
760      }
761  
762      // methods for waiting
763  
729    /** The number of CPUs, for spin control */
730    static final int NCPUS = Runtime.getRuntime().availableProcessors();
731
764      /**
765 <     * The number of times to spin before blocking in timed waits.
734 <     * The value is empirically derived.
765 >     * Wait nodes for Treiber stack representing wait queue
766       */
767 <    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
768 <
769 <    /**
770 <     * The number of times to spin before blocking in untimed waits.
771 <     * This is greater than timed value because untimed waits spin
772 <     * faster since they don't need to check times on each spin.
773 <     */
774 <    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 <
751 <    /**
752 <     * Wait nodes for Treiber stack representing wait queue for non-FJ
753 <     * tasks.
754 <     */
755 <    static final class QNode {
756 <        QNode next;
767 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
768 >        final Phaser phaser;
769 >        final int phase;
770 >        final long startTime;
771 >        final long nanos;
772 >        final boolean timed;
773 >        final boolean interruptible;
774 >        volatile boolean wasInterrupted = false;
775          volatile Thread thread; // nulled to cancel wait
776 <        QNode() {
776 >        QNode next;
777 >        QNode(Phaser phaser, int phase, boolean interruptible,
778 >              boolean timed, long startTime, long nanos) {
779 >            this.phaser = phaser;
780 >            this.phase = phase;
781 >            this.timed = timed;
782 >            this.interruptible = interruptible;
783 >            this.startTime = startTime;
784 >            this.nanos = nanos;
785              thread = Thread.currentThread();
786          }
787 +        public boolean isReleasable() {
788 +            return (thread == null ||
789 +                    phaser.getPhase() != phase ||
790 +                    (interruptible && wasInterrupted) ||
791 +                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
792 +        }
793 +        public boolean block() {
794 +            if (Thread.interrupted()) {
795 +                wasInterrupted = true;
796 +                if (interruptible)
797 +                    return true;
798 +            }
799 +            if (!timed)
800 +                LockSupport.park(this);
801 +            else {
802 +                long waitTime = nanos - (System.nanoTime() - startTime);
803 +                if (waitTime <= 0)
804 +                    return true;
805 +                LockSupport.parkNanos(this, waitTime);
806 +            }
807 +            return isReleasable();
808 +        }
809          void signal() {
810              Thread t = thread;
811              if (t != null) {
# Line 765 | Line 813 | public class Phaser {
813                  LockSupport.unpark(t);
814              }
815          }
816 +        boolean doWait() {
817 +            if (thread != null) {
818 +                try {
819 +                    ForkJoinPool.managedBlock(this, false);
820 +                } catch (InterruptedException ie) {
821 +                }
822 +            }
823 +            return wasInterrupted;
824 +        }
825 +
826      }
827  
828      /**
829 <     * Removes and signals waiting threads from wait queue
829 >     * Removes and signals waiting threads from wait queue.
830       */
831      private void releaseWaiters(int phase) {
832          AtomicReference<QNode> head = queueFor(phase);
# Line 780 | Line 838 | public class Phaser {
838      }
839  
840      /**
841 +     * Tries to enqueue given node in the appropriate wait queue.
842 +     *
843 +     * @return true if successful
844 +     */
845 +    private boolean tryEnqueue(QNode node) {
846 +        AtomicReference<QNode> head = queueFor(node.phase);
847 +        return head.compareAndSet(node.next = head.get(), node);
848 +    }
849 +
850 +    /**
851       * Enqueues node and waits unless aborted or signalled.
852 +     *
853 +     * @return current phase
854       */
855      private int untimedWait(int phase) {
786        int spins = maxUntimedSpins;
856          QNode node = null;
788        boolean interrupted = false;
857          boolean queued = false;
858 +        boolean interrupted = false;
859          int p;
860          while ((p = getPhase()) == phase) {
861 <            interrupted = Thread.interrupted();
862 <            if (node != null) {
863 <                if (!queued) {
864 <                    AtomicReference<QNode> head = queueFor(phase);
865 <                    queued = head.compareAndSet(node.next = head.get(), node);
866 <                }
798 <                else if (node.thread != null)
799 <                    LockSupport.park(this);
800 <            }
801 <            else if (spins <= 0)
802 <                node = new QNode();
861 >            if (Thread.interrupted())
862 >                interrupted = true;
863 >            else if (node == null)
864 >                node = new QNode(this, phase, false, false, 0, 0);
865 >            else if (!queued)
866 >                queued = tryEnqueue(node);
867              else
868 <                --spins;
868 >                interrupted = node.doWait();
869          }
870          if (node != null)
871              node.thread = null;
872 +        releaseWaiters(phase);
873          if (interrupted)
874              Thread.currentThread().interrupt();
810        releaseWaiters(phase);
875          return p;
876      }
877  
878      /**
879 <     * Messier interruptible version
879 >     * Interruptible version
880 >     * @return current phase
881       */
882      private int interruptibleWait(int phase) throws InterruptedException {
818        int spins = maxUntimedSpins;
883          QNode node = null;
884          boolean queued = false;
885          boolean interrupted = false;
886          int p;
887 <        while ((p = getPhase()) == phase) {
888 <            if (interrupted = Thread.interrupted())
889 <                break;
890 <            if (node != null) {
891 <                if (!queued) {
892 <                    AtomicReference<QNode> head = queueFor(phase);
893 <                    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();
887 >        while ((p = getPhase()) == phase && !interrupted) {
888 >            if (Thread.interrupted())
889 >                interrupted = true;
890 >            else if (node == null)
891 >                node = new QNode(this, phase, true, false, 0, 0);
892 >            else if (!queued)
893 >                queued = tryEnqueue(node);
894              else
895 <                --spins;
895 >                interrupted = node.doWait();
896          }
897          if (node != null)
898              node.thread = null;
899 +        if (p != phase || (p = getPhase()) != phase)
900 +            releaseWaiters(phase);
901          if (interrupted)
902              throw new InterruptedException();
843        releaseWaiters(phase);
903          return p;
904      }
905  
906      /**
907 <     * Even messier timeout version.
907 >     * Timeout version.
908 >     * @return current phase
909       */
910      private int timedWait(int phase, long nanos)
911          throws InterruptedException, TimeoutException {
912 +        long startTime = System.nanoTime();
913 +        QNode node = null;
914 +        boolean queued = false;
915 +        boolean interrupted = false;
916          int p;
917 <        if ((p = getPhase()) == phase) {
918 <            long lastTime = System.nanoTime();
919 <            int spins = maxTimedSpins;
920 <            QNode node = null;
921 <            boolean queued = false;
922 <            boolean interrupted = false;
923 <            while ((p = getPhase()) == phase) {
924 <                if (interrupted = Thread.interrupted())
925 <                    break;
926 <                long now = System.nanoTime();
927 <                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();
917 >        while ((p = getPhase()) == phase && !interrupted) {
918 >            if (Thread.interrupted())
919 >                interrupted = true;
920 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
921 >                break;
922 >            else if (node == null)
923 >                node = new QNode(this, phase, true, true, startTime, nanos);
924 >            else if (!queued)
925 >                queued = tryEnqueue(node);
926 >            else
927 >                interrupted = node.doWait();
928          }
929 <        releaseWaiters(phase);
929 >        if (node != null)
930 >            node.thread = null;
931 >        if (p != phase || (p = getPhase()) != phase)
932 >            releaseWaiters(phase);
933 >        if (interrupted)
934 >            throw new InterruptedException();
935 >        if (p == phase)
936 >            throw new TimeoutException();
937          return p;
938      }
939  
940 <    // Temporary Unsafe mechanics for preliminary release
940 >    // Unsafe mechanics
941 >
942 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
943 >    private static final long stateOffset =
944 >        objectFieldOffset("state", Phaser.class);
945  
946 <    static final Unsafe _unsafe;
947 <    static final long stateOffset;
946 >    private final boolean casState(long cmp, long val) {
947 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
948 >    }
949  
950 <    static {
950 >    private static long objectFieldOffset(String field, Class<?> klazz) {
951          try {
952 <            if (Phaser.class.getClassLoader() != null) {
953 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
954 <                f.setAccessible(true);
955 <                _unsafe = (Unsafe)f.get(null);
956 <            }
957 <            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);
952 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
953 >        } catch (NoSuchFieldException e) {
954 >            // Convert Exception to corresponding Error
955 >            NoSuchFieldError error = new NoSuchFieldError(field);
956 >            error.initCause(e);
957 >            throw error;
958          }
959      }
960  
961 <    final boolean casState(long cmp, long val) {
962 <        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
961 >    /**
962 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
963 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
964 >     * into a jdk.
965 >     *
966 >     * @return a sun.misc.Unsafe
967 >     */
968 >    private static sun.misc.Unsafe getUnsafe() {
969 >        try {
970 >            return sun.misc.Unsafe.getUnsafe();
971 >        } catch (SecurityException se) {
972 >            try {
973 >                return java.security.AccessController.doPrivileged
974 >                    (new java.security
975 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
976 >                        public sun.misc.Unsafe run() throws Exception {
977 >                            java.lang.reflect.Field f = sun.misc
978 >                                .Unsafe.class.getDeclaredField("theUnsafe");
979 >                            f.setAccessible(true);
980 >                            return (sun.misc.Unsafe) f.get(null);
981 >                        }});
982 >            } catch (java.security.PrivilegedActionException e) {
983 >                throw new RuntimeException("Could not initialize intrinsics",
984 >                                           e.getCause());
985 >            }
986 >        }
987      }
988   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines