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.3 by jsr166, Fri Jul 25 18:11:53 2008 UTC vs.
Revision 1.35 by dl, Sun Aug 23 13:37:08 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import jsr166y.forkjoin.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
10 >
11 > import java.util.concurrent.atomic.AtomicReference;
12   import java.util.concurrent.locks.LockSupport;
13  
14   /**
15   * A reusable synchronization barrier, similar in functionality to a
16 < * {@link java.util.concurrent.CyclicBarrier}, but supporting more
17 < * flexible usage.
16 > * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
17 > * {@link java.util.concurrent.CountDownLatch CountDownLatch}
18 > * but supporting more flexible usage.
19   *
20   * <ul>
21   *
22 < * <li> The number of parties synchronizing on the barrier may vary
23 < * over time.  A task may register to be a party in a barrier at any
24 < * time, and may deregister upon arriving at the barrier.  As is the
25 < * case with most basic synchronization constructs, registration
26 < * and deregistration affect only internal counts; they do not
27 < * establish any further internal bookkeeping, so tasks cannot query
28 < * whether they are registered.
22 > * <li> The number of parties <em>registered</em> to synchronize on a
23 > * phaser may vary over time.  Tasks may be registered at any time
24 > * (using methods {@link #register}, {@link #bulkRegister}, or forms
25 > * of constructors establishing initial numbers of parties), and may
26 > * optionally be deregistered upon any arrival (using {@link
27 > * #arriveAndDeregister}).  As is the case with most basic
28 > * synchronization constructs, registration and deregistration affect
29 > * only internal counts; they do not establish any further internal
30 > * bookkeeping, so tasks cannot query whether they are
31 > * registered. (However, you can introduce such bookkeeping by
32 > * subclassing this class.)
33   *
34   * <li> Each generation has an associated phase value, starting at
35 < * zero, and advancing when all parties reach the barrier (wrapping
36 < * around to zero after reaching <tt>Integer.MAX_VALUE</tt>).
35 > * zero, and advancing when all parties arrive at the barrier
36 > * (wrapping around to zero after reaching {@code Integer.MAX_VALUE}).
37   *
38 < * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
39 < * Method <tt>arriveAndAwaitAdvance</tt> has effect analogous to
40 < * <tt>CyclicBarrier.await</tt>.  However, Phasers separate two
41 < * aspects of coordination, that may be invoked independently:
38 > * <li> Like a {@code CyclicBarrier}, a phaser may be repeatedly
39 > * awaited.  Method {@link #arriveAndAwaitAdvance} has effect
40 > * analogous to {@link java.util.concurrent.CyclicBarrier#await
41 > * CyclicBarrier.await}.  However, phasers separate two aspects of
42 > * coordination, which may also be invoked independently:
43   *
44   * <ul>
45   *
46 < *   <li> Arriving at a barrier. Methods <tt>arrive</tt> and
47 < *       <tt>arriveAndDeregister</tt> do not block, but return
48 < *       the phase value on entry to the method.
49 < *
50 < *   <li> Awaiting others. Method <tt>awaitAdvance</tt> requires an
51 < *       argument indicating the entry phase, and returns when the
52 < *       barrier advances to a new phase.
46 > *   <li> Arriving at a barrier. Methods {@link #arrive} and
47 > *       {@link #arriveAndDeregister} do not block, but return
48 > *       an associated <em>arrival phase number</em>;
49 > *       that is, the phase number of the barrier to which the
50 > *       arrival applied.
51 > *
52 > *   <li> Awaiting others. Method {@link #awaitAdvance} requires an
53 > *       argument indicating an arrival phase number, and returns
54 > *       when the barrier advances to a new phase.
55   * </ul>
56   *
57   *
58   * <li> Barrier actions, performed by the task triggering a phase
59 < * advance while others may be waiting, are arranged by overriding
60 < * method <tt>onAdvance</tt>, that also controls termination.
59 > * advance, are arranged by overriding method {@link #onAdvance(int,
60 > * int)}, which also controls termination. Overriding this method is
61 > * similar to, but more flexible than, providing a barrier action to a
62 > * {@code CyclicBarrier}.
63   *
64   * <li> Phasers may enter a <em>termination</em> state in which all
65 < * await actions immediately return, indicating (via a negative phase
66 < * value) that execution is complete.  Termination is triggered by
67 < * executing the overridable <tt>onAdvance</tt> method that is invoked
68 < * each time the barrier is tripped. When a Phaser is controlling an
69 < * action with a fixed number of iterations, it is often convenient to
70 < * override this method to cause termination when the current phase
71 < * number reaches a threshold.  Method <tt>forceTermination</tt> is
72 < * also available to assist recovery actions upon failure.
73 < *
74 < * <li> Unlike most synchronizers, a Phaser may also be used with
75 < * ForkJoinTasks (as well as plain threads).
76 < *
77 < * <li> By default, <tt>awaitAdvance</tt> continues to wait even if
78 < * the current thread is interrupted. And unlike the case in
79 < * CyclicBarriers, exceptions encountered while tasks wait
65 > * actions immediately return without updating phaser state or waiting
66 > * for advance, and indicating (via a negative phase value) that
67 > * execution is complete.  Termination is triggered when an invocation
68 > * of {@code onAdvance} returns {@code true}.  When a phaser is
69 > * controlling an action with a fixed number of iterations, it is
70 > * often convenient to override this method to cause termination when
71 > * the current phase number reaches a threshold. Method {@link
72 > * #forceTermination} is also available to abruptly release waiting
73 > * threads and allow them to terminate.
74 > *
75 > * <li> Phasers may be tiered to reduce contention. Phasers with large
76 > * numbers of parties that would otherwise experience heavy
77 > * synchronization contention costs may instead be arranged in trees.
78 > * This will typically greatly increase throughput even though it
79 > * incurs somewhat greater per-operation overhead.
80 > *
81 > * <li> By default, {@code awaitAdvance} continues to wait even if
82 > * the waiting thread is interrupted. And unlike the case in
83 > * {@code CyclicBarrier}, exceptions encountered while tasks wait
84   * interruptibly or with timeout do not change the state of the
85   * barrier. If necessary, you can perform any associated recovery
86 < * within handlers of those exceptions.
86 > * within handlers of those exceptions, often after invoking
87 > * {@code forceTermination}.
88 > *
89 > * <li>Phasers may be used to coordinate tasks executing in a {@link
90 > * ForkJoinPool}, which will ensure sufficient parallelism to execute
91 > * tasks when others are blocked waiting for a phase to advance.
92   *
93   * </ul>
94   *
95 < * <p><b>Sample usage:</b>
95 > * <p><b>Sample usages:</b>
96   *
97 < * <p>[todo: non-FJ example]
97 > * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
98 > * to control a one-shot action serving a variable number of
99 > * parties. The typical idiom is for the method setting this up to
100 > * first register, then start the actions, then deregister, as in:
101 > *
102 > *  <pre> {@code
103 > * void runTasks(List<Runnable> tasks) {
104 > *   final Phaser phaser = new Phaser(1); // "1" to register self
105 > *   // create and start threads
106 > *   for (Runnable task : tasks) {
107 > *     phaser.register();
108 > *     new Thread() {
109 > *       public void run() {
110 > *         phaser.arriveAndAwaitAdvance(); // await all creation
111 > *         task.run();
112 > *       }
113 > *     }.start();
114 > *   }
115   *
116 < * <p> A Phaser may be used to support a style of programming in
117 < * which a task waits for others to complete, without otherwise
118 < * needing to keep track of which tasks it is waiting for. This is
119 < * similar to the "sync" construct in Cilk and "clocks" in X10.
120 < * Special constructions based on such barriers are available using
121 < * the <tt>LinkedAsyncAction</tt> and <tt>CyclicAction</tt> classes,
122 < * but they can be useful in other contexts as well.  For a simple
123 < * (but not very useful) example, here is a variant of Fibonacci:
124 < *
125 < * <pre>
126 < * class BarrierFibonacci extends RecursiveAction {
127 < *   int argument, result;
128 < *   final Phaser parentBarrier;
129 < *   BarrierFibonacci(int n, Phaser parentBarrier) {
130 < *     this.argument = n;
131 < *     this.parentBarrier = parentBarrier;
132 < *     parentBarrier.register();
116 > *   // allow threads to start and deregister self
117 > *   phaser.arriveAndDeregister();
118 > * }}</pre>
119 > *
120 > * <p>One way to cause a set of threads to repeatedly perform actions
121 > * for a given number of iterations is to override {@code onAdvance}:
122 > *
123 > *  <pre> {@code
124 > * void startTasks(List<Runnable> tasks, final int iterations) {
125 > *   final Phaser phaser = new Phaser() {
126 > *     public boolean onAdvance(int phase, int registeredParties) {
127 > *       return phase >= iterations || registeredParties == 0;
128 > *     }
129 > *   };
130 > *   phaser.register();
131 > *   for (Runnable task : tasks) {
132 > *     phaser.register();
133 > *     new Thread() {
134 > *       public void run() {
135 > *         do {
136 > *           task.run();
137 > *           phaser.arriveAndAwaitAdvance();
138 > *         } while(!phaser.isTerminated();
139 > *       }
140 > *     }.start();
141   *   }
142 < *   protected void compute() {
143 < *     int n = argument;
144 < *     if (n &lt;= 1)
145 < *        result = n;
146 < *     else {
147 < *        Phaser childBarrier = new Phaser(1);
148 < *        BarrierFibonacci f1 = new BarrierFibonacci(n - 1, childBarrier);
149 < *        BarrierFibonacci f2 = new BarrierFibonacci(n - 2, childBarrier);
150 < *        f1.fork();
151 < *        f2.fork();
152 < *        childBarrier.arriveAndAwait();
153 < *        result = f1.result + f2.result;
142 > *   phaser.arriveAndDeregister(); // deregister self, don't wait
143 > * }}</pre>
144 > *
145 > * <p>To create a set of tasks using a tree of phasers,
146 > * you could use code of the following form, assuming a
147 > * Task class with a constructor accepting a phaser that
148 > * it registers for upon construction:
149 > *  <pre> {@code
150 > * void build(Task[] actions, int lo, int hi, Phaser b) {
151 > *   int step = (hi - lo) / TASKS_PER_PHASER;
152 > *   if (step > 1) {
153 > *     int i = lo;
154 > *     while (i < hi) {
155 > *       int r = Math.min(i + step, hi);
156 > *       build(actions, i, r, new Phaser(b));
157 > *       i = r;
158   *     }
159 < *     parentBarrier.arriveAndDeregister();
159 > *   } else {
160 > *     for (int i = lo; i < hi; ++i)
161 > *       actions[i] = new Task(b);
162 > *       // assumes new Task(b) performs b.register()
163   *   }
164   * }
165 + * // .. initially called, for n tasks via
166 + * build(new Task[n], 0, n, new Phaser());}</pre>
167 + *
168 + * The best value of {@code TASKS_PER_PHASER} depends mainly on
169 + * expected barrier synchronization rates. A value as low as four may
170 + * be appropriate for extremely small per-barrier task bodies (thus
171 + * high rates), or up to hundreds for extremely large ones.
172 + *
173   * </pre>
174   *
175   * <p><b>Implementation notes</b>: This implementation restricts the
176 < * maximum number of parties to 65535. Attempts to register
177 < * additional parties result in IllegalStateExceptions.
176 > * maximum number of parties to 65535. Attempts to register additional
177 > * parties result in {@code IllegalStateException}. However, you can and
178 > * should create tiered phasers to accommodate arbitrarily large sets
179 > * of participants.
180 > *
181 > * @since 1.7
182 > * @author Doug Lea
183   */
184   public class Phaser {
185      /*
186       * This class implements an extension of X10 "clocks".  Thanks to
187 <     * Vijay Saraswat for the idea of applying it to ForkJoinTasks,
188 <     * and to Vivek Sarkar for enhancements to extend functionality.
187 >     * Vijay Saraswat for the idea, and to Vivek Sarkar for
188 >     * enhancements to extend functionality.
189       */
190  
191      /**
# Line 133 | Line 198 | public class Phaser {
198       * * terminated -- set if barrier is terminated (1 bit)
199       *
200       * However, to efficiently maintain atomicity, these values are
201 <     * packed into a single AtomicLong. Termination uses the sign bit
202 <     * of 32 bit representation of phase, so phase is set to -1 on
203 <     * termination.
204 <     */
205 <    private final AtomicLong state;
206 <
207 <    /**
143 <     * Head of Treiber stack for waiting nonFJ threads.
201 >     * packed into a single (atomic) long. Termination uses the sign
202 >     * bit of 32 bit representation of phase, so phase is set to -1 on
203 >     * termination. Good performance relies on keeping state decoding
204 >     * and encoding simple, and keeping race windows short.
205 >     *
206 >     * Note: there are some cheats in arrive() that rely on unarrived
207 >     * count being lowest 16 bits.
208       */
209 <    private final AtomicReference<QNode> head = new AtomicReference<QNode>();
209 >    private volatile long state;
210  
211      private static final int ushortBits = 16;
212 <    private static final int ushortMask =  (1 << ushortBits) - 1;
213 <    private static final int phaseMask = 0x7fffffff;
212 >    private static final int ushortMask = 0xffff;
213 >    private static final int phaseMask  = 0x7fffffff;
214  
215      private static int unarrivedOf(long s) {
216 <        return (int)(s & ushortMask);
216 >        return (int) (s & ushortMask);
217      }
218  
219      private static int partiesOf(long s) {
220 <        return (int)(s & (ushortMask << 16)) >>> 16;
220 >        return ((int) s) >>> 16;
221      }
222  
223      private static int phaseOf(long s) {
224 <        return (int)(s >>> 32);
224 >        return (int) (s >>> 32);
225      }
226  
227      private static int arrivedOf(long s) {
# Line 165 | Line 229 | public class Phaser {
229      }
230  
231      private static long stateFor(int phase, int parties, int unarrived) {
232 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
232 >        return ((((long) phase) << 32) | (((long) parties) << 16) |
233 >                (long) unarrived);
234      }
235  
236 <    private static IllegalStateException badBounds(int parties, int unarrived) {
237 <        return new IllegalStateException("Attempt to set " + unarrived +
238 <                                         " unarrived of " + parties + " parties");
236 >    private static long trippedStateFor(int phase, int parties) {
237 >        long lp = (long) parties;
238 >        return (((long) phase) << 32) | (lp << 16) | lp;
239      }
240  
241      /**
242 <     * Creates a new Phaser without any initially registered parties,
243 <     * and initial phase number 0.
242 >     * Returns message string for bad bounds exceptions.
243 >     */
244 >    private static String badBounds(int parties, int unarrived) {
245 >        return ("Attempt to set " + unarrived +
246 >                " unarrived of " + parties + " parties");
247 >    }
248 >
249 >    /**
250 >     * The parent of this phaser, or null if none
251 >     */
252 >    private final Phaser parent;
253 >
254 >    /**
255 >     * The root of phaser tree. Equals this if not in a tree.  Used to
256 >     * support faster state push-down.
257 >     */
258 >    private final Phaser root;
259 >
260 >    // Wait queues
261 >
262 >    /**
263 >     * Heads of Treiber stacks for waiting threads. To eliminate
264 >     * contention while releasing some threads while adding others, we
265 >     * use two of them, alternating across even and odd phases.
266 >     */
267 >    private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
268 >    private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
269 >
270 >    private AtomicReference<QNode> queueFor(int phase) {
271 >        return ((phase & 1) == 0) ? evenQ : oddQ;
272 >    }
273 >
274 >    /**
275 >     * Returns current state, first resolving lagged propagation from
276 >     * root if necessary.
277 >     */
278 >    private long getReconciledState() {
279 >        return (parent == null) ? state : reconcileState();
280 >    }
281 >
282 >    /**
283 >     * Recursively resolves state.
284 >     */
285 >    private long reconcileState() {
286 >        Phaser p = parent;
287 >        long s = state;
288 >        if (p != null) {
289 >            while (unarrivedOf(s) == 0 && phaseOf(s) != phaseOf(root.state)) {
290 >                long parentState = p.getReconciledState();
291 >                int parentPhase = phaseOf(parentState);
292 >                int phase = phaseOf(s = state);
293 >                if (phase != parentPhase) {
294 >                    long next = trippedStateFor(parentPhase, partiesOf(s));
295 >                    if (casState(s, next)) {
296 >                        releaseWaiters(phase);
297 >                        s = next;
298 >                    }
299 >                }
300 >            }
301 >        }
302 >        return s;
303 >    }
304 >
305 >    /**
306 >     * Creates a new phaser without any initially registered parties,
307 >     * initial phase number 0, and no parent. Any thread using this
308 >     * phaser will need to first register for it.
309       */
310      public Phaser() {
311 <        state = new AtomicLong(stateFor(0, 0, 0));
311 >        this(null);
312      }
313  
314      /**
315 <     * Creates a new Phaser with the given numbers of registered
316 <     * unarrived parties and initial phase number 0.
317 <     * @param parties the number of parties required to trip barrier.
315 >     * Creates a new phaser with the given numbers of registered
316 >     * unarrived parties, initial phase number 0, and no parent.
317 >     *
318 >     * @param parties the number of parties required to trip barrier
319       * @throws IllegalArgumentException if parties less than zero
320 <     * or greater than the maximum number of parties supported.
320 >     * or greater than the maximum number of parties supported
321       */
322      public Phaser(int parties) {
323 +        this(null, parties);
324 +    }
325 +
326 +    /**
327 +     * Creates a new phaser with the given parent, without any
328 +     * initially registered parties. If parent is non-null this phaser
329 +     * is registered with the parent and its initial phase number is
330 +     * the same as that of parent phaser.
331 +     *
332 +     * @param parent the parent phaser
333 +     */
334 +    public Phaser(Phaser parent) {
335 +        int phase = 0;
336 +        this.parent = parent;
337 +        if (parent != null) {
338 +            this.root = parent.root;
339 +            phase = parent.register();
340 +        }
341 +        else
342 +            this.root = this;
343 +        this.state = trippedStateFor(phase, 0);
344 +    }
345 +
346 +    /**
347 +     * Creates a new phaser with the given parent and numbers of
348 +     * registered unarrived parties. If parent is non-null, this phaser
349 +     * is registered with the parent and its initial phase number is
350 +     * the same as that of parent phaser.
351 +     *
352 +     * @param parent the parent phaser
353 +     * @param parties the number of parties required to trip barrier
354 +     * @throws IllegalArgumentException if parties less than zero
355 +     * or greater than the maximum number of parties supported
356 +     */
357 +    public Phaser(Phaser parent, int parties) {
358          if (parties < 0 || parties > ushortMask)
359              throw new IllegalArgumentException("Illegal number of parties");
360 <        state = new AtomicLong(stateFor(0, parties, parties));
360 >        int phase = 0;
361 >        this.parent = parent;
362 >        if (parent != null) {
363 >            this.root = parent.root;
364 >            phase = parent.register();
365 >        }
366 >        else
367 >            this.root = this;
368 >        this.state = trippedStateFor(phase, parties);
369      }
370  
371      /**
372       * Adds a new unarrived party to this phaser.
373 <     * @return the current barrier phase number upon registration
373 >     *
374 >     * @return the arrival phase number to which this registration applied
375 >     * @throws IllegalStateException if attempting to register more
376 >     * than the maximum supported number of parties
377 >     */
378 >    public int register() {
379 >        return doRegister(1);
380 >    }
381 >
382 >    /**
383 >     * Adds the given number of new unarrived parties to this phaser.
384 >     *
385 >     * @param parties the number of parties required to trip barrier
386 >     * @return the arrival phase number to which this registration applied
387       * @throws IllegalStateException if attempting to register more
388 <     * than the maximum supported number of parties.
388 >     * than the maximum supported number of parties
389       */
390 <    public int register() { // increment both parties and unarrived
391 <        final AtomicLong state = this.state;
390 >    public int bulkRegister(int parties) {
391 >        if (parties < 0)
392 >            throw new IllegalArgumentException();
393 >        if (parties == 0)
394 >            return getPhase();
395 >        return doRegister(parties);
396 >    }
397 >
398 >    /**
399 >     * Shared code for register, bulkRegister
400 >     */
401 >    private int doRegister(int registrations) {
402 >        int phase;
403          for (;;) {
404 <            long s = state.get();
405 <            int phase = phaseOf(s);
406 <            int parties = partiesOf(s) + 1;
407 <            int unarrived = unarrivedOf(s) + 1;
404 >            long s = getReconciledState();
405 >            phase = phaseOf(s);
406 >            int unarrived = unarrivedOf(s) + registrations;
407 >            int parties = partiesOf(s) + registrations;
408 >            if (phase < 0)
409 >                break;
410              if (parties > ushortMask || unarrived > ushortMask)
411 <                throw badBounds(parties, unarrived);
412 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
413 <                return phase;
411 >                throw new IllegalStateException(badBounds(parties, unarrived));
412 >            if (phase == phaseOf(root.state) &&
413 >                casState(s, stateFor(phase, parties, unarrived)))
414 >                break;
415          }
416 +        return phase;
417      }
418  
419      /**
420       * Arrives at the barrier, but does not wait for others.  (You can
421       * in turn wait for others via {@link #awaitAdvance}).
422       *
423 <     * @return the current barrier phase number upon entry to
424 <     * this method, or a negative value if terminated;
425 <     * @throws IllegalStateException if the number of unarrived
224 <     * parties would become negative.
423 >     * @return the arrival phase number, or a negative value if terminated
424 >     * @throws IllegalStateException if not terminated and the number
425 >     * of unarrived parties would become negative
426       */
427 <    public int arrive() { // decrement unarrived. If zero, trip
428 <        final AtomicLong state = this.state;
427 >    public int arrive() {
428 >        int phase;
429          for (;;) {
430 <            long s = state.get();
431 <            int phase = phaseOf(s);
430 >            long s = state;
431 >            phase = phaseOf(s);
432 >            if (phase < 0)
433 >                break;
434              int parties = partiesOf(s);
435              int unarrived = unarrivedOf(s) - 1;
436 <            if (unarrived < 0)
437 <                throw badBounds(parties, unarrived);
438 <            if (unarrived == 0 && phase >= 0) {
236 <                trip(phase, parties);
237 <                return phase;
436 >            if (unarrived > 0) {        // Not the last arrival
437 >                if (casState(s, s - 1)) // s-1 adds one arrival
438 >                    break;
439              }
440 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
441 <                return phase;
440 >            else if (unarrived == 0) {  // the last arrival
441 >                Phaser par = parent;
442 >                if (par == null) {      // directly trip
443 >                    if (casState
444 >                        (s,
445 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
446 >                                         ((phase + 1) & phaseMask), parties))) {
447 >                        releaseWaiters(phase);
448 >                        break;
449 >                    }
450 >                }
451 >                else {                  // cascade to parent
452 >                    if (casState(s, s - 1)) { // zeroes unarrived
453 >                        par.arrive();
454 >                        reconcileState();
455 >                        break;
456 >                    }
457 >                }
458 >            }
459 >            else if (phase != phaseOf(root.state)) // or if unreconciled
460 >                reconcileState();
461 >            else
462 >                throw new IllegalStateException(badBounds(parties, unarrived));
463          }
464 +        return phase;
465      }
466  
467      /**
468 <     * Arrives at the barrier, and deregisters from it, without
469 <     * waiting for others.
468 >     * Arrives at the barrier and deregisters from it without waiting
469 >     * for others. Deregistration reduces the number of parties
470 >     * required to trip the barrier in future phases.  If this phaser
471 >     * has a parent, and deregistration causes this phaser to have
472 >     * zero parties, this phaser also arrives at and is deregistered
473 >     * from its parent.
474       *
475 <     * @return the current barrier phase number upon entry to
476 <     * this method, or a negative value if terminated;
477 <     * @throws IllegalStateException if the number of registered or
478 <     * unarrived parties would become negative.
479 <     */
480 <    public int arriveAndDeregister() { // Same as arrive, plus decrement parties
481 <        final AtomicLong state = this.state;
475 >     * @return the arrival phase number, or a negative value if terminated
476 >     * @throws IllegalStateException if not terminated and the number
477 >     * of registered or unarrived parties would become negative
478 >     */
479 >    public int arriveAndDeregister() {
480 >        // similar code to arrive, but too different to merge
481 >        Phaser par = parent;
482 >        int phase;
483          for (;;) {
484 <            long s = state.get();
485 <            int phase = phaseOf(s);
484 >            long s = state;
485 >            phase = phaseOf(s);
486 >            if (phase < 0)
487 >                break;
488              int parties = partiesOf(s) - 1;
489              int unarrived = unarrivedOf(s) - 1;
490 <            if (parties < 0 || unarrived < 0)
491 <                throw badBounds(parties, unarrived);
492 <            if (unarrived == 0 && phase >= 0) {
493 <                trip(phase, parties);
494 <                return phase;
490 >            if (parties >= 0) {
491 >                if (unarrived > 0 || (unarrived == 0 && par != null)) {
492 >                    if (casState
493 >                        (s,
494 >                         stateFor(phase, parties, unarrived))) {
495 >                        if (unarrived == 0) {
496 >                            par.arriveAndDeregister();
497 >                            reconcileState();
498 >                        }
499 >                        break;
500 >                    }
501 >                    continue;
502 >                }
503 >                if (unarrived == 0) {
504 >                    if (casState
505 >                        (s,
506 >                         trippedStateFor(onAdvance(phase, parties) ? -1 :
507 >                                         ((phase + 1) & phaseMask), parties))) {
508 >                        releaseWaiters(phase);
509 >                        break;
510 >                    }
511 >                    continue;
512 >                }
513 >                if (par != null && phase != phaseOf(root.state)) {
514 >                    reconcileState();
515 >                    continue;
516 >                }
517              }
518 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
267 <                return phase;
518 >            throw new IllegalStateException(badBounds(parties, unarrived));
519          }
520 +        return phase;
521      }
522  
523      /**
524 <     * Arrives at the barrier and awaits others. Unlike other arrival
525 <     * methods, this method returns the arrival index of the
526 <     * caller. The caller tripping the barrier returns zero, the
527 <     * previous caller 1, and so on.
528 <     * @return the arrival index
529 <     * @throws IllegalStateException if the number of unarrived
530 <     * parties would become negative.
524 >     * Arrives at the barrier and awaits others. Equivalent in effect
525 >     * to {@code awaitAdvance(arrive())}.  If you need to await with
526 >     * interruption or timeout, you can arrange this with an analogous
527 >     * construction using one of the other forms of the awaitAdvance
528 >     * method.  If instead you need to deregister upon arrival use
529 >     * {@code arriveAndDeregister}.
530 >     *
531 >     * @return the arrival phase number, or a negative number if terminated
532 >     * @throws IllegalStateException if not terminated and the number
533 >     * of unarrived parties would become negative
534       */
535      public int arriveAndAwaitAdvance() {
536 <        final AtomicLong state = this.state;
282 <        for (;;) {
283 <            long s = state.get();
284 <            int phase = phaseOf(s);
285 <            int parties = partiesOf(s);
286 <            int unarrived = unarrivedOf(s) - 1;
287 <            if (unarrived < 0)
288 <                throw badBounds(parties, unarrived);
289 <            if (unarrived == 0 && phase >= 0) {
290 <                trip(phase, parties);
291 <                return 0;
292 <            }
293 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived))) {
294 <                awaitAdvance(phase);
295 <                return unarrived;
296 <            }
297 <        }
536 >        return awaitAdvance(arrive());
537      }
538  
539      /**
540 <     * Awaits the phase of the barrier to advance from the given
541 <     * value, or returns immediately if this barrier is terminated.
542 <     * @param phase the phase on entry to this method
543 <     * @return the phase on exit from this method
540 >     * Awaits the phase of the barrier to advance from the given phase
541 >     * value, returning immediately if the current phase of the
542 >     * barrier is not equal to the given phase value or this barrier
543 >     * is terminated.
544 >     *
545 >     * @param phase an arrival phase number, or negative value if
546 >     * terminated; this argument is normally the value returned by a
547 >     * previous call to {@code arrive} or its variants
548 >     * @return the next arrival phase number, or a negative value
549 >     * if terminated or argument is negative
550       */
551      public int awaitAdvance(int phase) {
552          if (phase < 0)
553              return phase;
554 <        Thread current = Thread.currentThread();
555 <        if (current instanceof ForkJoinWorkerThread)
556 <            return helpingWait(phase);
557 <        if (untimedWait(current, phase, false))
558 <            current.interrupt();
559 <        return phaseOf(state.get());
554 >        long s = getReconciledState();
555 >        int p = phaseOf(s);
556 >        if (p != phase)
557 >            return p;
558 >        if (unarrivedOf(s) == 0 && parent != null)
559 >            parent.awaitAdvance(phase);
560 >        // Fall here even if parent waited, to reconcile and help release
561 >        return untimedWait(phase);
562      }
563  
564      /**
565 <     * Awaits the phase of the barrier to advance from the given
566 <     * value, or returns immediately if this barrier is terminated, or
567 <     * throws InterruptedException if interrupted while waiting.
568 <     * @param phase the phase on entry to this method
569 <     * @return the phase on exit from this method
565 >     * Awaits the phase of the barrier to advance from the given phase
566 >     * value, throwing {@code InterruptedException} if interrupted while
567 >     * waiting, or returning immediately if the current phase of the
568 >     * barrier is not equal to the given phase value or this barrier
569 >     * is terminated.
570 >     *
571 >     * @param phase an arrival phase number, or negative value if
572 >     * terminated; this argument is normally the value returned by a
573 >     * previous call to {@code arrive} or its variants
574 >     * @return the next arrival phase number, or a negative value
575 >     * if terminated or argument is negative
576       * @throws InterruptedException if thread interrupted while waiting
577       */
578 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
578 >    public int awaitAdvanceInterruptibly(int phase)
579 >        throws InterruptedException {
580          if (phase < 0)
581              return phase;
582 <        Thread current = Thread.currentThread();
583 <        if (current instanceof ForkJoinWorkerThread)
584 <            return helpingWait(phase);
585 <        else if (Thread.interrupted() || untimedWait(current, phase, true))
586 <            throw new InterruptedException();
587 <        else
588 <            return phaseOf(state.get());
582 >        long s = getReconciledState();
583 >        int p = phaseOf(s);
584 >        if (p != phase)
585 >            return p;
586 >        if (unarrivedOf(s) == 0 && parent != null)
587 >            parent.awaitAdvanceInterruptibly(phase);
588 >        return interruptibleWait(phase);
589      }
590  
591      /**
592 <     * Awaits the phase of the barrier to advance from the given value
593 <     * or the given timeout elapses, or returns immediately if this
594 <     * barrier is terminated.
595 <     * @param phase the phase on entry to this method
596 <     * @return the phase on exit from this method
592 >     * Awaits the phase of the barrier to advance from the given phase
593 >     * value or the given timeout to elapse, throwing
594 >     * {@code InterruptedException} if interrupted while waiting, or
595 >     * returning immediately if the current phase of the barrier is not
596 >     * equal to the given phase value or this barrier is terminated.
597 >     *
598 >     * @param phase an arrival phase number, or negative value if
599 >     * terminated; this argument is normally the value returned by a
600 >     * previous call to {@code arrive} or its variants
601 >     * @param timeout how long to wait before giving up, in units of
602 >     *        {@code unit}
603 >     * @param unit a {@code TimeUnit} determining how to interpret the
604 >     *        {@code timeout} parameter
605 >     * @return the next arrival phase number, or a negative value
606 >     * if terminated or argument is negative
607       * @throws InterruptedException if thread interrupted while waiting
608       * @throws TimeoutException if timed out while waiting
609       */
610 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
610 >    public int awaitAdvanceInterruptibly(int phase,
611 >                                         long timeout, TimeUnit unit)
612          throws InterruptedException, TimeoutException {
613          if (phase < 0)
614              return phase;
615 <        long nanos = unit.toNanos(timeout);
616 <        Thread current = Thread.currentThread();
617 <        if (current instanceof ForkJoinWorkerThread)
618 <            return timedHelpingWait(phase, nanos);
619 <        timedWait(current, phase, nanos);
620 <        return phaseOf(state.get());
615 >        long s = getReconciledState();
616 >        int p = phaseOf(s);
617 >        if (p != phase)
618 >            return p;
619 >        if (unarrivedOf(s) == 0 && parent != null)
620 >            parent.awaitAdvanceInterruptibly(phase, timeout, unit);
621 >        return timedWait(phase, unit.toNanos(timeout));
622      }
623  
624      /**
625       * Forces this barrier to enter termination state. Counts of
626 <     * arrived and registered parties are unaffected. This method may
627 <     * be useful for coordinating recovery after one or more tasks
628 <     * encounter unexpected exceptions.
626 >     * arrived and registered parties are unaffected. If this phaser
627 >     * has a parent, it too is terminated. This method may be useful
628 >     * for coordinating recovery after one or more tasks encounter
629 >     * unexpected exceptions.
630       */
631      public void forceTermination() {
365        final AtomicLong state = this.state;
632          for (;;) {
633 <            long s = state.get();
633 >            long s = getReconciledState();
634              int phase = phaseOf(s);
635              int parties = partiesOf(s);
636              int unarrived = unarrivedOf(s);
637              if (phase < 0 ||
638 <                state.compareAndSet(s, stateFor(-1, parties, unarrived))) {
639 <                if (head.get() != null)
640 <                    releaseWaiters(-1);
638 >                casState(s, stateFor(-1, parties, unarrived))) {
639 >                releaseWaiters(0);
640 >                releaseWaiters(1);
641 >                if (parent != null)
642 >                    parent.forceTermination();
643                  return;
644              }
645          }
646      }
647  
648      /**
381     * Resets the barrier with the given numbers of registered unarrived
382     * parties and phase number 0. This method allows repeated reuse
383     * of this barrier, but only if it is somehow known not to be in
384     * use for other purposes.
385     * @param parties the number of parties required to trip barrier.
386     * @throws IllegalArgumentException if parties less than zero
387     * or greater than the maximum number of parties supported.
388     */
389    public void reset(int parties) {
390        if (parties < 0 || parties > ushortMask)
391            throw new IllegalArgumentException("Illegal number of parties");
392        state.set(stateFor(0, parties, parties));
393        if (head.get() != null)
394            releaseWaiters(0);
395    }
396
397    /**
649       * Returns the current phase number. The maximum phase number is
650 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
650 >     * {@code Integer.MAX_VALUE}, after which it restarts at
651       * zero. Upon termination, the phase number is negative.
652 +     *
653       * @return the phase number, or a negative value if terminated
654       */
655 <    public int getPhase() {
656 <        return phaseOf(state.get());
655 >    public final int getPhase() {
656 >        return phaseOf(getReconciledState());
657      }
658  
659      /**
660       * Returns the number of parties registered at this barrier.
661 +     *
662       * @return the number of parties
663       */
664      public int getRegisteredParties() {
665 <        return partiesOf(state.get());
665 >        return partiesOf(state);
666      }
667  
668      /**
669       * Returns the number of parties that have arrived at the current
670       * phase of this barrier.
671 +     *
672       * @return the number of arrived parties
673       */
674      public int getArrivedParties() {
675 <        return arrivedOf(state.get());
675 >        return arrivedOf(state);
676      }
677  
678      /**
679       * Returns the number of registered parties that have not yet
680       * arrived at the current phase of this barrier.
681 +     *
682       * @return the number of unarrived parties
683       */
684      public int getUnarrivedParties() {
685 <        return unarrivedOf(state.get());
685 >        return unarrivedOf(state);
686 >    }
687 >
688 >    /**
689 >     * Returns the parent of this phaser, or {@code null} if none.
690 >     *
691 >     * @return the parent of this phaser, or {@code null} if none
692 >     */
693 >    public Phaser getParent() {
694 >        return parent;
695 >    }
696 >
697 >    /**
698 >     * Returns the root ancestor of this phaser, which is the same as
699 >     * this phaser if it has no parent.
700 >     *
701 >     * @return the root ancestor of this phaser
702 >     */
703 >    public Phaser getRoot() {
704 >        return root;
705      }
706  
707      /**
708 <     * Returns true if this barrier has been terminated.
709 <     * @return true if this barrier has been terminated
708 >     * Returns {@code true} if this barrier has been terminated.
709 >     *
710 >     * @return {@code true} if this barrier has been terminated
711       */
712      public boolean isTerminated() {
713 <        return phaseOf(state.get()) < 0;
713 >        return getPhase() < 0;
714      }
715  
716      /**
717       * Overridable method to perform an action upon phase advance, and
718       * to control termination. This method is invoked whenever the
719       * barrier is tripped (and thus all other waiting parties are
720 <     * dormant). If it returns true, then, rather than advance the
721 <     * phase number, this barrier will be set to a final termination
722 <     * state, and subsequent calls to <tt>isTerminated</tt> will
723 <     * return true.
720 >     * dormant). If it returns {@code true}, then, rather than advance
721 >     * the phase number, this barrier will be set to a final
722 >     * termination state, and subsequent calls to {@link #isTerminated}
723 >     * will return true.
724       *
725 <     * <p> The default version returns true when the number of
725 >     * <p>The default version returns {@code true} when the number of
726       * registered parties is zero. Normally, overrides that arrange
727       * termination for other reasons should also preserve this
728       * property.
729       *
730 +     * <p>You may override this method to perform an action with side
731 +     * effects visible to participating tasks, but it is in general
732 +     * only sensible to do so in designs where all parties register
733 +     * before any arrive, and all {@link #awaitAdvance} at each phase.
734 +     * Otherwise, you cannot ensure lack of interference from other
735 +     * parties during the invocation of this method.
736 +     *
737       * @param phase the phase number on entering the barrier
738 <     * @param registeredParties the current number of registered
739 <     * parties.
458 <     * @return true if this barrier should terminate
738 >     * @param registeredParties the current number of registered parties
739 >     * @return {@code true} if this barrier should terminate
740       */
741      protected boolean onAdvance(int phase, int registeredParties) {
742          return registeredParties <= 0;
743      }
744  
745      /**
746 <     * Returns a string identifying this barrier, as well as its
746 >     * Returns a string identifying this phaser, as well as its
747       * state.  The state, in brackets, includes the String {@code
748 <     * "phase ="} followed by the phase number, {@code "parties ="}
748 >     * "phase = "} followed by the phase number, {@code "parties = "}
749       * followed by the number of registered parties, and {@code
750 <     * "arrived ="} followed by the number of arrived parties
750 >     * "arrived = "} followed by the number of arrived parties.
751       *
752       * @return a string identifying this barrier, as well as its state
753       */
754      public String toString() {
755 <        long s = state.get();
756 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
755 >        long s = getReconciledState();
756 >        return super.toString() +
757 >            "[phase = " + phaseOf(s) +
758 >            " parties = " + partiesOf(s) +
759 >            " arrived = " + arrivedOf(s) + "]";
760      }
761  
762 <    // methods for tripping and waiting
762 >    // methods for waiting
763  
764      /**
765 <     * Advance the current phase (or terminate)
765 >     * Wait nodes for Treiber stack representing wait queue
766       */
767 <    private void trip(int phase, int parties) {
768 <        int next = onAdvance(phase, parties)? -1 : ((phase + 1) & phaseMask);
769 <        state.set(stateFor(next, parties, parties));
770 <        if (head.get() != null)
771 <            releaseWaiters(next);
772 <    }
773 <
774 <    private int helpingWait(int phase) {
775 <        final AtomicLong state = this.state;
776 <        int p;
777 <        while ((p = phaseOf(state.get())) == phase) {
778 <            ForkJoinTask<?> t = ForkJoinWorkerThread.pollTask();
779 <            if (t != null) {
780 <                if ((p = phaseOf(state.get())) == phase)
781 <                    t.exec();
782 <                else {   // push task and exit if barrier advanced
783 <                    t.fork();
784 <                    break;
785 <                }
767 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
768 >        final Phaser phaser;
769 >        final int phase;
770 >        final long startTime;
771 >        final long nanos;
772 >        final boolean timed;
773 >        final boolean interruptible;
774 >        volatile boolean wasInterrupted = false;
775 >        volatile Thread thread; // nulled to cancel wait
776 >        QNode next;
777 >        QNode(Phaser phaser, int phase, boolean interruptible,
778 >              boolean timed, long startTime, long nanos) {
779 >            this.phaser = phaser;
780 >            this.phase = phase;
781 >            this.timed = timed;
782 >            this.interruptible = interruptible;
783 >            this.startTime = startTime;
784 >            this.nanos = nanos;
785 >            thread = Thread.currentThread();
786 >        }
787 >        public boolean isReleasable() {
788 >            return (thread == null ||
789 >                    phaser.getPhase() != phase ||
790 >                    (interruptible && wasInterrupted) ||
791 >                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
792 >        }
793 >        public boolean block() {
794 >            if (Thread.interrupted()) {
795 >                wasInterrupted = true;
796 >                if (interruptible)
797 >                    return true;
798 >            }
799 >            if (!timed)
800 >                LockSupport.park(this);
801 >            else {
802 >                long waitTime = nanos - (System.nanoTime() - startTime);
803 >                if (waitTime <= 0)
804 >                    return true;
805 >                LockSupport.parkNanos(this, waitTime);
806              }
807 +            return isReleasable();
808          }
809 <        return p;
810 <    }
506 <
507 <    private int timedHelpingWait(int phase, long nanos) throws TimeoutException {
508 <        final AtomicLong state = this.state;
509 <        long lastTime = System.nanoTime();
510 <        int p;
511 <        while ((p = phaseOf(state.get())) == phase) {
512 <            long now = System.nanoTime();
513 <            nanos -= now - lastTime;
514 <            lastTime = now;
515 <            if (nanos <= 0) {
516 <                if ((p = phaseOf(state.get())) == phase)
517 <                    throw new TimeoutException();
518 <                else
519 <                    break;
520 <            }
521 <            ForkJoinTask<?> t = ForkJoinWorkerThread.pollTask();
809 >        void signal() {
810 >            Thread t = thread;
811              if (t != null) {
812 <                if ((p = phaseOf(state.get())) == phase)
813 <                    t.exec();
814 <                else {   // push task and exit if barrier advanced
815 <                    t.fork();
816 <                    break;
812 >                thread = null;
813 >                LockSupport.unpark(t);
814 >            }
815 >        }
816 >        boolean doWait() {
817 >            if (thread != null) {
818 >                try {
819 >                    ForkJoinPool.managedBlock(this, false);
820 >                } catch (InterruptedException ie) {
821                  }
822              }
823 +            return wasInterrupted;
824          }
825 <        return p;
825 >
826      }
827  
828      /**
829 <     * Wait nodes for Treiber stack representing wait queue for non-FJ
536 <     * tasks. The waiting scheme is an adaptation of the one used in
537 <     * forkjoin.PoolBarrier.
829 >     * Removes and signals waiting threads from wait queue.
830       */
831 <    static final class QNode {
832 <        QNode next;
833 <        volatile Thread thread; // nulled to cancel wait
834 <        final int phase;
835 <        QNode(Thread t, int c) {
836 <            thread = t;
545 <            phase = c;
546 <        }
547 <    }
548 <
549 <    private void releaseWaiters(int currentPhase) {
550 <        final AtomicReference<QNode> head = this.head;
551 <        QNode p;
552 <        while ((p = head.get()) != null && p.phase != currentPhase) {
553 <            if (head.compareAndSet(p, null)) {
554 <                do {
555 <                    Thread t = p.thread;
556 <                    if (t != null) {
557 <                        p.thread = null;
558 <                        LockSupport.unpark(t);
559 <                    }
560 <                } while ((p = p.next) != null);
561 <            }
831 >    private void releaseWaiters(int phase) {
832 >        AtomicReference<QNode> head = queueFor(phase);
833 >        QNode q;
834 >        while ((q = head.get()) != null) {
835 >            if (head.compareAndSet(q, q.next))
836 >                q.signal();
837          }
838      }
839  
565    /** The number of CPUs, for spin control */
566    static final int NCPUS = Runtime.getRuntime().availableProcessors();
567
568    /**
569     * The number of times to spin before blocking in timed waits.
570     * The value is empirically derived.
571     */
572    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
573
840      /**
841 <     * The number of times to spin before blocking in untimed waits.
842 <     * This is greater than timed value because untimed waits spin
843 <     * faster since they don't need to check times on each spin.
841 >     * Tries to enqueue given node in the appropriate wait queue.
842 >     *
843 >     * @return true if successful
844       */
845 <    static final int maxUntimedSpins = maxTimedSpins * 32;
845 >    private boolean tryEnqueue(QNode node) {
846 >        AtomicReference<QNode> head = queueFor(node.phase);
847 >        return head.compareAndSet(node.next = head.get(), node);
848 >    }
849  
850      /**
851 <     * The number of nanoseconds for which it is faster to spin
852 <     * rather than to use timed park. A rough estimate suffices.
851 >     * Enqueues node and waits unless aborted or signalled.
852 >     *
853 >     * @return current phase
854       */
855 <    static final long spinForTimeoutThreshold = 1000L;
855 >    private int untimedWait(int phase) {
856 >        QNode node = null;
857 >        boolean queued = false;
858 >        boolean interrupted = false;
859 >        int p;
860 >        while ((p = getPhase()) == phase) {
861 >            if (Thread.interrupted())
862 >                interrupted = true;
863 >            else if (node == null)
864 >                node = new QNode(this, phase, false, false, 0, 0);
865 >            else if (!queued)
866 >                queued = tryEnqueue(node);
867 >            else
868 >                interrupted = node.doWait();
869 >        }
870 >        if (node != null)
871 >            node.thread = null;
872 >        releaseWaiters(phase);
873 >        if (interrupted)
874 >            Thread.currentThread().interrupt();
875 >        return p;
876 >    }
877  
878      /**
879 <     * Enqueues node and waits unless aborted or signalled.
879 >     * Interruptible version
880 >     * @return current phase
881       */
882 <    private boolean untimedWait(Thread thread, int currentPhase,
591 <                               boolean abortOnInterrupt) {
592 <        final AtomicReference<QNode> head = this.head;
593 <        final AtomicLong state = this.state;
594 <        boolean wasInterrupted = false;
882 >    private int interruptibleWait(int phase) throws InterruptedException {
883          QNode node = null;
884          boolean queued = false;
885 <        int spins = maxUntimedSpins;
886 <        while (phaseOf(state.get()) == currentPhase) {
887 <            QNode h;
888 <            if (node != null && queued) {
889 <                if (node.thread != null) {
890 <                    LockSupport.park();
891 <                    if (Thread.interrupted()) {
892 <                        wasInterrupted = true;
893 <                        if (abortOnInterrupt)
606 <                            break;
607 <                    }
608 <                }
609 <            }
610 <            else if ((h = head.get()) != null && h.phase != currentPhase) {
611 <                if (phaseOf(state.get()) == currentPhase) { // must recheck
612 <                    if (head.compareAndSet(h, h.next)) {
613 <                        Thread t = h.thread; // help clear out old waiters
614 <                        if (t != null) {
615 <                            h.thread = null;
616 <                            LockSupport.unpark(t);
617 <                        }
618 <                    }
619 <                }
620 <                else
621 <                    break;
622 <            }
623 <            else if (node != null)
624 <                queued = head.compareAndSet(node.next = h, node);
625 <            else if (spins <= 0)
626 <                node = new QNode(thread, currentPhase);
885 >        boolean interrupted = false;
886 >        int p;
887 >        while ((p = getPhase()) == phase && !interrupted) {
888 >            if (Thread.interrupted())
889 >                interrupted = true;
890 >            else if (node == null)
891 >                node = new QNode(this, phase, true, false, 0, 0);
892 >            else if (!queued)
893 >                queued = tryEnqueue(node);
894              else
895 <                --spins;
895 >                interrupted = node.doWait();
896          }
897          if (node != null)
898              node.thread = null;
899 <        return wasInterrupted;
899 >        if (p != phase || (p = getPhase()) != phase)
900 >            releaseWaiters(phase);
901 >        if (interrupted)
902 >            throw new InterruptedException();
903 >        return p;
904      }
905  
906      /**
907 <     * Messier timeout version
907 >     * Timeout version.
908 >     * @return current phase
909       */
910 <    private void timedWait(Thread thread, int currentPhase, long nanos)
910 >    private int timedWait(int phase, long nanos)
911          throws InterruptedException, TimeoutException {
912 <        final AtomicReference<QNode> head = this.head;
641 <        final AtomicLong state = this.state;
642 <        long lastTime = System.nanoTime();
912 >        long startTime = System.nanoTime();
913          QNode node = null;
914          boolean queued = false;
915 <        int spins = maxTimedSpins;
916 <        while (phaseOf(state.get()) == currentPhase) {
917 <            QNode h;
918 <            long now = System.nanoTime();
919 <            nanos -= now - lastTime;
920 <            lastTime = now;
921 <            if (nanos <= 0) {
922 <                if (node != null)
923 <                    node.thread = null;
924 <                if (phaseOf(state.get()) == currentPhase)
925 <                    throw new TimeoutException();
656 <                else
657 <                    break;
658 <            }
659 <            else if (node != null && queued) {
660 <                if (node.thread != null &&
661 <                    nanos > spinForTimeoutThreshold) {
662 <                    //                LockSupport.parkNanos(this, nanos);
663 <                    LockSupport.parkNanos(nanos);
664 <                    if (Thread.interrupted()) {
665 <                        node.thread = null;
666 <                        throw new InterruptedException();
667 <                    }
668 <                }
669 <            }
670 <            else if ((h = head.get()) != null && h.phase != currentPhase) {
671 <                if (phaseOf(state.get()) == currentPhase) { // must recheck
672 <                    if (head.compareAndSet(h, h.next)) {
673 <                        Thread t = h.thread; // help clear out old waiters
674 <                        if (t != null) {
675 <                            h.thread = null;
676 <                            LockSupport.unpark(t);
677 <                        }
678 <                    }
679 <                }
680 <                else
681 <                    break;
682 <            }
683 <            else if (node != null)
684 <                queued = head.compareAndSet(node.next = h, node);
685 <            else if (spins <= 0)
686 <                node = new QNode(thread, currentPhase);
915 >        boolean interrupted = false;
916 >        int p;
917 >        while ((p = getPhase()) == phase && !interrupted) {
918 >            if (Thread.interrupted())
919 >                interrupted = true;
920 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
921 >                break;
922 >            else if (node == null)
923 >                node = new QNode(this, phase, true, true, startTime, nanos);
924 >            else if (!queued)
925 >                queued = tryEnqueue(node);
926              else
927 <                --spins;
927 >                interrupted = node.doWait();
928          }
929          if (node != null)
930              node.thread = null;
931 +        if (p != phase || (p = getPhase()) != phase)
932 +            releaseWaiters(phase);
933 +        if (interrupted)
934 +            throw new InterruptedException();
935 +        if (p == phase)
936 +            throw new TimeoutException();
937 +        return p;
938      }
939  
940 +    // Unsafe mechanics
941 +
942 +    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
943 +    private static final long stateOffset =
944 +        objectFieldOffset("state", Phaser.class);
945 +
946 +    private final boolean casState(long cmp, long val) {
947 +        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
948 +    }
949 +
950 +    private static long objectFieldOffset(String field, Class<?> klazz) {
951 +        try {
952 +            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
953 +        } catch (NoSuchFieldException e) {
954 +            // Convert Exception to corresponding Error
955 +            NoSuchFieldError error = new NoSuchFieldError(field);
956 +            error.initCause(e);
957 +            throw error;
958 +        }
959 +    }
960 +
961 +    /**
962 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
963 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
964 +     * into a jdk.
965 +     *
966 +     * @return a sun.misc.Unsafe
967 +     */
968 +    private static sun.misc.Unsafe getUnsafe() {
969 +        try {
970 +            return sun.misc.Unsafe.getUnsafe();
971 +        } catch (SecurityException se) {
972 +            try {
973 +                return java.security.AccessController.doPrivileged
974 +                    (new java.security
975 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
976 +                        public sun.misc.Unsafe run() throws Exception {
977 +                            java.lang.reflect.Field f = sun.misc
978 +                                .Unsafe.class.getDeclaredField("theUnsafe");
979 +                            f.setAccessible(true);
980 +                            return (sun.misc.Unsafe) f.get(null);
981 +                        }});
982 +            } catch (java.security.PrivilegedActionException e) {
983 +                throw new RuntimeException("Could not initialize intrinsics",
984 +                                           e.getCause());
985 +            }
986 +        }
987 +    }
988   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines