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.10 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.36 by dl, Sun Aug 23 20:12:24 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}).
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:
34 > * <li> Each generation has an associated phase number. The phase
35 > * number starts at zero, amd advances when all parties arrive at the
36 > * barrier, wrapping around to zero after reaching {@code
37 > * Integer.MAX_VALUE}.
38 > *
39 > * <li> Like a {@code CyclicBarrier}, a phaser may be repeatedly
40 > * awaited.  Method {@link #arriveAndAwaitAdvance} has effect
41 > * analogous to {@link java.util.concurrent.CyclicBarrier#await
42 > * CyclicBarrier.await}.  However, phasers separate two aspects of
43 > * coordination, which may also be invoked independently:
44   *
45   * <ul>
46   *
47 < *   <li> Arriving at a barrier. Methods {@code arrive} and
48 < *       {@code arriveAndDeregister} do not block, but return
49 < *       the phase value current upon entry to the method.
50 < *
51 < *   <li> Awaiting others. Method {@code awaitAdvance} requires an
52 < *       argument indicating the entry phase, and returns when the
53 < *       barrier advances to a new phase.
47 > *   <li> Arriving at a barrier. Methods {@link #arrive} and
48 > *       {@link #arriveAndDeregister} do not block, but return
49 > *       an associated <em>arrival phase number</em>;
50 > *       that is, the phase number of the barrier to which the
51 > *       arrival applied.
52 > *
53 > *   <li> Awaiting others. Method {@link #awaitAdvance} requires an
54 > *       argument indicating an arrival phase number, and returns
55 > *       when the barrier advances to a new phase.
56   * </ul>
57   *
52 *
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 > * <li>The current state of a phaser may be monitored.  At any given
94 > * moment there are {@link #getRegisteredParties}, where {@link
95 > * #getArrivedParties} have arrived at the current phase ({@link
96 > * #getPhase}). When the remaining {@link #getUnarrivedParties})
97 > * arrive, the phase advances. Method {@link #toString} returns
98 > * snapshots of these state queries in a form convenient for
99 > * informal monitoring.
100   *
101   * </ul>
102   *
103   * <p><b>Sample usages:</b>
104   *
105 < * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
106 < * a one-shot action serving a variable number of parties. The typical
107 < * idiom is for the method setting this up to first register, then
108 < * start the actions, then deregister, as in:
109 < *
110 < * <pre>
111 < *  void runTasks(List&lt;Runnable&gt; list) {
112 < *    final Phaser phaser = new Phaser(1); // "1" to register self
113 < *    for (Runnable r : list) {
114 < *      phaser.register();
115 < *      new Thread() {
116 < *        public void run() {
117 < *          phaser.arriveAndAwaitAdvance(); // await all creation
118 < *          r.run();
119 < *          phaser.arriveAndDeregister();   // signal completion
120 < *        }
121 < *      }.start();
105 > * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
106 > * to control a one-shot action serving a variable number of
107 > * parties. The typical idiom is for the method setting this up to
108 > * first register, then start the actions, then deregister, as in:
109 > *
110 > *  <pre> {@code
111 > * void runTasks(List<Runnable> tasks) {
112 > *   final Phaser phaser = new Phaser(1); // "1" to register self
113 > *   // create and start threads
114 > *   for (Runnable task : tasks) {
115 > *     phaser.register();
116 > *     new Thread() {
117 > *       public void run() {
118 > *         phaser.arriveAndAwaitAdvance(); // await all creation
119 > *         task.run();
120 > *       }
121 > *     }.start();
122   *   }
123   *
124 < *   doSomethingOnBehalfOfWorkers();
125 < *   phaser.arrive(); // allow threads to start
126 < *   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>
124 > *   // allow threads to start and deregister self
125 > *   phaser.arriveAndDeregister();
126 > * }}</pre>
127   *
128   * <p>One way to cause a set of threads to repeatedly perform actions
129   * for a given number of iterations is to override {@code onAdvance}:
130   *
131 < * <pre>
132 < *  void startTasks(List&lt;Runnable&gt; list, final int iterations) {
133 < *    final Phaser phaser = new Phaser() {
134 < *       public boolean onAdvance(int phase, int registeredParties) {
135 < *         return phase &gt;= iterations || registeredParties == 0;
131 > *  <pre> {@code
132 > * void startTasks(List<Runnable> tasks, final int iterations) {
133 > *   final Phaser phaser = new Phaser() {
134 > *     public boolean onAdvance(int phase, int registeredParties) {
135 > *       return phase >= iterations || registeredParties == 0;
136 > *     }
137 > *   };
138 > *   phaser.register();
139 > *   for (Runnable task : tasks) {
140 > *     phaser.register();
141 > *     new Thread() {
142 > *       public void run() {
143 > *         do {
144 > *           task.run();
145 > *           phaser.arriveAndAwaitAdvance();
146 > *         } while(!phaser.isTerminated();
147   *       }
148 < *    };
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();
148 > *     }.start();
149   *   }
150   *   phaser.arriveAndDeregister(); // deregister self, don't wait
151 < * }
143 < * </pre>
151 > * }}</pre>
152   *
153 < * <p> To create a set of tasks using a tree of Phasers,
153 > * <p>To create a set of tasks using a tree of phasers,
154   * you could use code of the following form, assuming a
155 < * Task class with a constructor accepting a Phaser that
155 > * Task class with a constructor accepting a phaser that
156   * it registers for upon construction:
157 < * <pre>
158 < *  void build(Task[] actions, int lo, int hi, Phaser b) {
159 < *    int step = (hi - lo) / TASKS_PER_PHASER;
160 < *    if (step &gt; 1) {
161 < *       int i = lo;
162 < *       while (i &lt; hi) {
163 < *         int r = Math.min(i + step, hi);
164 < *         build(actions, i, r, new Phaser(b));
165 < *         i = r;
166 < *       }
167 < *    }
168 < *    else {
169 < *      for (int i = lo; i &lt; hi; ++i)
170 < *        actions[i] = new Task(b);
171 < *        // assumes new Task(b) performs b.register()
172 < *    }
173 < *  }
174 < *  // .. initially called, for n tasks via
167 < *  build(new Task[n], 0, n, new Phaser());
168 < * </pre>
157 > *  <pre> {@code
158 > * void build(Task[] actions, int lo, int hi, Phaser b) {
159 > *   int step = (hi - lo) / TASKS_PER_PHASER;
160 > *   if (step > 1) {
161 > *     int i = lo;
162 > *     while (i < hi) {
163 > *       int r = Math.min(i + step, hi);
164 > *       build(actions, i, r, new Phaser(b));
165 > *       i = r;
166 > *     }
167 > *   } else {
168 > *     for (int i = lo; i < hi; ++i)
169 > *       actions[i] = new Task(b);
170 > *       // assumes new Task(b) performs b.register()
171 > *   }
172 > * }
173 > * // .. initially called, for n tasks via
174 > * build(new Task[n], 0, n, new Phaser());}</pre>
175   *
176   * The best value of {@code TASKS_PER_PHASER} depends mainly on
177   * expected barrier synchronization rates. A value as low as four may
# Line 176 | Line 182 | import java.lang.reflect.*;
182   *
183   * <p><b>Implementation notes</b>: This implementation restricts the
184   * maximum number of parties to 65535. Attempts to register additional
185 < * parties result in IllegalStateExceptions. However, you can and
185 > * parties result in {@code IllegalStateException}. However, you can and
186   * should create tiered phasers to accommodate arbitrarily large sets
187   * of participants.
188 + *
189 + * @since 1.7
190 + * @author Doug Lea
191   */
192   public class Phaser {
193      /*
# Line 212 | Line 221 | public class Phaser {
221      private static final int phaseMask  = 0x7fffffff;
222  
223      private static int unarrivedOf(long s) {
224 <        return (int)(s & ushortMask);
224 >        return (int) (s & ushortMask);
225      }
226  
227      private static int partiesOf(long s) {
228 <        return ((int)s) >>> 16;
228 >        return ((int) s) >>> 16;
229      }
230  
231      private static int phaseOf(long s) {
232 <        return (int)(s >>> 32);
232 >        return (int) (s >>> 32);
233      }
234  
235      private static int arrivedOf(long s) {
# Line 228 | Line 237 | public class Phaser {
237      }
238  
239      private static long stateFor(int phase, int parties, int unarrived) {
240 <        return ((((long)phase) << 32) | (((long)parties) << 16) |
241 <                (long)unarrived);
240 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
241 >                (long) unarrived);
242      }
243  
244      private static long trippedStateFor(int phase, int parties) {
245 <        long lp = (long)parties;
246 <        return (((long)phase) << 32) | (lp << 16) | lp;
245 >        long lp = (long) parties;
246 >        return (((long) phase) << 32) | (lp << 16) | lp;
247      }
248  
249      /**
250 <     * Returns message string for bad bounds exceptions
250 >     * Returns message string for bad bounds exceptions.
251       */
252      private static String badBounds(int parties, int unarrived) {
253          return ("Attempt to set " + unarrived +
# Line 251 | Line 260 | public class Phaser {
260      private final Phaser parent;
261  
262      /**
263 <     * The root of Phaser tree. Equals this if not in a tree.  Used to
263 >     * The root of phaser tree. Equals this if not in a tree.  Used to
264       * support faster state push-down.
265       */
266      private final Phaser root;
# Line 267 | Line 276 | public class Phaser {
276      private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
277  
278      private AtomicReference<QNode> queueFor(int phase) {
279 <        return (phase & 1) == 0? evenQ : oddQ;
279 >        return ((phase & 1) == 0) ? evenQ : oddQ;
280      }
281  
282      /**
# Line 275 | Line 284 | public class Phaser {
284       * root if necessary.
285       */
286      private long getReconciledState() {
287 <        return parent == null? state : reconcileState();
287 >        return (parent == null) ? state : reconcileState();
288      }
289  
290      /**
# Line 302 | Line 311 | public class Phaser {
311      }
312  
313      /**
314 <     * Creates a new Phaser without any initially registered parties,
314 >     * Creates a new phaser without any initially registered parties,
315       * initial phase number 0, and no parent. Any thread using this
316 <     * Phaser will need to first register for it.
316 >     * phaser will need to first register for it.
317       */
318      public Phaser() {
319          this(null);
320      }
321  
322      /**
323 <     * Creates a new Phaser with the given numbers of registered
323 >     * Creates a new phaser with the given numbers of registered
324       * unarrived parties, initial phase number 0, and no parent.
325 <     * @param parties the number of parties required to trip barrier.
325 >     *
326 >     * @param parties the number of parties required to trip barrier
327       * @throws IllegalArgumentException if parties less than zero
328 <     * or greater than the maximum number of parties supported.
328 >     * or greater than the maximum number of parties supported
329       */
330      public Phaser(int parties) {
331          this(null, parties);
332      }
333  
334      /**
335 <     * Creates a new Phaser with the given parent, without any
335 >     * Creates a new phaser with the given parent, without any
336       * initially registered parties. If parent is non-null this phaser
337       * is registered with the parent and its initial phase number is
338       * the same as that of parent phaser.
339 <     * @param parent the parent phaser.
339 >     *
340 >     * @param parent the parent phaser
341       */
342      public Phaser(Phaser parent) {
343          int phase = 0;
# Line 341 | Line 352 | public class Phaser {
352      }
353  
354      /**
355 <     * Creates a new Phaser with the given parent and numbers of
356 <     * registered unarrived parties. If parent is non-null this phaser
355 >     * Creates a new phaser with the given parent and numbers of
356 >     * registered unarrived parties. If parent is non-null, this phaser
357       * is registered with the parent and its initial phase number is
358       * the same as that of parent phaser.
359 <     * @param parent the parent phaser.
360 <     * @param parties the number of parties required to trip barrier.
359 >     *
360 >     * @param parent the parent phaser
361 >     * @param parties the number of parties required to trip barrier
362       * @throws IllegalArgumentException if parties less than zero
363 <     * or greater than the maximum number of parties supported.
363 >     * or greater than the maximum number of parties supported
364       */
365      public Phaser(Phaser parent, int parties) {
366          if (parties < 0 || parties > ushortMask)
# Line 366 | Line 378 | public class Phaser {
378  
379      /**
380       * Adds a new unarrived party to this phaser.
381 <     * @return the current barrier phase number upon registration
381 >     *
382 >     * @return the arrival phase number to which this registration applied
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 register() {
387          return doRegister(1);
# Line 376 | Line 389 | public class Phaser {
389  
390      /**
391       * Adds the given number of new unarrived parties to this phaser.
392 <     * @param parties the number of parties required to trip barrier.
393 <     * @return the current barrier phase number upon registration
392 >     *
393 >     * @param parties the number of parties required to trip barrier
394 >     * @return the arrival phase number to which this registration applied
395       * @throws IllegalStateException if attempting to register more
396 <     * than the maximum supported number of parties.
396 >     * than the maximum supported number of parties
397       */
398      public int bulkRegister(int parties) {
399          if (parties < 0)
# Line 399 | Line 413 | public class Phaser {
413              phase = phaseOf(s);
414              int unarrived = unarrivedOf(s) + registrations;
415              int parties = partiesOf(s) + registrations;
416 <            if (phase < 0)
416 >            if (phase < 0)
417                  break;
418              if (parties > ushortMask || unarrived > ushortMask)
419                  throw new IllegalStateException(badBounds(parties, unarrived));
# Line 414 | Line 428 | public class Phaser {
428       * Arrives at the barrier, but does not wait for others.  (You can
429       * in turn wait for others via {@link #awaitAdvance}).
430       *
431 <     * @return the barrier phase number upon entry to this method, or a
418 <     * negative value if terminated;
431 >     * @return the arrival phase number, or a negative value if terminated
432       * @throws IllegalStateException if not terminated and the number
433 <     * of unarrived parties would become negative.
433 >     * of unarrived parties would become negative
434       */
435      public int arrive() {
436          int phase;
# Line 437 | Line 450 | public class Phaser {
450                  if (par == null) {      // directly trip
451                      if (casState
452                          (s,
453 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
453 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
454                                           ((phase + 1) & phaseMask), parties))) {
455                          releaseWaiters(phase);
456                          break;
# Line 460 | Line 473 | public class Phaser {
473      }
474  
475      /**
476 <     * Arrives at the barrier, and deregisters from it, without
477 <     * waiting for others. Deregistration reduces number of parties
476 >     * Arrives at the barrier and deregisters from it without waiting
477 >     * for others. Deregistration reduces the number of parties
478       * required to trip the barrier in future phases.  If this phaser
479       * has a parent, and deregistration causes this phaser to have
480 <     * zero parties, this phaser is also deregistered from its parent.
480 >     * zero parties, this phaser also arrives at and is deregistered
481 >     * from its parent.
482       *
483 <     * @return the current barrier phase number upon entry to
470 <     * this method, or a negative value if terminated;
483 >     * @return the arrival phase number, or a negative value if terminated
484       * @throws IllegalStateException if not terminated and the number
485 <     * of registered or unarrived parties would become negative.
485 >     * of registered or unarrived parties would become negative
486       */
487      public int arriveAndDeregister() {
488          // similar code to arrive, but too different to merge
# Line 498 | Line 511 | public class Phaser {
511                  if (unarrived == 0) {
512                      if (casState
513                          (s,
514 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
514 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
515                                           ((phase + 1) & phaseMask), parties))) {
516                          releaseWaiters(phase);
517                          break;
# Line 517 | Line 530 | public class Phaser {
530  
531      /**
532       * Arrives at the barrier and awaits others. Equivalent in effect
533 <     * to {@code awaitAdvance(arrive())}.  If you instead need to
534 <     * await with interruption of timeout, and/or deregister upon
535 <     * arrival, you can arrange them using analogous constructions.
536 <     * @return the phase on entry to this method
533 >     * to {@code awaitAdvance(arrive())}.  If you need to await with
534 >     * interruption or timeout, you can arrange this with an analogous
535 >     * construction using one of the other forms of the awaitAdvance
536 >     * method.  If instead you need to deregister upon arrival use
537 >     * {@code arriveAndDeregister}.
538 >     *
539 >     * @return the arrival phase number, or a negative number if terminated
540       * @throws IllegalStateException if not terminated and the number
541 <     * of unarrived parties would become negative.
541 >     * of unarrived parties would become negative
542       */
543      public int arriveAndAwaitAdvance() {
544          return awaitAdvance(arrive());
545      }
546  
547      /**
548 <     * Awaits the phase of the barrier to advance from the given
549 <     * value, or returns immediately if argument is negative or this
550 <     * barrier is terminated.
551 <     * @param phase the phase on entry to this method
552 <     * @return the phase on exit from this method
548 >     * Awaits the phase of the barrier to advance from the given phase
549 >     * value, returning immediately if the current phase of the
550 >     * barrier is not equal to the given phase value or this barrier
551 >     * is terminated.
552 >     *
553 >     * @param phase an arrival phase number, or negative value if
554 >     * terminated; this argument is normally the value returned by a
555 >     * previous call to {@code arrive} or its variants
556 >     * @return the next arrival phase number, or a negative value
557 >     * if terminated or argument is negative
558       */
559      public int awaitAdvance(int phase) {
560          if (phase < 0)
# Line 549 | Line 570 | public class Phaser {
570      }
571  
572      /**
573 <     * Awaits the phase of the barrier to advance from the given
574 <     * value, or returns immediately if argument is negative or this
575 <     * barrier is terminated, or throws InterruptedException if
576 <     * interrupted while waiting.
577 <     * @param phase the phase on entry to this method
578 <     * @return the phase on exit from this method
573 >     * Awaits the phase of the barrier to advance from the given phase
574 >     * value, throwing {@code InterruptedException} if interrupted while
575 >     * waiting, or returning immediately if the current phase of the
576 >     * barrier is not equal to the given phase value or this barrier
577 >     * is terminated.
578 >     *
579 >     * @param phase an arrival phase number, or negative value if
580 >     * terminated; this argument is normally the value returned by a
581 >     * previous call to {@code arrive} or its variants
582 >     * @return the next arrival phase number, or a negative value
583 >     * if terminated or argument is negative
584       * @throws InterruptedException if thread interrupted while waiting
585       */
586 <    public int awaitAdvanceInterruptibly(int phase)
586 >    public int awaitAdvanceInterruptibly(int phase)
587          throws InterruptedException {
588          if (phase < 0)
589              return phase;
# Line 571 | Line 597 | public class Phaser {
597      }
598  
599      /**
600 <     * Awaits the phase of the barrier to advance from the given value
601 <     * or the given timeout elapses, or returns immediately if
602 <     * argument is negative or this barrier is terminated.
603 <     * @param phase the phase on entry to this method
604 <     * @return the phase on exit from this method
600 >     * Awaits the phase of the barrier to advance from the given phase
601 >     * value or the given timeout to elapse, throwing
602 >     * {@code InterruptedException} if interrupted while waiting, or
603 >     * returning immediately if the current phase of the barrier is not
604 >     * equal to the given phase value or this barrier is terminated.
605 >     *
606 >     * @param phase an arrival phase number, or negative value if
607 >     * terminated; this argument is normally the value returned by a
608 >     * previous call to {@code arrive} or its variants
609 >     * @param timeout how long to wait before giving up, in units of
610 >     *        {@code unit}
611 >     * @param unit a {@code TimeUnit} determining how to interpret the
612 >     *        {@code timeout} parameter
613 >     * @return the next arrival phase number, or a negative value
614 >     * if terminated or argument is negative
615       * @throws InterruptedException if thread interrupted while waiting
616       * @throws TimeoutException if timed out while waiting
617       */
618 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
618 >    public int awaitAdvanceInterruptibly(int phase,
619 >                                         long timeout, TimeUnit unit)
620          throws InterruptedException, TimeoutException {
621          if (phase < 0)
622              return phase;
# Line 620 | Line 657 | public class Phaser {
657       * Returns the current phase number. The maximum phase number is
658       * {@code Integer.MAX_VALUE}, after which it restarts at
659       * zero. Upon termination, the phase number is negative.
660 +     *
661       * @return the phase number, or a negative value if terminated
662       */
663      public final int getPhase() {
# Line 627 | Line 665 | public class Phaser {
665      }
666  
667      /**
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    /**
668       * Returns the number of parties registered at this barrier.
669 +     *
670       * @return the number of parties
671       */
672      public int getRegisteredParties() {
# Line 644 | Line 674 | public class Phaser {
674      }
675  
676      /**
677 <     * Returns the number of parties that have arrived at the current
678 <     * phase of this barrier.
677 >     * Returns the number of registered parties that have arrived at
678 >     * the current phase of this barrier.
679 >     *
680       * @return the number of arrived parties
681       */
682      public int getArrivedParties() {
# Line 655 | Line 686 | public class Phaser {
686      /**
687       * Returns the number of registered parties that have not yet
688       * arrived at the current phase of this barrier.
689 +     *
690       * @return the number of unarrived parties
691       */
692      public int getUnarrivedParties() {
# Line 662 | Line 694 | public class Phaser {
694      }
695  
696      /**
697 <     * Returns the parent of this phaser, or null if none.
698 <     * @return the parent of this phaser, or null if none
697 >     * Returns the parent of this phaser, or {@code null} if none.
698 >     *
699 >     * @return the parent of this phaser, or {@code null} if none
700       */
701      public Phaser getParent() {
702          return parent;
# Line 672 | Line 705 | public class Phaser {
705      /**
706       * Returns the root ancestor of this phaser, which is the same as
707       * this phaser if it has no parent.
708 +     *
709       * @return the root ancestor of this phaser
710       */
711      public Phaser getRoot() {
# Line 680 | Line 714 | public class Phaser {
714  
715      /**
716       * Returns {@code true} if this barrier has been terminated.
717 +     *
718       * @return {@code true} if this barrier has been terminated
719       */
720      public boolean isTerminated() {
# Line 690 | Line 725 | public class Phaser {
725       * Overridable method to perform an action upon phase advance, and
726       * to control termination. This method is invoked whenever the
727       * barrier is tripped (and thus all other waiting parties are
728 <     * dormant). If it returns true, then, rather than advance the
729 <     * phase number, this barrier will be set to a final termination
730 <     * state, and subsequent calls to {@code isTerminated} will
731 <     * return true.
728 >     * dormant). If it returns {@code true}, then, rather than advance
729 >     * the phase number, this barrier will be set to a final
730 >     * termination state, and subsequent calls to {@link #isTerminated}
731 >     * will return true.
732       *
733 <     * <p> The default version returns true when the number of
733 >     * <p>The default version returns {@code true} when the number of
734       * registered parties is zero. Normally, overrides that arrange
735       * termination for other reasons should also preserve this
736       * property.
737       *
738 <     * <p> You may override this method to perform an action with side
738 >     * <p>You may override this method to perform an action with side
739       * effects visible to participating tasks, but it is in general
740       * only sensible to do so in designs where all parties register
741 <     * before any arrive, and all {@code awaitAdvance} at each phase.
742 <     * Otherwise, you cannot ensure lack of interference. In
743 <     * 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.
741 >     * before any arrive, and all {@link #awaitAdvance} at each phase.
742 >     * Otherwise, you cannot ensure lack of interference from other
743 >     * parties during the invocation of this method.
744       *
745       * @param phase the phase number on entering the barrier
746       * @param registeredParties the current number of registered parties
# Line 795 | Line 826 | public class Phaser {
826                  try {
827                      ForkJoinPool.managedBlock(this, false);
828                  } catch (InterruptedException ie) {
829 <                }
829 >                }
830              }
831              return wasInterrupted;
832          }
# Line 803 | Line 834 | public class Phaser {
834      }
835  
836      /**
837 <     * Removes and signals waiting threads from wait queue
837 >     * Removes and signals waiting threads from wait queue.
838       */
839      private void releaseWaiters(int phase) {
840          AtomicReference<QNode> head = queueFor(phase);
# Line 815 | Line 846 | public class Phaser {
846      }
847  
848      /**
849 <     * Tries to enqueue given node in the appropriate wait queue
849 >     * Tries to enqueue given node in the appropriate wait queue.
850 >     *
851       * @return true if successful
852       */
853      private boolean tryEnqueue(QNode node) {
# Line 825 | Line 857 | public class Phaser {
857  
858      /**
859       * Enqueues node and waits unless aborted or signalled.
860 +     *
861       * @return current phase
862       */
863      private int untimedWait(int phase) {
# Line 912 | Line 945 | public class Phaser {
945          return p;
946      }
947  
948 <    // Temporary Unsafe mechanics for preliminary release
948 >    // Unsafe mechanics
949 >
950 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
951 >    private static final long stateOffset =
952 >        objectFieldOffset("state", Phaser.class);
953  
954 <    static final Unsafe _unsafe;
955 <    static final long stateOffset;
954 >    private final boolean casState(long cmp, long val) {
955 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
956 >    }
957  
958 <    static {
958 >    private static long objectFieldOffset(String field, 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
928 <                _unsafe = Unsafe.getUnsafe();
929 <            stateOffset = _unsafe.objectFieldOffset
930 <                (Phaser.class.getDeclaredField("state"));
931 <        } catch (Exception e) {
932 <            throw new RuntimeException("Could not initialize intrinsics", e);
960 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
961 >        } catch (NoSuchFieldException e) {
962 >            // Convert Exception to corresponding Error
963 >            NoSuchFieldError error = new NoSuchFieldError(field);
964 >            error.initCause(e);
965 >            throw error;
966          }
967      }
968  
969 <    final boolean casState(long cmp, long val) {
970 <        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
969 >    /**
970 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
971 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
972 >     * into a jdk.
973 >     *
974 >     * @return a sun.misc.Unsafe
975 >     */
976 >    private static sun.misc.Unsafe getUnsafe() {
977 >        try {
978 >            return sun.misc.Unsafe.getUnsafe();
979 >        } catch (SecurityException se) {
980 >            try {
981 >                return java.security.AccessController.doPrivileged
982 >                    (new java.security
983 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
984 >                        public sun.misc.Unsafe run() throws Exception {
985 >                            java.lang.reflect.Field f = sun.misc
986 >                                .Unsafe.class.getDeclaredField("theUnsafe");
987 >                            f.setAccessible(true);
988 >                            return (sun.misc.Unsafe) f.get(null);
989 >                        }});
990 >            } catch (java.security.PrivilegedActionException e) {
991 >                throw new RuntimeException("Could not initialize intrinsics",
992 >                                           e.getCause());
993 >            }
994 >        }
995      }
996   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines