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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines