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.9 by jsr166, Mon Jan 5 09:11:26 2009 UTC vs.
Revision 1.18 by jsr166, Thu Jul 23 23:07:57 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines