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.5 by dl, Sun Sep 7 11:24:26 2008 UTC vs.
Revision 1.13 by jsr166, Mon Jul 20 22:40:09 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;
# Line 13 | Line 14 | import java.lang.reflect.*;
14  
15   /**
16   * A reusable synchronization barrier, similar in functionality to a
17 < * {@link java.util.concurrent.CyclicBarrier} and {@link
18 < * java.util.concurrent.CountDownLatch} but supporting more flexible
19 < * usage.
17 > * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
18 > * {@link java.util.concurrent.CountDownLatch CountDownLatch}
19 > * but supporting more flexible usage.
20   *
21   * <ul>
22   *
# Line 25 | Line 26 | import java.lang.reflect.*;
26   * basic synchronization constructs, registration and deregistration
27   * affect only internal counts; they do not establish any further
28   * internal bookkeeping, so tasks cannot query whether they are
29 < * registered. (However, you can introduce such bookkeeping in by
29 > * registered. (However, you can introduce such bookkeeping by
30   * subclassing this class.)
31   *
32   * <li> Each generation has an associated phase value, starting at
33   * zero, and advancing when all parties reach the barrier (wrapping
34 < * around to zero after reaching <tt>Integer.MAX_VALUE</tt>).
34 > * around to zero after reaching {@code Integer.MAX_VALUE}).
35   *
36   * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
37 < * Method <tt>arriveAndAwaitAdvance</tt> has effect analogous to
38 < * <tt>CyclicBarrier.await</tt>.  However, Phasers separate two
37 > * Method {@code arriveAndAwaitAdvance} has effect analogous to
38 > * {@code CyclicBarrier.await}.  However, Phasers separate two
39   * aspects of coordination, that may also be invoked independently:
40   *
41   * <ul>
42   *
43 < *   <li> Arriving at a barrier. Methods <tt>arrive</tt> and
44 < *       <tt>arriveAndDeregister</tt> do not block, but return
43 > *   <li> Arriving at a barrier. Methods {@code arrive} and
44 > *       {@code arriveAndDeregister} do not block, but return
45   *       the phase value current upon entry to the method.
46   *
47 < *   <li> Awaiting others. Method <tt>awaitAdvance</tt> requires an
47 > *   <li> Awaiting others. Method {@code awaitAdvance} requires an
48   *       argument indicating the entry phase, and returns when the
49   *       barrier advances to a new phase.
50   * </ul>
# Line 51 | Line 52 | import java.lang.reflect.*;
52   *
53   * <li> Barrier actions, performed by the task triggering a phase
54   * advance while others may be waiting, are arranged by overriding
55 < * method <tt>onAdvance</tt>, that also controls termination.
55 > * method {@code onAdvance}, that also controls termination.
56   * Overriding this method may be used to similar but more flexible
57   * effect as providing a barrier action to a CyclicBarrier.
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 <tt>onAdvance</tt> 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 < * <tt>forceTermination</tt> 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 72 | Line 74 | import java.lang.reflect.*;
74   * This will typically greatly increase throughput even though it
75   * incurs somewhat greater per-operation overhead.
76   *
77 < * <li> By default, <tt>awaitAdvance</tt> continues to wait even if
77 > * <li> By default, {@code awaitAdvance} continues to wait even if
78   * the waiting thread is interrupted. And unlike the case in
79   * CyclicBarriers, exceptions encountered while tasks wait
80   * interruptibly or with timeout do not change the state of the
81   * barrier. If necessary, you can perform any associated recovery
82   * within handlers of those exceptions, often after invoking
83 < * <tt>forceTermination</tt>.
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>
90   *
91 < * <p>A Phaser may be used instead of a <tt>CountdownLatch</tt> to control
91 > * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
92   * a one-shot action serving a variable number of parties. The typical
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();
111   *   phaser.arrive(); // allow threads to start
112 < *   int p = phaser.arriveAndDeregister(); // deregister self
112 > *   int p = phaser.arriveAndDeregister(); // deregister self  ...
113 > *   p = phaser.awaitAdvance(p); // ... and await arrival
114   *   otherActions(); // do other things while tasks execute
115 < *   phaser.awaitAdvance(p); // wait for all tasks to arrive
116 < * }
110 < * </pre>
115 > *   phaser.awaitAdvance(p); // await final completion
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 <tt>onAdvance</tt>:
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 < *    };
122 < *    phaser.register();
123 < *    for (Runnable r : list) {
124 < *      phaser.register();
125 < *      new Thread() {
126 < *        public void run() {
127 < *           do {
128 < *             r.run();
129 < *             phaser.arriveAndAwaitAdvance();
130 < *           } while(!phaser.isTerminated();
131 < *        }
132 < *      }.start();
138 > *     }.start();
139   *   }
140   *   phaser.arriveAndDeregister(); // deregister self, don't wait
141 < * }
136 < * </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
160 < *  build(new Task[n], 0, n, new Phaser());
161 < * </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 <tt>TASKS_PER_PHASER</tt> depends mainly on
166 > * The best value of {@code TASKS_PER_PHASER} depends mainly on
167   * expected barrier synchronization rates. A value as low as four may
168   * be appropriate for extremely small per-barrier task bodies (thus
169   * high rates), or up to hundreds for extremely large ones.
# Line 192 | Line 195 | public class Phaser {
195       * However, to efficiently maintain atomicity, these values are
196       * packed into a single (atomic) long. Termination uses the sign
197       * bit of 32 bit representation of phase, so phase is set to -1 on
198 <     * termination. Good performace relies on keeping state decoding
198 >     * termination. Good performance relies on keeping state decoding
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 221 | 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 248 | 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 292 | 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 390 | Line 398 | public class Phaser {
398              if (phase < 0)
399                  break;
400              if (parties > ushortMask || unarrived > ushortMask)
401 <                throw badBounds(parties, unarrived);
401 >                throw new IllegalStateException(badBounds(parties, unarrived));
402              if (phase == phaseOf(root.state) &&
403                  casState(s, stateFor(phase, parties, unarrived)))
404                  break;
# Line 412 | Line 420 | public class Phaser {
420          for (;;) {
421              long s = state;
422              phase = phaseOf(s);
423 +            if (phase < 0)
424 +                break;
425              int parties = partiesOf(s);
426              int unarrived = unarrivedOf(s) - 1;
427              if (unarrived > 0) {        // Not the last arrival
# Line 437 | Line 447 | public class Phaser {
447                      }
448                  }
449              }
440            else if (phase < 0) // Don't throw exception if terminated
441                break;
450              else if (phase != phaseOf(root.state)) // or if unreconciled
451                  reconcileState();
452              else
453 <                throw badBounds(parties, unarrived);
453 >                throw new IllegalStateException(badBounds(parties, unarrived));
454          }
455          return phase;
456      }
# Line 466 | Line 474 | public class Phaser {
474          for (;;) {
475              long s = state;
476              phase = phaseOf(s);
477 +            if (phase < 0)
478 +                break;
479              int parties = partiesOf(s) - 1;
480              int unarrived = unarrivedOf(s) - 1;
481              if (parties >= 0) {
# Line 491 | Line 501 | public class Phaser {
501                      }
502                      continue;
503                  }
494                if (phase < 0)
495                    break;
504                  if (par != null && phase != phaseOf(root.state)) {
505                      reconcileState();
506                      continue;
507                  }
508              }
509 <            throw badBounds(parties, unarrived);
509 >            throw new IllegalStateException(badBounds(parties, unarrived));
510          }
511          return phase;
512      }
513  
514      /**
515       * Arrives at the barrier and awaits others. Equivalent in effect
516 <     * to <tt>awaitAdvance(arrive())</tt>.  If you instead need to
516 >     * to {@code awaitAdvance(arrive())}.  If you instead need to
517       * await with interruption of timeout, and/or deregister upon
518       * arrival, you can arrange them using analogous constructions.
519       * @return the phase on entry to this method
# Line 530 | Line 538 | public class Phaser {
538          int p = phaseOf(s);
539          if (p != phase)
540              return p;
541 <        if (unarrivedOf(s) == 0)
541 >        if (unarrivedOf(s) == 0 && parent != null)
542              parent.awaitAdvance(phase);
543          // Fall here even if parent waited, to reconcile and help release
544          return untimedWait(phase);
# Line 538 | Line 546 | public class Phaser {
546  
547      /**
548       * Awaits the phase of the barrier to advance from the given
549 <     * value, or returns immediately if argumet is negative or this
549 >     * value, or returns immediately if argument is negative or this
550       * barrier is terminated, or throws InterruptedException if
551       * interrupted while waiting.
552       * @param phase the phase on entry to this method
553       * @return the phase on exit from this method
554       * @throws InterruptedException if thread interrupted while waiting
555       */
556 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
556 >    public int awaitAdvanceInterruptibly(int phase)
557 >        throws InterruptedException {
558          if (phase < 0)
559              return phase;
560          long s = getReconciledState();
561          int p = phaseOf(s);
562          if (p != phase)
563              return p;
564 <        if (unarrivedOf(s) != 0)
564 >        if (unarrivedOf(s) == 0 && parent != null)
565              parent.awaitAdvanceInterruptibly(phase);
566          return interruptibleWait(phase);
567      }
# Line 574 | Line 583 | public class Phaser {
583          int p = phaseOf(s);
584          if (p != phase)
585              return p;
586 <        if (unarrivedOf(s) == 0)
586 >        if (unarrivedOf(s) == 0 && parent != null)
587              parent.awaitAdvanceInterruptibly(phase, timeout, unit);
588          return timedWait(phase, unit.toNanos(timeout));
589      }
# Line 605 | Line 614 | public class Phaser {
614  
615      /**
616       * Returns the current phase number. The maximum phase number is
617 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
617 >     * {@code Integer.MAX_VALUE}, after which it restarts at
618       * zero. Upon termination, the phase number is negative.
619       * @return the phase number, or a negative value if terminated
620       */
# Line 614 | Line 623 | public class Phaser {
623      }
624  
625      /**
626 <     * Returns true if the current phase number equals the given phase.
626 >     * Returns {@code true} if the current phase number equals the given phase.
627       * @param phase the phase
628 <     * @return true if the current phase number equals the given phase.
628 >     * @return {@code true} if the current phase number equals the given phase
629       */
630      public final boolean hasPhase(int phase) {
631          return phaseOf(getReconciledState()) == phase;
# Line 650 | Line 659 | public class Phaser {
659  
660      /**
661       * Returns the parent of this phaser, or null if none.
662 <     * @return the parent of this phaser, or null if none.
662 >     * @return the parent of this phaser, or null if none
663       */
664      public Phaser getParent() {
665          return parent;
# Line 659 | Line 668 | public class Phaser {
668      /**
669       * Returns the root ancestor of this phaser, which is the same as
670       * this phaser if it has no parent.
671 <     * @return the root ancestor of this phaser.
671 >     * @return the root ancestor of this phaser
672       */
673      public Phaser getRoot() {
674          return root;
675      }
676  
677      /**
678 <     * Returns true if this barrier has been terminated.
679 <     * @return true if this barrier has been terminated
678 >     * Returns {@code true} if this barrier has been terminated.
679 >     * @return {@code true} if this barrier has been terminated
680       */
681      public boolean isTerminated() {
682          return getPhase() < 0;
# Line 679 | Line 688 | public class Phaser {
688       * barrier is tripped (and thus all other waiting parties are
689       * dormant). If it returns true, then, rather than advance the
690       * phase number, this barrier will be set to a final termination
691 <     * state, and subsequent calls to <tt>isTerminated</tt> will
691 >     * state, and subsequent calls to {@code isTerminated} will
692       * return true.
693       *
694       * <p> The default version returns true when the number of
# Line 690 | Line 699 | public class Phaser {
699       * <p> You may override this method to perform an action with side
700       * effects visible to participating tasks, but it is in general
701       * only sensible to do so in designs where all parties register
702 <     * before any arrive, and all <tt>awaitAdvance</tt> at each phase.
702 >     * before any arrive, and all {@code awaitAdvance} at each phase.
703       * Otherwise, you cannot ensure lack of interference. In
704       * particular, this method may be invoked more than once per
705       * transition if other parties successfully register while the
# Line 699 | Line 708 | public class Phaser {
708       * method.
709       *
710       * @param phase the phase number on entering the barrier
711 <     * @param registeredParties the current number of registered
712 <     * parties.
704 <     * @return true if this barrier should terminate
711 >     * @param registeredParties the current number of registered parties
712 >     * @return {@code true} if this barrier should terminate
713       */
714      protected boolean onAdvance(int phase, int registeredParties) {
715          return registeredParties <= 0;
# Line 710 | Line 718 | public class Phaser {
718      /**
719       * Returns a string identifying this phaser, as well as its
720       * state.  The state, in brackets, includes the String {@code
721 <     * "phase ="} followed by the phase number, {@code "parties ="}
721 >     * "phase = "} followed by the phase number, {@code "parties = "}
722       * followed by the number of registered parties, and {@code
723 <     * "arrived ="} followed by the number of arrived parties
723 >     * "arrived = "} followed by the number of arrived parties.
724       *
725       * @return a string identifying this barrier, as well as its state
726       */
727      public String toString() {
728          long s = getReconciledState();
729 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
729 >        return super.toString() +
730 >            "[phase = " + phaseOf(s) +
731 >            " parties = " + partiesOf(s) +
732 >            " arrived = " + arrivedOf(s) + "]";
733      }
734  
735      // methods for waiting
736  
726    /** The number of CPUs, for spin control */
727    static final int NCPUS = Runtime.getRuntime().availableProcessors();
728
729    /**
730     * The number of times to spin before blocking in timed waits.
731     * The value is empirically derived.
732     */
733    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
734
735    /**
736     * The number of times to spin before blocking in untimed waits.
737     * This is greater than timed value because untimed waits spin
738     * faster since they don't need to check times on each spin.
739     */
740    static final int maxUntimedSpins = maxTimedSpins * 32;
741
742    /**
743     * The number of nanoseconds for which it is faster to spin
744     * rather than to use timed park. A rough estimate suffices.
745     */
746    static final long spinForTimeoutThreshold = 1000L;
747
737      /**
738 <     * Wait nodes for Treiber stack representing wait queue for non-FJ
750 <     * tasks.
738 >     * Wait nodes for Treiber stack representing wait queue
739       */
740 <    static final class QNode {
741 <        QNode next;
740 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
741 >        final Phaser phaser;
742 >        final int phase;
743 >        final long startTime;
744 >        final long nanos;
745 >        final boolean timed;
746 >        final boolean interruptible;
747 >        volatile boolean wasInterrupted = false;
748          volatile Thread thread; // nulled to cancel wait
749 <        QNode() {
749 >        QNode next;
750 >        QNode(Phaser phaser, int phase, boolean interruptible,
751 >              boolean timed, long startTime, long nanos) {
752 >            this.phaser = phaser;
753 >            this.phase = phase;
754 >            this.timed = timed;
755 >            this.interruptible = interruptible;
756 >            this.startTime = startTime;
757 >            this.nanos = nanos;
758              thread = Thread.currentThread();
759          }
760 +        public boolean isReleasable() {
761 +            return (thread == null ||
762 +                    phaser.getPhase() != phase ||
763 +                    (interruptible && wasInterrupted) ||
764 +                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
765 +        }
766 +        public boolean block() {
767 +            if (Thread.interrupted()) {
768 +                wasInterrupted = true;
769 +                if (interruptible)
770 +                    return true;
771 +            }
772 +            if (!timed)
773 +                LockSupport.park(this);
774 +            else {
775 +                long waitTime = nanos - (System.nanoTime() - startTime);
776 +                if (waitTime <= 0)
777 +                    return true;
778 +                LockSupport.parkNanos(this, waitTime);
779 +            }
780 +            return isReleasable();
781 +        }
782          void signal() {
783              Thread t = thread;
784              if (t != null) {
# Line 762 | Line 786 | public class Phaser {
786                  LockSupport.unpark(t);
787              }
788          }
789 +        boolean doWait() {
790 +            if (thread != null) {
791 +                try {
792 +                    ForkJoinPool.managedBlock(this, false);
793 +                } catch (InterruptedException ie) {
794 +                }
795 +            }
796 +            return wasInterrupted;
797 +        }
798 +
799      }
800  
801      /**
# Line 777 | Line 811 | public class Phaser {
811      }
812  
813      /**
814 +     * Tries to enqueue given node in the appropriate wait queue
815 +     * @return true if successful
816 +     */
817 +    private boolean tryEnqueue(QNode node) {
818 +        AtomicReference<QNode> head = queueFor(node.phase);
819 +        return head.compareAndSet(node.next = head.get(), node);
820 +    }
821 +
822 +    /**
823       * Enqueues node and waits unless aborted or signalled.
824 +     * @return current phase
825       */
826      private int untimedWait(int phase) {
783        int spins = maxUntimedSpins;
827          QNode node = null;
785        boolean interrupted = false;
828          boolean queued = false;
829 +        boolean interrupted = false;
830          int p;
831          while ((p = getPhase()) == phase) {
832 <            interrupted = Thread.interrupted();
833 <            if (node != null) {
834 <                if (!queued) {
835 <                    AtomicReference<QNode> head = queueFor(phase);
836 <                    queued = head.compareAndSet(node.next = head.get(), node);
837 <                }
795 <                else if (node.thread != null)
796 <                    LockSupport.park(this);
797 <            }
798 <            else if (spins <= 0)
799 <                node = new QNode();
832 >            if (Thread.interrupted())
833 >                interrupted = true;
834 >            else if (node == null)
835 >                node = new QNode(this, phase, false, false, 0, 0);
836 >            else if (!queued)
837 >                queued = tryEnqueue(node);
838              else
839 <                --spins;
839 >                interrupted = node.doWait();
840          }
841          if (node != null)
842              node.thread = null;
843 +        releaseWaiters(phase);
844          if (interrupted)
845              Thread.currentThread().interrupt();
807        releaseWaiters(phase);
846          return p;
847      }
848  
849      /**
850 <     * Messier interruptible version
850 >     * Interruptible version
851 >     * @return current phase
852       */
853      private int interruptibleWait(int phase) throws InterruptedException {
815        int spins = maxUntimedSpins;
854          QNode node = null;
855          boolean queued = false;
856          boolean interrupted = false;
857          int p;
858 <        while ((p = getPhase()) == phase) {
859 <            if (interrupted = Thread.interrupted())
860 <                break;
861 <            if (node != null) {
862 <                if (!queued) {
863 <                    AtomicReference<QNode> head = queueFor(phase);
864 <                    queued = head.compareAndSet(node.next = head.get(), node);
827 <                }
828 <                else if (node.thread != null)
829 <                    LockSupport.park(this);
830 <            }
831 <            else if (spins <= 0)
832 <                node = new QNode();
858 >        while ((p = getPhase()) == phase && !interrupted) {
859 >            if (Thread.interrupted())
860 >                interrupted = true;
861 >            else if (node == null)
862 >                node = new QNode(this, phase, true, false, 0, 0);
863 >            else if (!queued)
864 >                queued = tryEnqueue(node);
865              else
866 <                --spins;
866 >                interrupted = node.doWait();
867          }
868          if (node != null)
869              node.thread = null;
870 +        if (p != phase || (p = getPhase()) != phase)
871 +            releaseWaiters(phase);
872          if (interrupted)
873              throw new InterruptedException();
840        releaseWaiters(phase);
874          return p;
875      }
876  
877      /**
878 <     * Even messier timeout version.
878 >     * Timeout version.
879 >     * @return current phase
880       */
881      private int timedWait(int phase, long nanos)
882          throws InterruptedException, TimeoutException {
883 +        long startTime = System.nanoTime();
884 +        QNode node = null;
885 +        boolean queued = false;
886 +        boolean interrupted = false;
887          int p;
888 <        if ((p = getPhase()) == phase) {
889 <            long lastTime = System.nanoTime();
890 <            int spins = maxTimedSpins;
891 <            QNode node = null;
892 <            boolean queued = false;
893 <            boolean interrupted = false;
894 <            while ((p = getPhase()) == phase) {
895 <                if (interrupted = Thread.interrupted())
896 <                    break;
897 <                long now = System.nanoTime();
898 <                if ((nanos -= now - lastTime) <= 0)
861 <                    break;
862 <                lastTime = now;
863 <                if (node != null) {
864 <                    if (!queued) {
865 <                        AtomicReference<QNode> head = queueFor(phase);
866 <                        queued = head.compareAndSet(node.next = head.get(), node);
867 <                    }
868 <                    else if (node.thread != null &&
869 <                             nanos > spinForTimeoutThreshold) {
870 <                        LockSupport.parkNanos(this, nanos);
871 <                    }
872 <                }
873 <                else if (spins <= 0)
874 <                    node = new QNode();
875 <                else
876 <                    --spins;
877 <            }
878 <            if (node != null)
879 <                node.thread = null;
880 <            if (interrupted)
881 <                throw new InterruptedException();
882 <            if (p == phase && (p = getPhase()) == phase)
883 <                throw new TimeoutException();
888 >        while ((p = getPhase()) == phase && !interrupted) {
889 >            if (Thread.interrupted())
890 >                interrupted = true;
891 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
892 >                break;
893 >            else if (node == null)
894 >                node = new QNode(this, phase, true, true, startTime, nanos);
895 >            else if (!queued)
896 >                queued = tryEnqueue(node);
897 >            else
898 >                interrupted = node.doWait();
899          }
900 <        releaseWaiters(phase);
900 >        if (node != null)
901 >            node.thread = null;
902 >        if (p != phase || (p = getPhase()) != phase)
903 >            releaseWaiters(phase);
904 >        if (interrupted)
905 >            throw new InterruptedException();
906 >        if (p == phase)
907 >            throw new TimeoutException();
908          return p;
909      }
910  
911      // Temporary Unsafe mechanics for preliminary release
912 +    private static Unsafe getUnsafe() throws Throwable {
913 +        try {
914 +            return Unsafe.getUnsafe();
915 +        } catch (SecurityException se) {
916 +            try {
917 +                return java.security.AccessController.doPrivileged
918 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
919 +                        public Unsafe run() throws Exception {
920 +                            return getUnsafePrivileged();
921 +                        }});
922 +            } catch (java.security.PrivilegedActionException e) {
923 +                throw e.getCause();
924 +            }
925 +        }
926 +    }
927 +
928 +    private static Unsafe getUnsafePrivileged()
929 +            throws NoSuchFieldException, IllegalAccessException {
930 +        Field f = Unsafe.class.getDeclaredField("theUnsafe");
931 +        f.setAccessible(true);
932 +        return (Unsafe) f.get(null);
933 +    }
934 +
935 +    private static long fieldOffset(String fieldName)
936 +            throws NoSuchFieldException {
937 +        return _unsafe.objectFieldOffset
938 +            (Phaser.class.getDeclaredField(fieldName));
939 +    }
940  
941      static final Unsafe _unsafe;
942      static final long stateOffset;
943  
944      static {
945          try {
946 <            if (Phaser.class.getClassLoader() != null) {
947 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
948 <                f.setAccessible(true);
899 <                _unsafe = (Unsafe)f.get(null);
900 <            }
901 <            else
902 <                _unsafe = Unsafe.getUnsafe();
903 <            stateOffset = _unsafe.objectFieldOffset
904 <                (Phaser.class.getDeclaredField("state"));
905 <        } catch (Exception e) {
946 >            _unsafe = getUnsafe();
947 >            stateOffset = fieldOffset("state");
948 >        } catch (Throwable e) {
949              throw new RuntimeException("Could not initialize intrinsics", e);
950          }
951      }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines