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.2 by jsr166, Fri Jul 25 18:10:41 2008 UTC vs.
Revision 1.19 by jsr166, Fri Jul 24 23:47:01 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines