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.12 by jsr166, Thu Mar 19 05:10:42 2009 UTC vs.
Revision 1.35 by dl, Sun Aug 23 13:37:08 2009 UTC

# Line 7 | Line 7
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;
12 import sun.misc.Unsafe;
13 import java.lang.reflect.*;
13  
14   /**
15   * A reusable synchronization barrier, similar in functionality to a
# Line 20 | Line 19 | import java.lang.reflect.*;
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
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   * 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 by executing the
68 < * overridable {@code onAdvance} method that is invoked each time the
69 < * barrier is about to be tripped. When a Phaser is controlling an
70 < * action with a fixed number of iterations, it is often convenient to
71 < * override this method to cause termination when the current phase
72 < * number reaches a threshold. Method {@code forceTermination} is also
73 < * available to abruptly release waiting threads and allow them to
69 < * terminate.
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 {@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 76 | 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 ensure lack of starvation when used by ForkJoinTasks.
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  ...
113 < *   p = phaser.awaitAdvance(p); // ... and await arrival
114 < *   otherActions(); // do other things while tasks execute
115 < *   phaser.awaitAdvance(p); // await final completion
116 < * }
117 < * </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 < *    };
129 < *    phaser.register();
130 < *    for (Runnable r : list) {
131 < *      phaser.register();
132 < *      new Thread() {
133 < *        public void run() {
134 < *           do {
135 < *             r.run();
136 < *             phaser.arriveAndAwaitAdvance();
137 < *           } while(!phaser.isTerminated();
138 < *        }
139 < *      }.start();
140 > *     }.start();
141   *   }
142   *   phaser.arriveAndDeregister(); // deregister self, don't wait
143 < * }
143 < * </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
167 < *  build(new Task[n], 0, n, new Phaser());
168 < * </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 176 | 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 212 | Line 213 | public class Phaser {
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) >>> 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 228 | Line 229 | public class Phaser {
229      }
230  
231      private static long stateFor(int phase, int parties, int unarrived) {
232 <        return ((((long)phase) << 32) | (((long)parties) << 16) |
233 <                (long)unarrived);
232 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
233 >                (long) unarrived);
234      }
235  
236      private static long trippedStateFor(int phase, int parties) {
237 <        long lp = (long)parties;
238 <        return (((long)phase) << 32) | (lp << 16) | lp;
237 >        long lp = (long) parties;
238 >        return (((long) phase) << 32) | (lp << 16) | lp;
239      }
240  
241      /**
242 <     * Returns message string for bad bounds exceptions
242 >     * Returns message string for bad bounds exceptions.
243       */
244      private static String badBounds(int parties, int unarrived) {
245          return ("Attempt to set " + unarrived +
# Line 251 | 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 267 | 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 275 | 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 302 | Line 303 | public class Phaser {
303      }
304  
305      /**
306 <     * Creates a new Phaser without any initially registered parties,
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.
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 341 | 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 366 | 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 376 | 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 414 | 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
418 <     * 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;
# Line 437 | 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 460 | Line 465 | public class Phaser {
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
470 <     * 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 498 | 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;
# Line 517 | Line 522 | public class Phaser {
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 549 | Line 562 | public class Phaser {
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)
# Line 571 | Line 589 | public class Phaser {
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 620 | 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 627 | Line 657 | public class Phaser {
657      }
658  
659      /**
630     * Returns {@code true} if the current phase number equals the given phase.
631     * @param phase the phase
632     * @return {@code true} if the current phase number equals the given phase
633     */
634    public final boolean hasPhase(int phase) {
635        return phaseOf(getReconciledState()) == phase;
636    }
637
638    /**
660       * Returns the number of parties registered at this barrier.
661 +     *
662       * @return the number of parties
663       */
664      public int getRegisteredParties() {
# Line 646 | 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 655 | 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 662 | 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 672 | 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 +     *
701       * @return the root ancestor of this phaser
702       */
703      public Phaser getRoot() {
# Line 680 | Line 706 | public class Phaser {
706  
707      /**
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() {
# Line 690 | 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
709 <     * transition if other parties successfully register while the
710 <     * invocation of this method is in progress, thus postponing the
711 <     * transition until those parties also arrive, re-triggering this
712 <     * 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 parties
# Line 803 | Line 826 | public class Phaser {
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 815 | Line 838 | public class Phaser {
838      }
839  
840      /**
841 <     * Tries to enqueue given node in the appropriate wait queue
841 >     * Tries to enqueue given node in the appropriate wait queue.
842 >     *
843       * @return true if successful
844       */
845      private boolean tryEnqueue(QNode node) {
# Line 825 | Line 849 | public class Phaser {
849  
850      /**
851       * Enqueues node and waits unless aborted or signalled.
852 +     *
853       * @return current phase
854       */
855      private int untimedWait(int phase) {
# Line 912 | Line 937 | public class Phaser {
937          return p;
938      }
939  
940 <    // Temporary Unsafe mechanics for preliminary release
916 <    private static Unsafe getUnsafe() throws Throwable {
917 <        try {
918 <            return Unsafe.getUnsafe();
919 <        } catch (SecurityException se) {
920 <            try {
921 <                return java.security.AccessController.doPrivileged
922 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
923 <                        public Unsafe run() throws Exception {
924 <                            return getUnsafePrivileged();
925 <                        }});
926 <            } catch (java.security.PrivilegedActionException e) {
927 <                throw e.getCause();
928 <            }
929 <        }
930 <    }
940 >    // Unsafe mechanics
941  
942 <    private static Unsafe getUnsafePrivileged()
943 <            throws NoSuchFieldException, IllegalAccessException {
944 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
935 <        f.setAccessible(true);
936 <        return (Unsafe) f.get(null);
937 <    }
942 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
943 >    private static final long stateOffset =
944 >        objectFieldOffset("state", Phaser.class);
945  
946 <    private static long fieldOffset(String fieldName)
947 <            throws NoSuchFieldException {
941 <        return _unsafe.objectFieldOffset
942 <            (Phaser.class.getDeclaredField(fieldName));
946 >    private final boolean casState(long cmp, long val) {
947 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
948      }
949  
950 <    static final Unsafe _unsafe;
946 <    static final long stateOffset;
947 <
948 <    static {
950 >    private static long objectFieldOffset(String field, Class<?> klazz) {
951          try {
952 <            _unsafe = getUnsafe();
953 <            stateOffset = fieldOffset("state");
954 <        } catch (Throwable e) {
955 <            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