ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
(Generate patch)

Comparing jsr166/src/jsr166y/Phaser.java (file contents):
Revision 1.8 by jsr166, Mon Jan 5 05:50:47 2009 UTC vs.
Revision 1.19 by jsr166, Fri Jul 24 23:47:01 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines