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.15 by jsr166, Tue Jul 21 18:11:44 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 200 | Line 199 | public class Phaser {
199       * and encoding simple, and keeping race windows short.
200       *
201       * Note: there are some cheats in arrive() that rely on unarrived
202 <     * being lowest 16 bits.
202 >     * count being lowest 16 bits.
203       */
204      private volatile long state;
205  
206      private static final int ushortBits = 16;
207 <    private static final int ushortMask =  (1 << ushortBits) - 1;
208 <    private static final int phaseMask = 0x7fffffff;
207 >    private static final int ushortMask = 0xffff;
208 >    private static final int phaseMask  = 0x7fffffff;
209  
210      private static int unarrivedOf(long s) {
211          return (int)(s & ushortMask);
212      }
213  
214      private static int partiesOf(long s) {
215 <        return (int)(s & (ushortMask << 16)) >>> 16;
215 >        return ((int)s) >>> 16;
216      }
217  
218      private static int phaseOf(long s) {
# Line 225 | Line 224 | public class Phaser {
224      }
225  
226      private static long stateFor(int phase, int parties, int unarrived) {
227 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
227 >        return ((((long)phase) << 32) | (((long)parties) << 16) |
228 >                (long)unarrived);
229      }
230  
231      private static long trippedStateFor(int phase, int parties) {
232 <        return (((long)phase) << 32) | ((parties << 16) | parties);
232 >        long lp = (long)parties;
233 >        return (((long)phase) << 32) | (lp << 16) | lp;
234      }
235  
236 <    private static IllegalStateException badBounds(int parties, int unarrived) {
237 <        return new IllegalStateException
238 <            ("Attempt to set " + unarrived +
239 <             " unarrived of " + parties + " parties");
236 >    /**
237 >     * Returns message string for bad bounds exceptions.
238 >     */
239 >    private static String badBounds(int parties, int unarrived) {
240 >        return ("Attempt to set " + unarrived +
241 >                " unarrived of " + parties + " parties");
242      }
243  
244      /**
# Line 252 | Line 255 | public class Phaser {
255      // Wait queues
256  
257      /**
258 <     * Heads of Treiber stacks waiting for nonFJ threads. To eliminate
258 >     * Heads of Treiber stacks for waiting threads. To eliminate
259       * contention while releasing some threads while adding others, we
260       * use two of them, alternating across even and odd phases.
261       */
# Line 296 | Line 299 | public class Phaser {
299  
300      /**
301       * Creates a new Phaser without any initially registered parties,
302 <     * initial phase number 0, and no parent.
302 >     * initial phase number 0, and no parent. Any thread using this
303 >     * Phaser will need to first register for it.
304       */
305      public Phaser() {
306          this(null);
# Line 305 | Line 309 | public class Phaser {
309      /**
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);
# Line 318 | Line 323 | public class Phaser {
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 334 | Line 340 | public class Phaser {
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
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 358 | 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 368 | 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 394 | Line 403 | public class Phaser {
403              if (phase < 0)
404                  break;
405              if (parties > ushortMask || unarrived > ushortMask)
406 <                throw badBounds(parties, unarrived);
406 >                throw new IllegalStateException(badBounds(parties, unarrived));
407              if (phase == phaseOf(root.state) &&
408                  casState(s, stateFor(phase, parties, unarrived)))
409                  break;
# Line 407 | 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;
425          for (;;) {
426              long s = state;
427              phase = phaseOf(s);
428 +            if (phase < 0)
429 +                break;
430              int parties = partiesOf(s);
431              int unarrived = unarrivedOf(s) - 1;
432              if (unarrived > 0) {        // Not the last arrival
# Line 441 | Line 452 | public class Phaser {
452                      }
453                  }
454              }
444            else if (phase < 0) // Don't throw exception if terminated
445                break;
455              else if (phase != phaseOf(root.state)) // or if unreconciled
456                  reconcileState();
457              else
458 <                throw badBounds(parties, unarrived);
458 >                throw new IllegalStateException(badBounds(parties, unarrived));
459          }
460          return phase;
461      }
# Line 459 | Line 468 | public class Phaser {
468       * zero parties, this phaser is also deregistered from its parent.
469       *
470       * @return the current barrier phase number upon entry to
471 <     * this method, or a negative value if terminated;
471 >     * this method, or a negative value if terminated
472       * @throws IllegalStateException if not terminated and the number
473 <     * of registered or unarrived parties would become negative.
473 >     * of registered or unarrived parties would become negative
474       */
475      public int arriveAndDeregister() {
476          // similar code to arrive, but too different to merge
# Line 470 | Line 479 | public class Phaser {
479          for (;;) {
480              long s = state;
481              phase = phaseOf(s);
482 +            if (phase < 0)
483 +                break;
484              int parties = partiesOf(s) - 1;
485              int unarrived = unarrivedOf(s) - 1;
486              if (parties >= 0) {
# Line 495 | Line 506 | public class Phaser {
506                      }
507                      continue;
508                  }
498                if (phase < 0)
499                    break;
509                  if (par != null && phase != phaseOf(root.state)) {
510                      reconcileState();
511                      continue;
512                  }
513              }
514 <            throw badBounds(parties, unarrived);
514 >            throw new IllegalStateException(badBounds(parties, unarrived));
515          }
516          return phase;
517      }
# Line 512 | Line 521 | public class Phaser {
521       * to {@code awaitAdvance(arrive())}.  If you instead need to
522       * await with interruption of timeout, and/or deregister upon
523       * arrival, you can arrange them using analogous constructions.
524 +     *
525       * @return the phase on entry to this method
526       * @throws IllegalStateException if not terminated and the number
527 <     * of unarrived parties would become negative.
527 >     * of unarrived parties would become negative
528       */
529      public int arriveAndAwaitAdvance() {
530          return awaitAdvance(arrive());
# Line 524 | Line 534 | public class Phaser {
534       * Awaits the phase of the barrier to advance from the given
535       * value, or returns immediately if argument is negative or this
536       * barrier is terminated.
537 +     *
538       * @param phase the phase on entry to this method
539       * @return the phase on exit from this method
540       */
# Line 534 | Line 545 | public class Phaser {
545          int p = phaseOf(s);
546          if (p != phase)
547              return p;
548 <        if (unarrivedOf(s) == 0)
548 >        if (unarrivedOf(s) == 0 && parent != null)
549              parent.awaitAdvance(phase);
550          // Fall here even if parent waited, to reconcile and help release
551          return untimedWait(phase);
# Line 545 | Line 556 | public class Phaser {
556       * value, or returns immediately if argument is negative or this
557       * barrier is terminated, or throws InterruptedException if
558       * interrupted while waiting.
559 +     *
560       * @param phase the phase on entry to this method
561       * @return the phase on exit from this method
562       * @throws InterruptedException if thread interrupted while waiting
563       */
564 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
564 >    public int awaitAdvanceInterruptibly(int phase)
565 >        throws InterruptedException {
566          if (phase < 0)
567              return phase;
568          long s = getReconciledState();
569          int p = phaseOf(s);
570          if (p != phase)
571              return p;
572 <        if (unarrivedOf(s) != 0)
572 >        if (unarrivedOf(s) == 0 && parent != null)
573              parent.awaitAdvanceInterruptibly(phase);
574          return interruptibleWait(phase);
575      }
# Line 565 | Line 578 | public class Phaser {
578       * Awaits the phase of the barrier to advance from the given value
579       * or the given timeout elapses, or returns immediately if
580       * argument is negative or this barrier is terminated.
581 +     *
582       * @param phase the phase on entry to this method
583       * @return the phase on exit from this method
584       * @throws InterruptedException if thread interrupted while waiting
# Line 578 | Line 592 | public class Phaser {
592          int p = phaseOf(s);
593          if (p != phase)
594              return p;
595 <        if (unarrivedOf(s) == 0)
595 >        if (unarrivedOf(s) == 0 && parent != null)
596              parent.awaitAdvanceInterruptibly(phase, timeout, unit);
597          return timedWait(phase, unit.toNanos(timeout));
598      }
# Line 611 | Line 625 | public class Phaser {
625       * Returns the current phase number. The maximum phase number is
626       * {@code Integer.MAX_VALUE}, after which it restarts at
627       * zero. Upon termination, the phase number is negative.
628 +     *
629       * @return the phase number, or a negative value if terminated
630       */
631      public final int getPhase() {
# Line 619 | Line 634 | public class Phaser {
634  
635      /**
636       * Returns {@code true} if the current phase number equals the given phase.
637 +     *
638       * @param phase the phase
639       * @return {@code true} if the current phase number equals the given phase
640       */
# Line 628 | Line 644 | public class Phaser {
644  
645      /**
646       * Returns the number of parties registered at this barrier.
647 +     *
648       * @return the number of parties
649       */
650      public int getRegisteredParties() {
# Line 637 | Line 654 | public class Phaser {
654      /**
655       * Returns the number of parties that have arrived at the current
656       * phase of this barrier.
657 +     *
658       * @return the number of arrived parties
659       */
660      public int getArrivedParties() {
# Line 646 | Line 664 | public class Phaser {
664      /**
665       * Returns the number of registered parties that have not yet
666       * arrived at the current phase of this barrier.
667 +     *
668       * @return the number of unarrived parties
669       */
670      public int getUnarrivedParties() {
# Line 654 | Line 673 | public class Phaser {
673  
674      /**
675       * Returns the parent of this phaser, or null if none.
676 +     *
677       * @return the parent of this phaser, or null if none
678       */
679      public Phaser getParent() {
# Line 663 | Line 683 | public class Phaser {
683      /**
684       * Returns the root ancestor of this phaser, which is the same as
685       * this phaser if it has no parent.
686 +     *
687       * @return the root ancestor of this phaser
688       */
689      public Phaser getRoot() {
# Line 671 | Line 692 | public class Phaser {
692  
693      /**
694       * Returns {@code true} if this barrier has been terminated.
695 +     *
696       * @return {@code true} if this barrier has been terminated
697       */
698      public boolean isTerminated() {
# Line 729 | Line 751 | public class Phaser {
751  
752      // methods for waiting
753  
732    /** The number of CPUs, for spin control */
733    static final int NCPUS = Runtime.getRuntime().availableProcessors();
734
735    /**
736     * The number of times to spin before blocking in timed waits.
737     * The value is empirically derived.
738     */
739    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
740
741    /**
742     * The number of times to spin before blocking in untimed waits.
743     * This is greater than timed value because untimed waits spin
744     * faster since they don't need to check times on each spin.
745     */
746    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.
755 >     * Wait nodes for Treiber stack representing wait queue
756       */
757 <    static final class QNode {
758 <        QNode next;
757 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
758 >        final Phaser phaser;
759 >        final int phase;
760 >        final long startTime;
761 >        final long nanos;
762 >        final boolean timed;
763 >        final boolean interruptible;
764 >        volatile boolean wasInterrupted = false;
765          volatile Thread thread; // nulled to cancel wait
766 <        QNode() {
766 >        QNode next;
767 >        QNode(Phaser phaser, int phase, boolean interruptible,
768 >              boolean timed, long startTime, long nanos) {
769 >            this.phaser = phaser;
770 >            this.phase = phase;
771 >            this.timed = timed;
772 >            this.interruptible = interruptible;
773 >            this.startTime = startTime;
774 >            this.nanos = nanos;
775              thread = Thread.currentThread();
776          }
777 +        public boolean isReleasable() {
778 +            return (thread == null ||
779 +                    phaser.getPhase() != phase ||
780 +                    (interruptible && wasInterrupted) ||
781 +                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
782 +        }
783 +        public boolean block() {
784 +            if (Thread.interrupted()) {
785 +                wasInterrupted = true;
786 +                if (interruptible)
787 +                    return true;
788 +            }
789 +            if (!timed)
790 +                LockSupport.park(this);
791 +            else {
792 +                long waitTime = nanos - (System.nanoTime() - startTime);
793 +                if (waitTime <= 0)
794 +                    return true;
795 +                LockSupport.parkNanos(this, waitTime);
796 +            }
797 +            return isReleasable();
798 +        }
799          void signal() {
800              Thread t = thread;
801              if (t != null) {
# Line 768 | Line 803 | public class Phaser {
803                  LockSupport.unpark(t);
804              }
805          }
806 +        boolean doWait() {
807 +            if (thread != null) {
808 +                try {
809 +                    ForkJoinPool.managedBlock(this, false);
810 +                } catch (InterruptedException ie) {
811 +                }
812 +            }
813 +            return wasInterrupted;
814 +        }
815 +
816      }
817  
818      /**
819 <     * Removes and signals waiting threads from wait queue
819 >     * Removes and signals waiting threads from wait queue.
820       */
821      private void releaseWaiters(int phase) {
822          AtomicReference<QNode> head = queueFor(phase);
# Line 783 | Line 828 | public class Phaser {
828      }
829  
830      /**
831 +     * Tries to enqueue given node in the appropriate wait queue.
832 +     *
833 +     * @return true if successful
834 +     */
835 +    private boolean tryEnqueue(QNode node) {
836 +        AtomicReference<QNode> head = queueFor(node.phase);
837 +        return head.compareAndSet(node.next = head.get(), node);
838 +    }
839 +
840 +    /**
841       * Enqueues node and waits unless aborted or signalled.
842 +     *
843 +     * @return current phase
844       */
845      private int untimedWait(int phase) {
789        int spins = maxUntimedSpins;
846          QNode node = null;
791        boolean interrupted = false;
847          boolean queued = false;
848 +        boolean interrupted = false;
849          int p;
850          while ((p = getPhase()) == phase) {
851 <            interrupted = Thread.interrupted();
852 <            if (node != null) {
853 <                if (!queued) {
854 <                    AtomicReference<QNode> head = queueFor(phase);
855 <                    queued = head.compareAndSet(node.next = head.get(), node);
856 <                }
801 <                else if (node.thread != null)
802 <                    LockSupport.park(this);
803 <            }
804 <            else if (spins <= 0)
805 <                node = new QNode();
851 >            if (Thread.interrupted())
852 >                interrupted = true;
853 >            else if (node == null)
854 >                node = new QNode(this, phase, false, false, 0, 0);
855 >            else if (!queued)
856 >                queued = tryEnqueue(node);
857              else
858 <                --spins;
858 >                interrupted = node.doWait();
859          }
860          if (node != null)
861              node.thread = null;
862 +        releaseWaiters(phase);
863          if (interrupted)
864              Thread.currentThread().interrupt();
813        releaseWaiters(phase);
865          return p;
866      }
867  
868      /**
869 <     * Messier interruptible version
869 >     * Interruptible version
870 >     * @return current phase
871       */
872      private int interruptibleWait(int phase) throws InterruptedException {
821        int spins = maxUntimedSpins;
873          QNode node = null;
874          boolean queued = false;
875          boolean interrupted = false;
876          int p;
877 <        while ((p = getPhase()) == phase) {
878 <            if (interrupted = Thread.interrupted())
879 <                break;
880 <            if (node != null) {
881 <                if (!queued) {
882 <                    AtomicReference<QNode> head = queueFor(phase);
883 <                    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();
877 >        while ((p = getPhase()) == phase && !interrupted) {
878 >            if (Thread.interrupted())
879 >                interrupted = true;
880 >            else if (node == null)
881 >                node = new QNode(this, phase, true, false, 0, 0);
882 >            else if (!queued)
883 >                queued = tryEnqueue(node);
884              else
885 <                --spins;
885 >                interrupted = node.doWait();
886          }
887          if (node != null)
888              node.thread = null;
889 +        if (p != phase || (p = getPhase()) != phase)
890 +            releaseWaiters(phase);
891          if (interrupted)
892              throw new InterruptedException();
846        releaseWaiters(phase);
893          return p;
894      }
895  
896      /**
897 <     * Even messier timeout version.
897 >     * Timeout version.
898 >     * @return current phase
899       */
900      private int timedWait(int phase, long nanos)
901          throws InterruptedException, TimeoutException {
902 +        long startTime = System.nanoTime();
903 +        QNode node = null;
904 +        boolean queued = false;
905 +        boolean interrupted = false;
906          int p;
907 <        if ((p = getPhase()) == phase) {
908 <            long lastTime = System.nanoTime();
909 <            int spins = maxTimedSpins;
910 <            QNode node = null;
911 <            boolean queued = false;
912 <            boolean interrupted = false;
913 <            while ((p = getPhase()) == phase) {
914 <                if (interrupted = Thread.interrupted())
915 <                    break;
916 <                long now = System.nanoTime();
917 <                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();
907 >        while ((p = getPhase()) == phase && !interrupted) {
908 >            if (Thread.interrupted())
909 >                interrupted = true;
910 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
911 >                break;
912 >            else if (node == null)
913 >                node = new QNode(this, phase, true, true, startTime, nanos);
914 >            else if (!queued)
915 >                queued = tryEnqueue(node);
916 >            else
917 >                interrupted = node.doWait();
918          }
919 <        releaseWaiters(phase);
919 >        if (node != null)
920 >            node.thread = null;
921 >        if (p != phase || (p = getPhase()) != phase)
922 >            releaseWaiters(phase);
923 >        if (interrupted)
924 >            throw new InterruptedException();
925 >        if (p == phase)
926 >            throw new TimeoutException();
927          return p;
928      }
929  
930      // Temporary Unsafe mechanics for preliminary release
931 +    private static Unsafe getUnsafe() throws Throwable {
932 +        try {
933 +            return Unsafe.getUnsafe();
934 +        } catch (SecurityException se) {
935 +            try {
936 +                return java.security.AccessController.doPrivileged
937 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
938 +                        public Unsafe run() throws Exception {
939 +                            return getUnsafePrivileged();
940 +                        }});
941 +            } catch (java.security.PrivilegedActionException e) {
942 +                throw e.getCause();
943 +            }
944 +        }
945 +    }
946  
947 <    static final Unsafe _unsafe;
947 >    private static Unsafe getUnsafePrivileged()
948 >            throws NoSuchFieldException, IllegalAccessException {
949 >        Field f = Unsafe.class.getDeclaredField("theUnsafe");
950 >        f.setAccessible(true);
951 >        return (Unsafe) f.get(null);
952 >    }
953 >
954 >    private static long fieldOffset(String fieldName)
955 >            throws NoSuchFieldException {
956 >        return UNSAFE.objectFieldOffset
957 >            (Phaser.class.getDeclaredField(fieldName));
958 >    }
959 >
960 >    static final Unsafe UNSAFE;
961      static final long stateOffset;
962  
963      static {
964          try {
965 <            if (Phaser.class.getClassLoader() != null) {
966 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
967 <                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) {
965 >            UNSAFE = getUnsafe();
966 >            stateOffset = fieldOffset("state");
967 >        } catch (Throwable e) {
968              throw new RuntimeException("Could not initialize intrinsics", e);
969          }
970      }
971  
972      final boolean casState(long cmp, long val) {
973 <        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
973 >        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
974      }
975   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines