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.15 by jsr166, Tue Jul 21 18:11:44 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   public class Phaser {
180      /*
181       * This class implements an extension of X10 "clocks".  Thanks to
182 <     * Vijay Saraswat for the idea of applying it to ForkJoinTasks,
183 <     * and to Vivek Sarkar for enhancements to extend functionality.
182 >     * Vijay Saraswat for the idea, and to Vivek Sarkar for
183 >     * enhancements to extend functionality.
184       */
185  
186      /**
187       * Barrier state representation. Conceptually, a barrier contains
188       * four values:
189 <     *
189 >     *
190       * * parties -- the number of parties to wait (16 bits)
191       * * unarrived -- the number of parties yet to hit barrier (16 bits)
192       * * phase -- the generation of the barrier (31 bits)
193       * * terminated -- set if barrier is terminated (1 bit)
194       *
195       * However, to efficiently maintain atomicity, these values are
196 <     * packed into a single AtomicLong. Termination uses the sign bit
197 <     * of 32 bit representation of phase, so phase is set to -1 on
198 <     * termination.
199 <     */
200 <    private final AtomicLong state;
201 <
202 <    /**
143 <     * Head of Treiber stack for waiting nonFJ threads.
196 >     * packed into a single (atomic) long. Termination uses the sign
197 >     * bit of 32 bit representation of phase, so phase is set to -1 on
198 >     * termination. Good performance relies on keeping state decoding
199 >     * and encoding simple, and keeping race windows short.
200 >     *
201 >     * Note: there are some cheats in arrive() that rely on unarrived
202 >     * count being lowest 16 bits.
203       */
204 <    private final AtomicReference<QNode> head = new AtomicReference<QNode>();
204 >    private volatile long state;
205  
206      private static final int ushortBits = 16;
207 <    private static final int ushortMask =  (1 << ushortBits) - 1;
208 <    private static final int phaseMask = 0x7fffffff;
207 >    private static final int ushortMask = 0xffff;
208 >    private static final int phaseMask  = 0x7fffffff;
209  
210      private static int unarrivedOf(long s) {
211          return (int)(s & ushortMask);
212      }
213  
214      private static int partiesOf(long s) {
215 <        return (int)(s & (ushortMask << 16)) >>> 16;
215 >        return ((int)s) >>> 16;
216      }
217  
218      private static int phaseOf(long s) {
# Line 165 | Line 224 | public class Phaser {
224      }
225  
226      private static long stateFor(int phase, int parties, int unarrived) {
227 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
227 >        return ((((long)phase) << 32) | (((long)parties) << 16) |
228 >                (long)unarrived);
229      }
230  
231 <    private static IllegalStateException badBounds(int parties, int unarrived) {
232 <        return new IllegalStateException("Attempt to set " + unarrived +
233 <                                         " unarrived of " + parties + " parties");
231 >    private static long trippedStateFor(int phase, int parties) {
232 >        long lp = (long)parties;
233 >        return (((long)phase) << 32) | (lp << 16) | lp;
234 >    }
235 >
236 >    /**
237 >     * Returns message string for bad bounds exceptions.
238 >     */
239 >    private static String badBounds(int parties, int unarrived) {
240 >        return ("Attempt to set " + unarrived +
241 >                " unarrived of " + parties + " parties");
242 >    }
243 >
244 >    /**
245 >     * The parent of this phaser, or null if none
246 >     */
247 >    private final Phaser parent;
248 >
249 >    /**
250 >     * The root of Phaser tree. Equals this if not in a tree.  Used to
251 >     * support faster state push-down.
252 >     */
253 >    private final Phaser root;
254 >
255 >    // Wait queues
256 >
257 >    /**
258 >     * Heads of Treiber stacks for waiting threads. To eliminate
259 >     * contention while releasing some threads while adding others, we
260 >     * use two of them, alternating across even and odd phases.
261 >     */
262 >    private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
263 >    private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
264 >
265 >    private AtomicReference<QNode> queueFor(int phase) {
266 >        return (phase & 1) == 0? evenQ : oddQ;
267 >    }
268 >
269 >    /**
270 >     * Returns current state, first resolving lagged propagation from
271 >     * root if necessary.
272 >     */
273 >    private long getReconciledState() {
274 >        return parent == null? state : reconcileState();
275 >    }
276 >
277 >    /**
278 >     * Recursively resolves state.
279 >     */
280 >    private long reconcileState() {
281 >        Phaser p = parent;
282 >        long s = state;
283 >        if (p != null) {
284 >            while (unarrivedOf(s) == 0 && phaseOf(s) != phaseOf(root.state)) {
285 >                long parentState = p.getReconciledState();
286 >                int parentPhase = phaseOf(parentState);
287 >                int phase = phaseOf(s = state);
288 >                if (phase != parentPhase) {
289 >                    long next = trippedStateFor(parentPhase, partiesOf(s));
290 >                    if (casState(s, next)) {
291 >                        releaseWaiters(phase);
292 >                        s = next;
293 >                    }
294 >                }
295 >            }
296 >        }
297 >        return s;
298      }
299  
300      /**
301       * Creates a new Phaser without any initially registered parties,
302 <     * and initial phase number 0.
302 >     * initial phase number 0, and no parent. Any thread using this
303 >     * Phaser will need to first register for it.
304       */
305      public Phaser() {
306 <        state = new AtomicLong(stateFor(0, 0, 0));
306 >        this(null);
307      }
308  
309      /**
310       * Creates a new Phaser with the given numbers of registered
311 <     * unarrived parties and initial phase number 0.
312 <     * @param parties the number of parties required to trip barrier.
311 >     * unarrived parties, initial phase number 0, and no parent.
312 >     *
313 >     * @param parties the number of parties required to trip barrier
314       * @throws IllegalArgumentException if parties less than zero
315 <     * or greater than the maximum number of parties supported.
315 >     * or greater than the maximum number of parties supported
316       */
317      public Phaser(int parties) {
318 +        this(null, parties);
319 +    }
320 +
321 +    /**
322 +     * Creates a new Phaser with the given parent, without any
323 +     * initially registered parties. If parent is non-null this phaser
324 +     * is registered with the parent and its initial phase number is
325 +     * the same as that of parent phaser.
326 +     *
327 +     * @param parent the parent phaser
328 +     */
329 +    public Phaser(Phaser parent) {
330 +        int phase = 0;
331 +        this.parent = parent;
332 +        if (parent != null) {
333 +            this.root = parent.root;
334 +            phase = parent.register();
335 +        }
336 +        else
337 +            this.root = this;
338 +        this.state = trippedStateFor(phase, 0);
339 +    }
340 +
341 +    /**
342 +     * Creates a new Phaser with the given parent and numbers of
343 +     * registered unarrived parties. If parent is non-null, this phaser
344 +     * is registered with the parent and its initial phase number is
345 +     * the same as that of parent phaser.
346 +     *
347 +     * @param parent the parent phaser
348 +     * @param parties the number of parties required to trip barrier
349 +     * @throws IllegalArgumentException if parties less than zero
350 +     * or greater than the maximum number of parties supported
351 +     */
352 +    public Phaser(Phaser parent, int parties) {
353          if (parties < 0 || parties > ushortMask)
354              throw new IllegalArgumentException("Illegal number of parties");
355 <        state = new AtomicLong(stateFor(0, parties, parties));
355 >        int phase = 0;
356 >        this.parent = parent;
357 >        if (parent != null) {
358 >            this.root = parent.root;
359 >            phase = parent.register();
360 >        }
361 >        else
362 >            this.root = this;
363 >        this.state = trippedStateFor(phase, parties);
364      }
365  
366      /**
367       * Adds a new unarrived party to this phaser.
368 +     *
369 +     * @return the current barrier phase number upon registration
370 +     * @throws IllegalStateException if attempting to register more
371 +     * than the maximum supported number of parties
372 +     */
373 +    public int register() {
374 +        return doRegister(1);
375 +    }
376 +
377 +    /**
378 +     * Adds the given number of new unarrived parties to this phaser.
379 +     *
380 +     * @param parties the number of parties required to trip barrier
381       * @return the current barrier phase number upon registration
382       * @throws IllegalStateException if attempting to register more
383 <     * than the maximum supported number of parties.
383 >     * than the maximum supported number of parties
384       */
385 <    public int register() { // increment both parties and unarrived
386 <        final AtomicLong state = this.state;
385 >    public int bulkRegister(int parties) {
386 >        if (parties < 0)
387 >            throw new IllegalArgumentException();
388 >        if (parties == 0)
389 >            return getPhase();
390 >        return doRegister(parties);
391 >    }
392 >
393 >    /**
394 >     * Shared code for register, bulkRegister
395 >     */
396 >    private int doRegister(int registrations) {
397 >        int phase;
398          for (;;) {
399 <            long s = state.get();
400 <            int phase = phaseOf(s);
401 <            int parties = partiesOf(s) + 1;
402 <            int unarrived = unarrivedOf(s) + 1;
399 >            long s = getReconciledState();
400 >            phase = phaseOf(s);
401 >            int unarrived = unarrivedOf(s) + registrations;
402 >            int parties = partiesOf(s) + registrations;
403 >            if (phase < 0)
404 >                break;
405              if (parties > ushortMask || unarrived > ushortMask)
406 <                throw badBounds(parties, unarrived);
407 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
408 <                return phase;
406 >                throw new IllegalStateException(badBounds(parties, unarrived));
407 >            if (phase == phaseOf(root.state) &&
408 >                casState(s, stateFor(phase, parties, unarrived)))
409 >                break;
410          }
411 +        return phase;
412      }
413  
414      /**
415       * Arrives at the barrier, but does not wait for others.  (You can
416       * in turn wait for others via {@link #awaitAdvance}).
417       *
418 <     * @return the current barrier phase number upon entry to
419 <     * this method, or a negative value if terminated;
420 <     * @throws IllegalStateException if the number of unarrived
421 <     * parties would become negative.
418 >     * @return the barrier phase number upon entry to this method, or a
419 >     * negative value if terminated
420 >     * @throws IllegalStateException if not terminated and the number
421 >     * of unarrived parties would become negative
422       */
423 <    public int arrive() { // decrement unarrived. If zero, trip
424 <        final AtomicLong state = this.state;
423 >    public int arrive() {
424 >        int phase;
425          for (;;) {
426 <            long s = state.get();
427 <            int phase = phaseOf(s);
426 >            long s = state;
427 >            phase = phaseOf(s);
428 >            if (phase < 0)
429 >                break;
430              int parties = partiesOf(s);
431              int unarrived = unarrivedOf(s) - 1;
432 <            if (unarrived < 0)
433 <                throw badBounds(parties, unarrived);
434 <            if (unarrived == 0 && phase >= 0) {
236 <                trip(phase, parties);
237 <                return phase;
432 >            if (unarrived > 0) {        // Not the last arrival
433 >                if (casState(s, s - 1)) // s-1 adds one arrival
434 >                    break;
435              }
436 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
437 <                return phase;
436 >            else if (unarrived == 0) {  // the last arrival
437 >                Phaser par = parent;
438 >                if (par == null) {      // directly trip
439 >                    if (casState
440 >                        (s,
441 >                         trippedStateFor(onAdvance(phase, parties)? -1 :
442 >                                         ((phase + 1) & phaseMask), parties))) {
443 >                        releaseWaiters(phase);
444 >                        break;
445 >                    }
446 >                }
447 >                else {                  // cascade to parent
448 >                    if (casState(s, s - 1)) { // zeroes unarrived
449 >                        par.arrive();
450 >                        reconcileState();
451 >                        break;
452 >                    }
453 >                }
454 >            }
455 >            else if (phase != phaseOf(root.state)) // or if unreconciled
456 >                reconcileState();
457 >            else
458 >                throw new IllegalStateException(badBounds(parties, unarrived));
459          }
460 +        return phase;
461      }
462  
463      /**
464       * Arrives at the barrier, and deregisters from it, without
465 <     * waiting for others.
465 >     * waiting for others. Deregistration reduces number of parties
466 >     * required to trip the barrier in future phases.  If this phaser
467 >     * has a parent, and deregistration causes this phaser to have
468 >     * zero parties, this phaser is also deregistered from its parent.
469       *
470       * @return the current barrier phase number upon entry to
471 <     * this method, or a negative value if terminated;
472 <     * @throws IllegalStateException if the number of registered or
473 <     * unarrived parties would become negative.
474 <     */
475 <    public int arriveAndDeregister() { // Same as arrive, plus decrement parties
476 <        final AtomicLong state = this.state;
471 >     * this method, or a negative value if terminated
472 >     * @throws IllegalStateException if not terminated and the number
473 >     * of registered or unarrived parties would become negative
474 >     */
475 >    public int arriveAndDeregister() {
476 >        // similar code to arrive, but too different to merge
477 >        Phaser par = parent;
478 >        int phase;
479          for (;;) {
480 <            long s = state.get();
481 <            int phase = phaseOf(s);
480 >            long s = state;
481 >            phase = phaseOf(s);
482 >            if (phase < 0)
483 >                break;
484              int parties = partiesOf(s) - 1;
485              int unarrived = unarrivedOf(s) - 1;
486 <            if (parties < 0 || unarrived < 0)
487 <                throw badBounds(parties, unarrived);
488 <            if (unarrived == 0 && phase >= 0) {
489 <                trip(phase, parties);
490 <                return phase;
486 >            if (parties >= 0) {
487 >                if (unarrived > 0 || (unarrived == 0 && par != null)) {
488 >                    if (casState
489 >                        (s,
490 >                         stateFor(phase, parties, unarrived))) {
491 >                        if (unarrived == 0) {
492 >                            par.arriveAndDeregister();
493 >                            reconcileState();
494 >                        }
495 >                        break;
496 >                    }
497 >                    continue;
498 >                }
499 >                if (unarrived == 0) {
500 >                    if (casState
501 >                        (s,
502 >                         trippedStateFor(onAdvance(phase, parties)? -1 :
503 >                                         ((phase + 1) & phaseMask), parties))) {
504 >                        releaseWaiters(phase);
505 >                        break;
506 >                    }
507 >                    continue;
508 >                }
509 >                if (par != null && phase != phaseOf(root.state)) {
510 >                    reconcileState();
511 >                    continue;
512 >                }
513              }
514 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
267 <                return phase;
514 >            throw new IllegalStateException(badBounds(parties, unarrived));
515          }
516 +        return phase;
517      }
518  
519      /**
520 <     * Arrives at the barrier and awaits others. Unlike other arrival
521 <     * methods, this method returns the arrival index of the
522 <     * caller. The caller tripping the barrier returns zero, the
523 <     * previous caller 1, and so on.
524 <     * @return the arrival index
525 <     * @throws IllegalStateException if the number of unarrived
526 <     * parties would become negative.
520 >     * Arrives at the barrier and awaits others. Equivalent in effect
521 >     * to {@code awaitAdvance(arrive())}.  If you instead need to
522 >     * await with interruption of timeout, and/or deregister upon
523 >     * arrival, you can arrange them using analogous constructions.
524 >     *
525 >     * @return the phase on entry to this method
526 >     * @throws IllegalStateException if not terminated and the number
527 >     * of unarrived parties would become negative
528       */
529      public int arriveAndAwaitAdvance() {
530 <        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 <        }
530 >        return awaitAdvance(arrive());
531      }
532  
533      /**
534       * Awaits the phase of the barrier to advance from the given
535 <     * value, or returns immediately if this barrier is terminated
535 >     * value, or returns immediately if argument is negative or this
536 >     * barrier is terminated.
537 >     *
538       * @param phase the phase on entry to this method
539       * @return the phase on exit from this method
540       */
541      public int awaitAdvance(int phase) {
542          if (phase < 0)
543              return phase;
544 <        Thread current = Thread.currentThread();
545 <        if (current instanceof ForkJoinWorkerThread)
546 <            return helpingWait(phase);
547 <        if (untimedWait(current, phase, false))
548 <            current.interrupt();
549 <        return phaseOf(state.get());
544 >        long s = getReconciledState();
545 >        int p = phaseOf(s);
546 >        if (p != phase)
547 >            return p;
548 >        if (unarrivedOf(s) == 0 && parent != null)
549 >            parent.awaitAdvance(phase);
550 >        // Fall here even if parent waited, to reconcile and help release
551 >        return untimedWait(phase);
552      }
553  
554      /**
555       * Awaits the phase of the barrier to advance from the given
556 <     * value, or returns immediately if this barrier is terminated, or
557 <     * throws InterruptedException if interrupted while waiting.
556 >     * value, or returns immediately if argument is negative or this
557 >     * barrier is terminated, or throws InterruptedException if
558 >     * interrupted while waiting.
559 >     *
560       * @param phase the phase on entry to this method
561       * @return the phase on exit from this method
562       * @throws InterruptedException if thread interrupted while waiting
563       */
564 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
564 >    public int awaitAdvanceInterruptibly(int phase)
565 >        throws InterruptedException {
566          if (phase < 0)
567              return phase;
568 <        Thread current = Thread.currentThread();
569 <        if (current instanceof ForkJoinWorkerThread)
570 <            return helpingWait(phase);
571 <        else if (Thread.interrupted() || untimedWait(current, phase, true))
572 <            throw new InterruptedException();
573 <        else
574 <            return phaseOf(state.get());
568 >        long s = getReconciledState();
569 >        int p = phaseOf(s);
570 >        if (p != phase)
571 >            return p;
572 >        if (unarrivedOf(s) == 0 && parent != null)
573 >            parent.awaitAdvanceInterruptibly(phase);
574 >        return interruptibleWait(phase);
575      }
576  
577      /**
578       * Awaits the phase of the barrier to advance from the given value
579 <     * or the given timeout elapses, or returns immediately if this
580 <     * barrier is terminated
579 >     * or the given timeout elapses, or returns immediately if
580 >     * argument is negative or this barrier is terminated.
581 >     *
582       * @param phase the phase on entry to this method
583       * @return the phase on exit from this method
584       * @throws InterruptedException if thread interrupted while waiting
585       * @throws TimeoutException if timed out while waiting
586       */
587 <    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
587 >    public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
588          throws InterruptedException, TimeoutException {
589          if (phase < 0)
590              return phase;
591 <        long nanos = unit.toNanos(timeout);
592 <        Thread current = Thread.currentThread();
593 <        if (current instanceof ForkJoinWorkerThread)
594 <            return timedHelpingWait(phase, nanos);
595 <        timedWait(current, phase, nanos);
596 <        return phaseOf(state.get());
591 >        long s = getReconciledState();
592 >        int p = phaseOf(s);
593 >        if (p != phase)
594 >            return p;
595 >        if (unarrivedOf(s) == 0 && parent != null)
596 >            parent.awaitAdvanceInterruptibly(phase, timeout, unit);
597 >        return timedWait(phase, unit.toNanos(timeout));
598      }
599  
600      /**
601       * Forces this barrier to enter termination state. Counts of
602 <     * arrived and registered parties are unaffected. This method may
603 <     * be useful for coordinating recovery after one or more tasks
604 <     * encounter unexpected exceptions.
602 >     * arrived and registered parties are unaffected. If this phaser
603 >     * has a parent, it too is terminated. This method may be useful
604 >     * for coordinating recovery after one or more tasks encounter
605 >     * unexpected exceptions.
606       */
607      public void forceTermination() {
365        final AtomicLong state = this.state;
608          for (;;) {
609 <            long s = state.get();
609 >            long s = getReconciledState();
610              int phase = phaseOf(s);
611              int parties = partiesOf(s);
612              int unarrived = unarrivedOf(s);
613              if (phase < 0 ||
614 <                state.compareAndSet(s, stateFor(-1, parties, unarrived))) {
615 <                if (head.get() != null)
616 <                    releaseWaiters(-1);
614 >                casState(s, stateFor(-1, parties, unarrived))) {
615 >                releaseWaiters(0);
616 >                releaseWaiters(1);
617 >                if (parent != null)
618 >                    parent.forceTermination();
619                  return;
620              }
621          }
622      }
623  
624      /**
625 <     * Resets the barrier with the given numbers of registered unarrived
626 <     * parties and phase number 0. This method allows repeated reuse
627 <     * of this barrier, but only if it is somehow known not to be in
628 <     * use for other purposes.
629 <     * @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.
625 >     * Returns the current phase number. The maximum phase number is
626 >     * {@code Integer.MAX_VALUE}, after which it restarts at
627 >     * zero. Upon termination, the phase number is negative.
628 >     *
629 >     * @return the phase number, or a negative value if terminated
630       */
631 <    public void reset(int parties) {
632 <        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);
631 >    public final int getPhase() {
632 >        return phaseOf(getReconciledState());
633      }
634  
635      /**
636 <     * Returns the current phase number. The maximum phase number is
637 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
638 <     * zero. Upon termination, the phase number is negative.
639 <     * @return the phase number, or a negative value if terminated
636 >     * Returns {@code true} if the current phase number equals the given phase.
637 >     *
638 >     * @param phase the phase
639 >     * @return {@code true} if the current phase number equals the given phase
640       */
641 <    public int getPhase() {
642 <        return phaseOf(state.get());
641 >    public final boolean hasPhase(int phase) {
642 >        return phaseOf(getReconciledState()) == phase;
643      }
644  
645      /**
646       * Returns the number of parties registered at this barrier.
647 +     *
648       * @return the number of parties
649       */
650      public int getRegisteredParties() {
651 <        return partiesOf(state.get());
651 >        return partiesOf(state);
652      }
653  
654      /**
655       * Returns the number of parties that have arrived at the current
656       * phase of this barrier.
657 +     *
658       * @return the number of arrived parties
659       */
660      public int getArrivedParties() {
661 <        return arrivedOf(state.get());
661 >        return arrivedOf(state);
662      }
663  
664      /**
665       * Returns the number of registered parties that have not yet
666       * arrived at the current phase of this barrier.
667 +     *
668       * @return the number of unarrived parties
669       */
670      public int getUnarrivedParties() {
671 <        return unarrivedOf(state.get());
671 >        return unarrivedOf(state);
672      }
673  
674      /**
675 <     * Returns true if this barrier has been terminated
676 <     * @return true if this barrier has been terminated
675 >     * Returns the parent of this phaser, or null if none.
676 >     *
677 >     * @return the parent of this phaser, or null if none
678 >     */
679 >    public Phaser getParent() {
680 >        return parent;
681 >    }
682 >
683 >    /**
684 >     * Returns the root ancestor of this phaser, which is the same as
685 >     * this phaser if it has no parent.
686 >     *
687 >     * @return the root ancestor of this phaser
688 >     */
689 >    public Phaser getRoot() {
690 >        return root;
691 >    }
692 >
693 >    /**
694 >     * Returns {@code true} if this barrier has been terminated.
695 >     *
696 >     * @return {@code true} if this barrier has been terminated
697       */
698      public boolean isTerminated() {
699 <        return phaseOf(state.get()) < 0;
699 >        return getPhase() < 0;
700      }
701  
702      /**
# Line 444 | Line 705 | public class Phaser {
705       * barrier is tripped (and thus all other waiting parties are
706       * dormant). If it returns true, then, rather than advance the
707       * phase number, this barrier will be set to a final termination
708 <     * state, and subsequent calls to <tt>isTerminated</tt> will
708 >     * state, and subsequent calls to {@code isTerminated} will
709       * return true.
710 <     *
710 >     *
711       * <p> The default version returns true when the number of
712       * registered parties is zero. Normally, overrides that arrange
713       * termination for other reasons should also preserve this
714       * property.
715       *
716 +     * <p> You may override this method to perform an action with side
717 +     * effects visible to participating tasks, but it is in general
718 +     * only sensible to do so in designs where all parties register
719 +     * before any arrive, and all {@code awaitAdvance} at each phase.
720 +     * Otherwise, you cannot ensure lack of interference. In
721 +     * particular, this method may be invoked more than once per
722 +     * transition if other parties successfully register while the
723 +     * invocation of this method is in progress, thus postponing the
724 +     * transition until those parties also arrive, re-triggering this
725 +     * method.
726 +     *
727       * @param phase the phase number on entering the barrier
728 <     * @param registeredParties the current number of registered
729 <     * parties.
458 <     * @return true if this barrier should terminate
728 >     * @param registeredParties the current number of registered parties
729 >     * @return {@code true} if this barrier should terminate
730       */
731      protected boolean onAdvance(int phase, int registeredParties) {
732          return registeredParties <= 0;
733      }
734  
735      /**
736 <     * Returns a string identifying this barrier, as well as its
736 >     * Returns a string identifying this phaser, as well as its
737       * state.  The state, in brackets, includes the String {@code
738 <     * "phase ="} followed by the phase number, {@code "parties ="}
738 >     * "phase = "} followed by the phase number, {@code "parties = "}
739       * followed by the number of registered parties, and {@code
740 <     * "arrived ="} followed by the number of arrived parties
740 >     * "arrived = "} followed by the number of arrived parties.
741       *
742       * @return a string identifying this barrier, as well as its state
743       */
744      public String toString() {
745 <        long s = state.get();
746 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
745 >        long s = getReconciledState();
746 >        return super.toString() +
747 >            "[phase = " + phaseOf(s) +
748 >            " parties = " + partiesOf(s) +
749 >            " arrived = " + arrivedOf(s) + "]";
750      }
751  
752 <    // methods for tripping and waiting
752 >    // methods for waiting
753  
754      /**
755 <     * Advance the current phase (or terminate)
755 >     * Wait nodes for Treiber stack representing wait queue
756       */
757 <    private void trip(int phase, int parties) {
758 <        int next = onAdvance(phase, parties)? -1 : ((phase + 1) & phaseMask);
759 <        state.set(stateFor(next, parties, parties));
760 <        if (head.get() != null)
761 <            releaseWaiters(next);
762 <    }
763 <
764 <    private int helpingWait(int phase) {
765 <        final AtomicLong state = this.state;
766 <        int p;
767 <        while ((p = phaseOf(state.get())) == phase) {
768 <            ForkJoinTask<?> t = ForkJoinWorkerThread.pollTask();
769 <            if (t != null) {
770 <                if ((p = phaseOf(state.get())) == phase)
771 <                    t.exec();
772 <                else {   // push task and exit if barrier advanced
773 <                    t.fork();
774 <                    break;
775 <                }
757 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
758 >        final Phaser phaser;
759 >        final int phase;
760 >        final long startTime;
761 >        final long nanos;
762 >        final boolean timed;
763 >        final boolean interruptible;
764 >        volatile boolean wasInterrupted = false;
765 >        volatile Thread thread; // nulled to cancel wait
766 >        QNode next;
767 >        QNode(Phaser phaser, int phase, boolean interruptible,
768 >              boolean timed, long startTime, long nanos) {
769 >            this.phaser = phaser;
770 >            this.phase = phase;
771 >            this.timed = timed;
772 >            this.interruptible = interruptible;
773 >            this.startTime = startTime;
774 >            this.nanos = nanos;
775 >            thread = Thread.currentThread();
776 >        }
777 >        public boolean isReleasable() {
778 >            return (thread == null ||
779 >                    phaser.getPhase() != phase ||
780 >                    (interruptible && wasInterrupted) ||
781 >                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
782 >        }
783 >        public boolean block() {
784 >            if (Thread.interrupted()) {
785 >                wasInterrupted = true;
786 >                if (interruptible)
787 >                    return true;
788 >            }
789 >            if (!timed)
790 >                LockSupport.park(this);
791 >            else {
792 >                long waitTime = nanos - (System.nanoTime() - startTime);
793 >                if (waitTime <= 0)
794 >                    return true;
795 >                LockSupport.parkNanos(this, waitTime);
796              }
797 +            return isReleasable();
798          }
799 <        return p;
800 <    }
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();
799 >        void signal() {
800 >            Thread t = thread;
801              if (t != null) {
802 <                if ((p = phaseOf(state.get())) == phase)
803 <                    t.exec();
804 <                else {   // push task and exit if barrier advanced
805 <                    t.fork();
806 <                    break;
802 >                thread = null;
803 >                LockSupport.unpark(t);
804 >            }
805 >        }
806 >        boolean doWait() {
807 >            if (thread != null) {
808 >                try {
809 >                    ForkJoinPool.managedBlock(this, false);
810 >                } catch (InterruptedException ie) {
811                  }
812              }
813 +            return wasInterrupted;
814          }
815 <        return p;
815 >
816      }
817  
818      /**
819 <     * 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.
819 >     * Removes and signals waiting threads from wait queue.
820       */
821 <    static final class QNode {
822 <        QNode next;
823 <        volatile Thread thread; // nulled to cancel wait
824 <        final int phase;
825 <        QNode(Thread t, int c) {
826 <            thread = t;
545 <            phase = c;
821 >    private void releaseWaiters(int phase) {
822 >        AtomicReference<QNode> head = queueFor(phase);
823 >        QNode q;
824 >        while ((q = head.get()) != null) {
825 >            if (head.compareAndSet(q, q.next))
826 >                q.signal();
827          }
828      }
829  
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
830      /**
831 <     * The number of times to spin before blocking in untimed waits.
832 <     * This is greater than timed value because untimed waits spin
833 <     * faster since they don't need to check times on each spin.
831 >     * Tries to enqueue given node in the appropriate wait queue.
832 >     *
833 >     * @return true if successful
834       */
835 <    static final int maxUntimedSpins = maxTimedSpins * 32;
835 >    private boolean tryEnqueue(QNode node) {
836 >        AtomicReference<QNode> head = queueFor(node.phase);
837 >        return head.compareAndSet(node.next = head.get(), node);
838 >    }
839  
840      /**
841 <     * The number of nanoseconds for which it is faster to spin
842 <     * rather than to use timed park. A rough estimate suffices.
841 >     * Enqueues node and waits unless aborted or signalled.
842 >     *
843 >     * @return current phase
844       */
845 <    static final long spinForTimeoutThreshold = 1000L;
845 >    private int untimedWait(int phase) {
846 >        QNode node = null;
847 >        boolean queued = false;
848 >        boolean interrupted = false;
849 >        int p;
850 >        while ((p = getPhase()) == phase) {
851 >            if (Thread.interrupted())
852 >                interrupted = true;
853 >            else if (node == null)
854 >                node = new QNode(this, phase, false, false, 0, 0);
855 >            else if (!queued)
856 >                queued = tryEnqueue(node);
857 >            else
858 >                interrupted = node.doWait();
859 >        }
860 >        if (node != null)
861 >            node.thread = null;
862 >        releaseWaiters(phase);
863 >        if (interrupted)
864 >            Thread.currentThread().interrupt();
865 >        return p;
866 >    }
867  
868      /**
869 <     * Enqueues node and waits unless aborted or signalled.
869 >     * Interruptible version
870 >     * @return current phase
871       */
872 <    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;
872 >    private int interruptibleWait(int phase) throws InterruptedException {
873          QNode node = null;
874          boolean queued = false;
875 <        int spins = maxUntimedSpins;
876 <        while (phaseOf(state.get()) == currentPhase) {
877 <            QNode h;
878 <            if (node != null && queued) {
879 <                if (node.thread != null) {
880 <                    LockSupport.park();
881 <                    if (Thread.interrupted()) {
882 <                        wasInterrupted = true;
883 <                        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);
875 >        boolean interrupted = false;
876 >        int p;
877 >        while ((p = getPhase()) == phase && !interrupted) {
878 >            if (Thread.interrupted())
879 >                interrupted = true;
880 >            else if (node == null)
881 >                node = new QNode(this, phase, true, false, 0, 0);
882 >            else if (!queued)
883 >                queued = tryEnqueue(node);
884              else
885 <                --spins;
885 >                interrupted = node.doWait();
886          }
887          if (node != null)
888              node.thread = null;
889 <        return wasInterrupted;
889 >        if (p != phase || (p = getPhase()) != phase)
890 >            releaseWaiters(phase);
891 >        if (interrupted)
892 >            throw new InterruptedException();
893 >        return p;
894      }
895  
896      /**
897 <     * Messier timeout version
897 >     * Timeout version.
898 >     * @return current phase
899       */
900 <    private void timedWait(Thread thread, int currentPhase, long nanos)
900 >    private int timedWait(int phase, long nanos)
901          throws InterruptedException, TimeoutException {
902 <        final AtomicReference<QNode> head = this.head;
641 <        final AtomicLong state = this.state;
642 <        long lastTime = System.nanoTime();
902 >        long startTime = System.nanoTime();
903          QNode node = null;
904          boolean queued = false;
905 <        int spins = maxTimedSpins;
906 <        while (phaseOf(state.get()) == currentPhase) {
907 <            QNode h;
908 <            long now = System.nanoTime();
909 <            nanos -= now - lastTime;
910 <            lastTime = now;
911 <            if (nanos <= 0) {
912 <                if (node != null)
913 <                    node.thread = null;
914 <                if (phaseOf(state.get()) == currentPhase)
915 <                    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);
905 >        boolean interrupted = false;
906 >        int p;
907 >        while ((p = getPhase()) == phase && !interrupted) {
908 >            if (Thread.interrupted())
909 >                interrupted = true;
910 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
911 >                break;
912 >            else if (node == null)
913 >                node = new QNode(this, phase, true, true, startTime, nanos);
914 >            else if (!queued)
915 >                queued = tryEnqueue(node);
916              else
917 <                --spins;
917 >                interrupted = node.doWait();
918          }
919          if (node != null)
920              node.thread = null;
921 +        if (p != phase || (p = getPhase()) != phase)
922 +            releaseWaiters(phase);
923 +        if (interrupted)
924 +            throw new InterruptedException();
925 +        if (p == phase)
926 +            throw new TimeoutException();
927 +        return p;
928      }
929  
930 < }
930 >    // Temporary Unsafe mechanics for preliminary release
931 >    private static Unsafe getUnsafe() throws Throwable {
932 >        try {
933 >            return Unsafe.getUnsafe();
934 >        } catch (SecurityException se) {
935 >            try {
936 >                return java.security.AccessController.doPrivileged
937 >                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
938 >                        public Unsafe run() throws Exception {
939 >                            return getUnsafePrivileged();
940 >                        }});
941 >            } catch (java.security.PrivilegedActionException e) {
942 >                throw e.getCause();
943 >            }
944 >        }
945 >    }
946 >
947 >    private static Unsafe getUnsafePrivileged()
948 >            throws NoSuchFieldException, IllegalAccessException {
949 >        Field f = Unsafe.class.getDeclaredField("theUnsafe");
950 >        f.setAccessible(true);
951 >        return (Unsafe) f.get(null);
952 >    }
953 >
954 >    private static long fieldOffset(String fieldName)
955 >            throws NoSuchFieldException {
956 >        return UNSAFE.objectFieldOffset
957 >            (Phaser.class.getDeclaredField(fieldName));
958 >    }
959  
960 +    static final Unsafe UNSAFE;
961 +    static final long stateOffset;
962 +
963 +    static {
964 +        try {
965 +            UNSAFE = getUnsafe();
966 +            stateOffset = fieldOffset("state");
967 +        } catch (Throwable e) {
968 +            throw new RuntimeException("Could not initialize intrinsics", e);
969 +        }
970 +    }
971 +
972 +    final boolean casState(long cmp, long val) {
973 +        return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
974 +    }
975 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines