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.32 by jsr166, Wed Aug 19 17:44:45 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 33 | Line 32 | import java.lang.reflect.*;
32   * zero, and advancing when all parties reach the barrier (wrapping
33   * around to zero after reaching {@code Integer.MAX_VALUE}).
34   *
35 < * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
36 < * Method {@code arriveAndAwaitAdvance} has effect analogous to
37 < * {@code CyclicBarrier.await}.  However, Phasers separate two
38 < * aspects of coordination, that may also be invoked independently:
35 > * <li> Like a {@code CyclicBarrier}, a phaser may be repeatedly
36 > * awaited.  Method {@link #arriveAndAwaitAdvance} has effect
37 > * analogous to {@link java.util.concurrent.CyclicBarrier#await
38 > * CyclicBarrier.await}.  However, phasers separate two aspects of
39 > * coordination, which may also be invoked independently:
40   *
41   * <ul>
42   *
43 < *   <li> Arriving at a barrier. Methods {@code arrive} and
44 < *       {@code arriveAndDeregister} do not block, but return
43 > *   <li> Arriving at a barrier. Methods {@link #arrive} and
44 > *       {@link #arriveAndDeregister} do not block, but return
45   *       the phase value current upon entry to the method.
46   *
47 < *   <li> Awaiting others. Method {@code awaitAdvance} requires an
47 > *   <li> Awaiting others. Method {@link #awaitAdvance} requires an
48   *       argument indicating the entry phase, and returns when the
49   *       barrier advances to a new phase.
50   * </ul>
51   *
52   *
53   * <li> Barrier actions, performed by the task triggering a phase
54 < * advance while others may be waiting, are arranged by overriding
55 < * method {@code onAdvance}, that also controls termination.
56 < * Overriding this method may be used to similar but more flexible
57 < * effect as providing a barrier action to a CyclicBarrier.
54 > * advance, are arranged by overriding method {@link #onAdvance(int,
55 > * int)}, which also controls termination. Overriding this method is
56 > * similar to, but more flexible than, providing a barrier action to a
57 > * {@code CyclicBarrier}.
58   *
59   * <li> Phasers may enter a <em>termination</em> state in which all
60   * actions immediately return without updating phaser state or waiting
61   * for advance, and indicating (via a negative phase value) that
62 < * execution is complete.  Termination is triggered by executing the
63 < * overridable {@code onAdvance} method that is invoked each time the
64 < * barrier is about to be tripped. When a Phaser is controlling an
65 < * action with a fixed number of iterations, it is often convenient to
66 < * override this method to cause termination when the current phase
67 < * number reaches a threshold. Method {@code forceTermination} is also
68 < * available to abruptly release waiting threads and allow them to
69 < * terminate.
62 > * execution is complete.  Termination is triggered when an invocation
63 > * of {@code onAdvance} returns {@code true}.  When a phaser is
64 > * controlling an action with a fixed number of iterations, it is
65 > * often convenient to override this method to cause termination when
66 > * the current phase number reaches a threshold. Method {@link
67 > * #forceTermination} is also available to abruptly release waiting
68 > * threads and allow them to terminate.
69   *
70   * <li> Phasers may be tiered to reduce contention. Phasers with large
71   * numbers of parties that would otherwise experience heavy
# Line 76 | Line 75 | import java.lang.reflect.*;
75   *
76   * <li> By default, {@code awaitAdvance} continues to wait even if
77   * the waiting thread is interrupted. And unlike the case in
78 < * CyclicBarriers, exceptions encountered while tasks wait
78 > * {@code CyclicBarrier}, exceptions encountered while tasks wait
79   * interruptibly or with timeout do not change the state of the
80   * barrier. If necessary, you can perform any associated recovery
81   * within handlers of those exceptions, often after invoking
82   * {@code forceTermination}.
83   *
84 < * <li>Phasers ensure lack of starvation when used by ForkJoinTasks.
84 > * <li>Phasers may be used to coordinate tasks executing in a {@link
85 > * ForkJoinPool}, which will ensure sufficient parallelism to execute
86 > * tasks when others are blocked waiting for a phase to advance.
87   *
88   * </ul>
89   *
90   * <p><b>Sample usages:</b>
91   *
92 < * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
93 < * a one-shot action serving a variable number of parties. The typical
94 < * idiom is for the method setting this up to first register, then
95 < * start the actions, then deregister, as in:
96 < *
97 < * <pre>
98 < *  void runTasks(List&lt;Runnable&gt; list) {
99 < *    final Phaser phaser = new Phaser(1); // "1" to register self
100 < *    for (Runnable r : list) {
101 < *      phaser.register();
102 < *      new Thread() {
103 < *        public void run() {
104 < *          phaser.arriveAndAwaitAdvance(); // await all creation
105 < *          r.run();
106 < *          phaser.arriveAndDeregister();   // signal completion
107 < *        }
108 < *      }.start();
92 > * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
93 > * to control a one-shot action serving a variable number of
94 > * parties. The typical idiom is for the method setting this up to
95 > * first register, then start the actions, then deregister, as in:
96 > *
97 > *  <pre> {@code
98 > * void runTasks(List<Runnable> list) {
99 > *   final Phaser phaser = new Phaser(1); // "1" to register self
100 > *   // create and start threads
101 > *   for (Runnable r : list) {
102 > *     phaser.register();
103 > *     new Thread() {
104 > *       public void run() {
105 > *         phaser.arriveAndAwaitAdvance(); // await all creation
106 > *         r.run();
107 > *       }
108 > *     }.start();
109   *   }
110   *
111 < *   doSomethingOnBehalfOfWorkers();
112 < *   phaser.arrive(); // allow threads to start
113 < *   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>
111 > *   // allow threads to start and deregister self
112 > *   phaser.arriveAndDeregister();
113 > * }}</pre>
114   *
115   * <p>One way to cause a set of threads to repeatedly perform actions
116   * for a given number of iterations is to override {@code onAdvance}:
117   *
118 < * <pre>
119 < *  void startTasks(List&lt;Runnable&gt; list, final int iterations) {
120 < *    final Phaser phaser = new Phaser() {
121 < *       public boolean onAdvance(int phase, int registeredParties) {
122 < *         return phase &gt;= iterations || registeredParties == 0;
118 > *  <pre> {@code
119 > * void startTasks(List<Runnable> list, final int iterations) {
120 > *   final Phaser phaser = new Phaser() {
121 > *     public boolean onAdvance(int phase, int registeredParties) {
122 > *       return phase >= iterations || registeredParties == 0;
123 > *     }
124 > *   };
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 < *    };
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();
135 > *     }.start();
136   *   }
137   *   phaser.arriveAndDeregister(); // deregister self, don't wait
138 < * }
143 < * </pre>
138 > * }}</pre>
139   *
140 < * <p> To create a set of tasks using a tree of Phasers,
140 > * <p>To create a set of tasks using a tree of phasers,
141   * you could use code of the following form, assuming a
142 < * Task class with a constructor accepting a Phaser that
142 > * Task class with a constructor accepting a phaser that
143   * it registers for upon construction:
144 < * <pre>
145 < *  void build(Task[] actions, int lo, int hi, Phaser b) {
146 < *    int step = (hi - lo) / TASKS_PER_PHASER;
147 < *    if (step &gt; 1) {
148 < *       int i = lo;
149 < *       while (i &lt; hi) {
150 < *         int r = Math.min(i + step, hi);
151 < *         build(actions, i, r, new Phaser(b));
152 < *         i = r;
153 < *       }
154 < *    }
155 < *    else {
156 < *      for (int i = lo; i &lt; hi; ++i)
157 < *        actions[i] = new Task(b);
158 < *        // assumes new Task(b) performs b.register()
159 < *    }
160 < *  }
161 < *  // .. initially called, for n tasks via
167 < *  build(new Task[n], 0, n, new Phaser());
168 < * </pre>
144 > *  <pre> {@code
145 > * void build(Task[] actions, int lo, int hi, Phaser b) {
146 > *   int step = (hi - lo) / TASKS_PER_PHASER;
147 > *   if (step > 1) {
148 > *     int i = lo;
149 > *     while (i < hi) {
150 > *       int r = Math.min(i + step, hi);
151 > *       build(actions, i, r, new Phaser(b));
152 > *       i = r;
153 > *     }
154 > *   } else {
155 > *     for (int i = lo; i < hi; ++i)
156 > *       actions[i] = new Task(b);
157 > *       // assumes new Task(b) performs b.register()
158 > *   }
159 > * }
160 > * // .. initially called, for n tasks via
161 > * build(new Task[n], 0, n, new Phaser());}</pre>
162   *
163   * The best value of {@code TASKS_PER_PHASER} depends mainly on
164   * expected barrier synchronization rates. A value as low as four may
# Line 176 | Line 169 | import java.lang.reflect.*;
169   *
170   * <p><b>Implementation notes</b>: This implementation restricts the
171   * maximum number of parties to 65535. Attempts to register additional
172 < * parties result in IllegalStateExceptions. However, you can and
172 > * parties result in {@code IllegalStateException}. However, you can and
173   * should create tiered phasers to accommodate arbitrarily large sets
174   * of participants.
175 + *
176 + * @since 1.7
177 + * @author Doug Lea
178   */
179   public class Phaser {
180      /*
# Line 212 | Line 208 | public class Phaser {
208      private static final int phaseMask  = 0x7fffffff;
209  
210      private static int unarrivedOf(long s) {
211 <        return (int)(s & ushortMask);
211 >        return (int) (s & ushortMask);
212      }
213  
214      private static int partiesOf(long s) {
215 <        return ((int)s) >>> 16;
215 >        return ((int) s) >>> 16;
216      }
217  
218      private static int phaseOf(long s) {
219 <        return (int)(s >>> 32);
219 >        return (int) (s >>> 32);
220      }
221  
222      private static int arrivedOf(long s) {
# Line 228 | Line 224 | public class Phaser {
224      }
225  
226      private static long stateFor(int phase, int parties, int unarrived) {
227 <        return ((((long)phase) << 32) | (((long)parties) << 16) |
228 <                (long)unarrived);
227 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
228 >                (long) unarrived);
229      }
230  
231      private static long trippedStateFor(int phase, int parties) {
232 <        long lp = (long)parties;
233 <        return (((long)phase) << 32) | (lp << 16) | lp;
232 >        long lp = (long) parties;
233 >        return (((long) phase) << 32) | (lp << 16) | lp;
234      }
235  
236      /**
237 <     * Returns message string for bad bounds exceptions
237 >     * Returns message string for bad bounds exceptions.
238       */
239      private static String badBounds(int parties, int unarrived) {
240          return ("Attempt to set " + unarrived +
# Line 251 | Line 247 | public class Phaser {
247      private final Phaser parent;
248  
249      /**
250 <     * The root of Phaser tree. Equals this if not in a tree.  Used to
250 >     * The root of phaser tree. Equals this if not in a tree.  Used to
251       * support faster state push-down.
252       */
253      private final Phaser root;
# Line 267 | Line 263 | public class Phaser {
263      private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
264  
265      private AtomicReference<QNode> queueFor(int phase) {
266 <        return (phase & 1) == 0? evenQ : oddQ;
266 >        return ((phase & 1) == 0) ? evenQ : oddQ;
267      }
268  
269      /**
# Line 275 | Line 271 | public class Phaser {
271       * root if necessary.
272       */
273      private long getReconciledState() {
274 <        return parent == null? state : reconcileState();
274 >        return (parent == null) ? state : reconcileState();
275      }
276  
277      /**
# Line 302 | Line 298 | public class Phaser {
298      }
299  
300      /**
301 <     * Creates a new Phaser without any initially registered parties,
301 >     * Creates a new phaser without any initially registered parties,
302       * initial phase number 0, and no parent. Any thread using this
303 <     * Phaser will need to first register for it.
303 >     * phaser will need to first register for it.
304       */
305      public Phaser() {
306          this(null);
307      }
308  
309      /**
310 <     * Creates a new Phaser with the given numbers of registered
310 >     * Creates a new phaser with the given numbers of registered
311       * unarrived parties, initial phase number 0, and no parent.
312 <     * @param parties the number of parties required to trip barrier.
312 >     *
313 >     * @param parties the number of parties required to trip barrier
314       * @throws IllegalArgumentException if parties less than zero
315 <     * or greater than the maximum number of parties supported.
315 >     * or greater than the maximum number of parties supported
316       */
317      public Phaser(int parties) {
318          this(null, parties);
319      }
320  
321      /**
322 <     * Creates a new Phaser with the given parent, without any
322 >     * Creates a new phaser with the given parent, without any
323       * initially registered parties. If parent is non-null this phaser
324       * is registered with the parent and its initial phase number is
325       * the same as that of parent phaser.
326 <     * @param parent the parent phaser.
326 >     *
327 >     * @param parent the parent phaser
328       */
329      public Phaser(Phaser parent) {
330          int phase = 0;
# Line 341 | Line 339 | public class Phaser {
339      }
340  
341      /**
342 <     * Creates a new Phaser with the given parent and numbers of
343 <     * registered unarrived parties. If parent is non-null this phaser
342 >     * Creates a new phaser with the given parent and numbers of
343 >     * registered unarrived parties. If parent is non-null, this phaser
344       * is registered with the parent and its initial phase number is
345       * the same as that of parent phaser.
346 <     * @param parent the parent phaser.
347 <     * @param parties the number of parties required to trip barrier.
346 >     *
347 >     * @param parent the parent phaser
348 >     * @param parties the number of parties required to trip barrier
349       * @throws IllegalArgumentException if parties less than zero
350 <     * or greater than the maximum number of parties supported.
350 >     * or greater than the maximum number of parties supported
351       */
352      public Phaser(Phaser parent, int parties) {
353          if (parties < 0 || parties > ushortMask)
# Line 366 | Line 365 | public class Phaser {
365  
366      /**
367       * Adds a new unarrived party to this phaser.
368 +     *
369       * @return the current barrier phase number upon registration
370       * @throws IllegalStateException if attempting to register more
371 <     * than the maximum supported number of parties.
371 >     * than the maximum supported number of parties
372       */
373      public int register() {
374          return doRegister(1);
# Line 376 | Line 376 | public class Phaser {
376  
377      /**
378       * Adds the given number of new unarrived parties to this phaser.
379 <     * @param parties the number of parties required to trip barrier.
379 >     *
380 >     * @param parties the number of parties required to trip barrier
381       * @return the current barrier phase number upon registration
382       * @throws IllegalStateException if attempting to register more
383 <     * than the maximum supported number of parties.
383 >     * than the maximum supported number of parties
384       */
385      public int bulkRegister(int parties) {
386          if (parties < 0)
# Line 399 | Line 400 | public class Phaser {
400              phase = phaseOf(s);
401              int unarrived = unarrivedOf(s) + registrations;
402              int parties = partiesOf(s) + registrations;
403 <            if (phase < 0)
403 >            if (phase < 0)
404                  break;
405              if (parties > ushortMask || unarrived > ushortMask)
406                  throw new IllegalStateException(badBounds(parties, unarrived));
# Line 415 | Line 416 | public class Phaser {
416       * in turn wait for others via {@link #awaitAdvance}).
417       *
418       * @return the barrier phase number upon entry to this method, or a
419 <     * negative value if terminated;
419 >     * negative value if terminated
420       * @throws IllegalStateException if not terminated and the number
421 <     * of unarrived parties would become negative.
421 >     * of unarrived parties would become negative
422       */
423      public int arrive() {
424          int phase;
# Line 437 | Line 438 | public class Phaser {
438                  if (par == null) {      // directly trip
439                      if (casState
440                          (s,
441 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
441 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
442                                           ((phase + 1) & phaseMask), parties))) {
443                          releaseWaiters(phase);
444                          break;
# Line 460 | Line 461 | public class Phaser {
461      }
462  
463      /**
464 <     * Arrives at the barrier, and deregisters from it, without
465 <     * waiting for others. Deregistration reduces number of parties
464 >     * Arrives at the barrier and deregisters from it without waiting
465 >     * for others. Deregistration reduces the number of parties
466       * required to trip the barrier in future phases.  If this phaser
467       * has a parent, and deregistration causes this phaser to have
468 <     * zero parties, this phaser is also deregistered from its parent.
468 >     * zero parties, this phaser also arrives at and is deregistered
469 >     * from its parent.
470       *
471       * @return the current barrier phase number upon entry to
472 <     * this method, or a negative value if terminated;
472 >     * this method, or a negative value if terminated
473       * @throws IllegalStateException if not terminated and the number
474 <     * of registered or unarrived parties would become negative.
474 >     * of registered or unarrived parties would become negative
475       */
476      public int arriveAndDeregister() {
477          // similar code to arrive, but too different to merge
# Line 498 | Line 500 | public class Phaser {
500                  if (unarrived == 0) {
501                      if (casState
502                          (s,
503 <                         trippedStateFor(onAdvance(phase, parties)? -1 :
503 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
504                                           ((phase + 1) & phaseMask), parties))) {
505                          releaseWaiters(phase);
506                          break;
# Line 517 | Line 519 | public class Phaser {
519  
520      /**
521       * Arrives at the barrier and awaits others. Equivalent in effect
522 <     * to {@code awaitAdvance(arrive())}.  If you instead need to
523 <     * await with interruption of timeout, and/or deregister upon
524 <     * arrival, you can arrange them using analogous constructions.
522 >     * to {@code awaitAdvance(arrive())}.  If you need to await with
523 >     * interruption or timeout, you can arrange this with an analogous
524 >     * construction using one of the other forms of the awaitAdvance
525 >     * method.  If instead you need to deregister upon arrival use
526 >     * {@code arriveAndDeregister}.
527 >     *
528       * @return the phase on entry to this method
529       * @throws IllegalStateException if not terminated and the number
530 <     * of unarrived parties would become negative.
530 >     * of unarrived parties would become negative
531       */
532      public int arriveAndAwaitAdvance() {
533          return awaitAdvance(arrive());
534      }
535  
536      /**
537 <     * Awaits the phase of the barrier to advance from the given
538 <     * value, or returns immediately if argument is negative or this
539 <     * barrier is terminated.
537 >     * Awaits the phase of the barrier to advance from the given phase
538 >     * value, returning immediately if the current phase of the
539 >     * barrier is not equal to the given phase value or this barrier
540 >     * is terminated.
541 >     *
542       * @param phase the phase on entry to this method
543       * @return the phase on exit from this method
544       */
# Line 549 | Line 556 | public class Phaser {
556      }
557  
558      /**
559 <     * Awaits the phase of the barrier to advance from the given
560 <     * value, or returns immediately if argument is negative or this
561 <     * barrier is terminated, or throws InterruptedException if
562 <     * interrupted while waiting.
559 >     * Awaits the phase of the barrier to advance from the given phase
560 >     * value, throwing {@code InterruptedException} if interrupted while
561 >     * waiting, or returning immediately if the current phase of the
562 >     * barrier is not equal to the given phase value or this barrier
563 >     * is terminated.
564 >     *
565       * @param phase the phase on entry to this method
566       * @return the phase on exit from this method
567       * @throws InterruptedException if thread interrupted while waiting
568       */
569 <    public int awaitAdvanceInterruptibly(int phase)
569 >    public int awaitAdvanceInterruptibly(int phase)
570          throws InterruptedException {
571          if (phase < 0)
572              return phase;
# Line 571 | Line 580 | public class Phaser {
580      }
581  
582      /**
583 <     * Awaits the phase of the barrier to advance from the given value
584 <     * or the given timeout elapses, or returns immediately if
585 <     * argument is negative or this barrier is terminated.
583 >     * Awaits the phase of the barrier to advance from the given phase
584 >     * value or the given timeout to elapse, throwing
585 >     * {@code InterruptedException} if interrupted while waiting, or
586 >     * returning immediately if the current phase of the barrier is not
587 >     * equal to the given phase value or this barrier is terminated.
588 >     *
589       * @param phase the phase on entry to this method
590 +     * @param timeout how long to wait before giving up, in units of
591 +     *        {@code unit}
592 +     * @param unit a {@code TimeUnit} determining how to interpret the
593 +     *        {@code timeout} parameter
594       * @return the phase on exit from this method
595       * @throws InterruptedException if thread interrupted while waiting
596       * @throws TimeoutException if timed out while waiting
597       */
598 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
598 >    public int awaitAdvanceInterruptibly(int phase,
599 >                                         long timeout, TimeUnit unit)
600          throws InterruptedException, TimeoutException {
601          if (phase < 0)
602              return phase;
# Line 620 | Line 637 | public class Phaser {
637       * Returns the current phase number. The maximum phase number is
638       * {@code Integer.MAX_VALUE}, after which it restarts at
639       * zero. Upon termination, the phase number is negative.
640 +     *
641       * @return the phase number, or a negative value if terminated
642       */
643      public final int getPhase() {
# Line 627 | Line 645 | public class Phaser {
645      }
646  
647      /**
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    /**
648       * Returns the number of parties registered at this barrier.
649 +     *
650       * @return the number of parties
651       */
652      public int getRegisteredParties() {
# Line 646 | Line 656 | public class Phaser {
656      /**
657       * Returns the number of parties that have arrived at the current
658       * phase of this barrier.
659 +     *
660       * @return the number of arrived parties
661       */
662      public int getArrivedParties() {
# Line 655 | Line 666 | public class Phaser {
666      /**
667       * Returns the number of registered parties that have not yet
668       * arrived at the current phase of this barrier.
669 +     *
670       * @return the number of unarrived parties
671       */
672      public int getUnarrivedParties() {
# Line 662 | Line 674 | public class Phaser {
674      }
675  
676      /**
677 <     * Returns the parent of this phaser, or null if none.
678 <     * @return the parent of this phaser, or null if none
677 >     * Returns the parent of this phaser, or {@code null} if none.
678 >     *
679 >     * @return the parent of this phaser, or {@code null} if none
680       */
681      public Phaser getParent() {
682          return parent;
# Line 672 | Line 685 | public class Phaser {
685      /**
686       * Returns the root ancestor of this phaser, which is the same as
687       * this phaser if it has no parent.
688 +     *
689       * @return the root ancestor of this phaser
690       */
691      public Phaser getRoot() {
# Line 680 | Line 694 | public class Phaser {
694  
695      /**
696       * Returns {@code true} if this barrier has been terminated.
697 +     *
698       * @return {@code true} if this barrier has been terminated
699       */
700      public boolean isTerminated() {
# Line 690 | Line 705 | public class Phaser {
705       * Overridable method to perform an action upon phase advance, and
706       * to control termination. This method is invoked whenever the
707       * barrier is tripped (and thus all other waiting parties are
708 <     * dormant). If it returns true, then, rather than advance the
709 <     * phase number, this barrier will be set to a final termination
710 <     * state, and subsequent calls to {@code isTerminated} will
711 <     * return true.
708 >     * dormant). If it returns {@code true}, then, rather than advance
709 >     * the phase number, this barrier will be set to a final
710 >     * termination state, and subsequent calls to {@link #isTerminated}
711 >     * will return true.
712       *
713 <     * <p> The default version returns true when the number of
713 >     * <p>The default version returns {@code true} when the number of
714       * registered parties is zero. Normally, overrides that arrange
715       * termination for other reasons should also preserve this
716       * property.
717       *
718 <     * <p> You may override this method to perform an action with side
718 >     * <p>You may override this method to perform an action with side
719       * effects visible to participating tasks, but it is in general
720       * only sensible to do so in designs where all parties register
721 <     * before any arrive, and all {@code awaitAdvance} at each phase.
722 <     * Otherwise, you cannot ensure lack of interference. In
723 <     * particular, this method may be invoked more than once per
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.
721 >     * before any arrive, and all {@link #awaitAdvance} at each phase.
722 >     * Otherwise, you cannot ensure lack of interference from other
723 >     * parties during the invocation of this method.
724       *
725       * @param phase the phase number on entering the barrier
726       * @param registeredParties the current number of registered parties
# Line 795 | Line 806 | public class Phaser {
806                  try {
807                      ForkJoinPool.managedBlock(this, false);
808                  } catch (InterruptedException ie) {
809 <                }
809 >                }
810              }
811              return wasInterrupted;
812          }
# Line 803 | Line 814 | public class Phaser {
814      }
815  
816      /**
817 <     * Removes and signals waiting threads from wait queue
817 >     * Removes and signals waiting threads from wait queue.
818       */
819      private void releaseWaiters(int phase) {
820          AtomicReference<QNode> head = queueFor(phase);
# Line 815 | Line 826 | public class Phaser {
826      }
827  
828      /**
829 <     * Tries to enqueue given node in the appropriate wait queue
829 >     * Tries to enqueue given node in the appropriate wait queue.
830 >     *
831       * @return true if successful
832       */
833      private boolean tryEnqueue(QNode node) {
# Line 825 | Line 837 | public class Phaser {
837  
838      /**
839       * Enqueues node and waits unless aborted or signalled.
840 +     *
841       * @return current phase
842       */
843      private int untimedWait(int phase) {
# Line 912 | Line 925 | public class Phaser {
925          return p;
926      }
927  
928 <    // Temporary Unsafe mechanics for preliminary release
928 >    // Unsafe mechanics
929 >
930 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
931 >    private static final long stateOffset =
932 >        objectFieldOffset("state", Phaser.class);
933  
934 <    static final Unsafe _unsafe;
935 <    static final long stateOffset;
934 >    private final boolean casState(long cmp, long val) {
935 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
936 >    }
937  
938 <    static {
938 >    private static long objectFieldOffset(String field, Class<?> klazz) {
939          try {
940 <            if (Phaser.class.getClassLoader() != null) {
941 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
942 <                f.setAccessible(true);
943 <                _unsafe = (Unsafe)f.get(null);
944 <            }
945 <            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);
940 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
941 >        } catch (NoSuchFieldException e) {
942 >            // Convert Exception to corresponding Error
943 >            NoSuchFieldError error = new NoSuchFieldError(field);
944 >            error.initCause(e);
945 >            throw error;
946          }
947      }
948  
949 <    final boolean casState(long cmp, long val) {
950 <        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
949 >    /**
950 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
951 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
952 >     * into a jdk.
953 >     *
954 >     * @return a sun.misc.Unsafe
955 >     */
956 >    private static sun.misc.Unsafe getUnsafe() {
957 >        try {
958 >            return sun.misc.Unsafe.getUnsafe();
959 >        } catch (SecurityException se) {
960 >            try {
961 >                return java.security.AccessController.doPrivileged
962 >                    (new java.security
963 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
964 >                        public sun.misc.Unsafe run() throws Exception {
965 >                            java.lang.reflect.Field f = sun.misc
966 >                                .Unsafe.class.getDeclaredField("theUnsafe");
967 >                            f.setAccessible(true);
968 >                            return (sun.misc.Unsafe) f.get(null);
969 >                        }});
970 >            } catch (java.security.PrivilegedActionException e) {
971 >                throw new RuntimeException("Could not initialize intrinsics",
972 >                                           e.getCause());
973 >            }
974 >        }
975      }
976   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines