ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
(Generate patch)

Comparing jsr166/src/jsr166y/Phaser.java (file contents):
Revision 1.3 by jsr166, Fri Jul 25 18:11:53 2008 UTC vs.
Revision 1.13 by jsr166, Mon Jul 20 22:40:09 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>).
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.
69 < *
70 < * <li> Unlike most synchronizers, a Phaser may also be used with
71 < * ForkJoinTasks (as well as plain threads).
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> By default, <tt>awaitAdvance</tt> continues to wait even if
78 < * 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      /**
# Line 133 | Line 193 | public class Phaser {
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.
311 >     * unarrived parties, initial phase number 0, and no parent.
312       * @param parties the number of parties required to trip barrier.
313       * @throws IllegalArgumentException if parties less than zero
314       * or greater than the maximum number of parties supported.
315       */
316      public Phaser(int parties) {
317 +        this(null, parties);
318 +    }
319 +
320 +    /**
321 +     * Creates a new Phaser with the given parent, without any
322 +     * initially registered parties. If parent is non-null this phaser
323 +     * is registered with the parent and its initial phase number is
324 +     * the same as that of parent phaser.
325 +     * @param parent the parent phaser.
326 +     */
327 +    public Phaser(Phaser parent) {
328 +        int phase = 0;
329 +        this.parent = parent;
330 +        if (parent != null) {
331 +            this.root = parent.root;
332 +            phase = parent.register();
333 +        }
334 +        else
335 +            this.root = this;
336 +        this.state = trippedStateFor(phase, 0);
337 +    }
338 +
339 +    /**
340 +     * Creates a new Phaser with the given parent and numbers of
341 +     * registered unarrived parties. If parent is non-null this phaser
342 +     * is registered with the parent and its initial phase number is
343 +     * the same as that of parent phaser.
344 +     * @param parent the parent phaser.
345 +     * @param parties the number of parties required to trip barrier.
346 +     * @throws IllegalArgumentException if parties less than zero
347 +     * or greater than the maximum number of parties supported.
348 +     */
349 +    public Phaser(Phaser parent, int parties) {
350          if (parties < 0 || parties > ushortMask)
351              throw new IllegalArgumentException("Illegal number of parties");
352 <        state = new AtomicLong(stateFor(0, parties, parties));
352 >        int phase = 0;
353 >        this.parent = parent;
354 >        if (parent != null) {
355 >            this.root = parent.root;
356 >            phase = parent.register();
357 >        }
358 >        else
359 >            this.root = this;
360 >        this.state = trippedStateFor(phase, parties);
361      }
362  
363      /**
# Line 200 | Line 366 | public class Phaser {
366       * @throws IllegalStateException if attempting to register more
367       * than the maximum supported number of parties.
368       */
369 <    public int register() { // increment both parties and unarrived
370 <        final AtomicLong state = this.state;
369 >    public int register() {
370 >        return doRegister(1);
371 >    }
372 >
373 >    /**
374 >     * Adds the given number of new unarrived parties to this phaser.
375 >     * @param parties the number of parties required to trip barrier.
376 >     * @return the current barrier phase number upon registration
377 >     * @throws IllegalStateException if attempting to register more
378 >     * than the maximum supported number of parties.
379 >     */
380 >    public int bulkRegister(int parties) {
381 >        if (parties < 0)
382 >            throw new IllegalArgumentException();
383 >        if (parties == 0)
384 >            return getPhase();
385 >        return doRegister(parties);
386 >    }
387 >
388 >    /**
389 >     * Shared code for register, bulkRegister
390 >     */
391 >    private int doRegister(int registrations) {
392 >        int phase;
393          for (;;) {
394 <            long s = state.get();
395 <            int phase = phaseOf(s);
396 <            int parties = partiesOf(s) + 1;
397 <            int unarrived = unarrivedOf(s) + 1;
394 >            long s = getReconciledState();
395 >            phase = phaseOf(s);
396 >            int unarrived = unarrivedOf(s) + registrations;
397 >            int parties = partiesOf(s) + registrations;
398 >            if (phase < 0)
399 >                break;
400              if (parties > ushortMask || unarrived > ushortMask)
401 <                throw badBounds(parties, unarrived);
402 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
403 <                return phase;
401 >                throw new IllegalStateException(badBounds(parties, unarrived));
402 >            if (phase == phaseOf(root.state) &&
403 >                casState(s, stateFor(phase, parties, unarrived)))
404 >                break;
405          }
406 +        return phase;
407      }
408  
409      /**
410       * Arrives at the barrier, but does not wait for others.  (You can
411       * in turn wait for others via {@link #awaitAdvance}).
412       *
413 <     * @return the current barrier phase number upon entry to
414 <     * this method, or a negative value if terminated;
415 <     * @throws IllegalStateException if the number of unarrived
416 <     * parties would become negative.
413 >     * @return the barrier phase number upon entry to this method, or a
414 >     * negative value if terminated;
415 >     * @throws IllegalStateException if not terminated and the number
416 >     * of unarrived parties would become negative.
417       */
418 <    public int arrive() { // decrement unarrived. If zero, trip
419 <        final AtomicLong state = this.state;
418 >    public int arrive() {
419 >        int phase;
420          for (;;) {
421 <            long s = state.get();
422 <            int phase = phaseOf(s);
421 >            long s = state;
422 >            phase = phaseOf(s);
423 >            if (phase < 0)
424 >                break;
425              int parties = partiesOf(s);
426              int unarrived = unarrivedOf(s) - 1;
427 <            if (unarrived < 0)
428 <                throw badBounds(parties, unarrived);
429 <            if (unarrived == 0 && phase >= 0) {
236 <                trip(phase, parties);
237 <                return phase;
427 >            if (unarrived > 0) {        // Not the last arrival
428 >                if (casState(s, s - 1)) // s-1 adds one arrival
429 >                    break;
430              }
431 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
432 <                return phase;
431 >            else if (unarrived == 0) {  // the last arrival
432 >                Phaser par = parent;
433 >                if (par == null) {      // directly trip
434 >                    if (casState
435 >                        (s,
436 >                         trippedStateFor(onAdvance(phase, parties)? -1 :
437 >                                         ((phase + 1) & phaseMask), parties))) {
438 >                        releaseWaiters(phase);
439 >                        break;
440 >                    }
441 >                }
442 >                else {                  // cascade to parent
443 >                    if (casState(s, s - 1)) { // zeroes unarrived
444 >                        par.arrive();
445 >                        reconcileState();
446 >                        break;
447 >                    }
448 >                }
449 >            }
450 >            else if (phase != phaseOf(root.state)) // or if unreconciled
451 >                reconcileState();
452 >            else
453 >                throw new IllegalStateException(badBounds(parties, unarrived));
454          }
455 +        return phase;
456      }
457  
458      /**
459       * Arrives at the barrier, and deregisters from it, without
460 <     * waiting for others.
460 >     * waiting for others. Deregistration reduces number of parties
461 >     * required to trip the barrier in future phases.  If this phaser
462 >     * has a parent, and deregistration causes this phaser to have
463 >     * zero parties, this phaser is also deregistered from its parent.
464       *
465       * @return the current barrier phase number upon entry to
466       * this method, or a negative value if terminated;
467 <     * @throws IllegalStateException if the number of registered or
468 <     * unarrived parties would become negative.
467 >     * @throws IllegalStateException if not terminated and the number
468 >     * of registered or unarrived parties would become negative.
469       */
470 <    public int arriveAndDeregister() { // Same as arrive, plus decrement parties
471 <        final AtomicLong state = this.state;
470 >    public int arriveAndDeregister() {
471 >        // similar code to arrive, but too different to merge
472 >        Phaser par = parent;
473 >        int phase;
474          for (;;) {
475 <            long s = state.get();
476 <            int phase = phaseOf(s);
475 >            long s = state;
476 >            phase = phaseOf(s);
477 >            if (phase < 0)
478 >                break;
479              int parties = partiesOf(s) - 1;
480              int unarrived = unarrivedOf(s) - 1;
481 <            if (parties < 0 || unarrived < 0)
482 <                throw badBounds(parties, unarrived);
483 <            if (unarrived == 0 && phase >= 0) {
484 <                trip(phase, parties);
485 <                return phase;
481 >            if (parties >= 0) {
482 >                if (unarrived > 0 || (unarrived == 0 && par != null)) {
483 >                    if (casState
484 >                        (s,
485 >                         stateFor(phase, parties, unarrived))) {
486 >                        if (unarrived == 0) {
487 >                            par.arriveAndDeregister();
488 >                            reconcileState();
489 >                        }
490 >                        break;
491 >                    }
492 >                    continue;
493 >                }
494 >                if (unarrived == 0) {
495 >                    if (casState
496 >                        (s,
497 >                         trippedStateFor(onAdvance(phase, parties)? -1 :
498 >                                         ((phase + 1) & phaseMask), parties))) {
499 >                        releaseWaiters(phase);
500 >                        break;
501 >                    }
502 >                    continue;
503 >                }
504 >                if (par != null && phase != phaseOf(root.state)) {
505 >                    reconcileState();
506 >                    continue;
507 >                }
508              }
509 <            if (state.compareAndSet(s, stateFor(phase, parties, unarrived)))
267 <                return phase;
509 >            throw new IllegalStateException(badBounds(parties, unarrived));
510          }
511 +        return phase;
512      }
513  
514      /**
515 <     * Arrives at the barrier and awaits others. Unlike other arrival
516 <     * methods, this method returns the arrival index of the
517 <     * caller. The caller tripping the barrier returns zero, the
518 <     * previous caller 1, and so on.
519 <     * @return the arrival index
520 <     * @throws IllegalStateException if the number of unarrived
521 <     * parties would become negative.
515 >     * Arrives at the barrier and awaits others. Equivalent in effect
516 >     * to {@code awaitAdvance(arrive())}.  If you instead need to
517 >     * await with interruption of timeout, and/or deregister upon
518 >     * arrival, you can arrange them using analogous constructions.
519 >     * @return the phase on entry to this method
520 >     * @throws IllegalStateException if not terminated and the number
521 >     * of unarrived parties would become negative.
522       */
523      public int arriveAndAwaitAdvance() {
524 <        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 <        }
524 >        return awaitAdvance(arrive());
525      }
526  
527      /**
528       * Awaits the phase of the barrier to advance from the given
529 <     * value, or returns immediately if this barrier is terminated.
529 >     * value, or returns immediately if argument is negative or this
530 >     * barrier is terminated.
531       * @param phase the phase on entry to this method
532       * @return the phase on exit from this method
533       */
534      public int awaitAdvance(int phase) {
535          if (phase < 0)
536              return phase;
537 <        Thread current = Thread.currentThread();
538 <        if (current instanceof ForkJoinWorkerThread)
539 <            return helpingWait(phase);
540 <        if (untimedWait(current, phase, false))
541 <            current.interrupt();
542 <        return phaseOf(state.get());
537 >        long s = getReconciledState();
538 >        int p = phaseOf(s);
539 >        if (p != phase)
540 >            return p;
541 >        if (unarrivedOf(s) == 0 && parent != null)
542 >            parent.awaitAdvance(phase);
543 >        // Fall here even if parent waited, to reconcile and help release
544 >        return untimedWait(phase);
545      }
546  
547      /**
548       * Awaits the phase of the barrier to advance from the given
549 <     * value, or returns immediately if this barrier is terminated, or
550 <     * throws InterruptedException if interrupted while waiting.
549 >     * value, or returns immediately if argument is negative or this
550 >     * barrier is terminated, or throws InterruptedException if
551 >     * interrupted while waiting.
552       * @param phase the phase on entry to this method
553       * @return the phase on exit from this method
554       * @throws InterruptedException if thread interrupted while waiting
555       */
556 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
556 >    public int awaitAdvanceInterruptibly(int phase)
557 >        throws InterruptedException {
558          if (phase < 0)
559              return phase;
560 <        Thread current = Thread.currentThread();
561 <        if (current instanceof ForkJoinWorkerThread)
562 <            return helpingWait(phase);
563 <        else if (Thread.interrupted() || untimedWait(current, phase, true))
564 <            throw new InterruptedException();
565 <        else
566 <            return phaseOf(state.get());
560 >        long s = getReconciledState();
561 >        int p = phaseOf(s);
562 >        if (p != phase)
563 >            return p;
564 >        if (unarrivedOf(s) == 0 && parent != null)
565 >            parent.awaitAdvanceInterruptibly(phase);
566 >        return interruptibleWait(phase);
567      }
568  
569      /**
570       * Awaits the phase of the barrier to advance from the given value
571 <     * or the given timeout elapses, or returns immediately if this
572 <     * barrier is terminated.
571 >     * or the given timeout elapses, or returns immediately if
572 >     * argument is negative or this barrier is terminated.
573       * @param phase the phase on entry to this method
574       * @return the phase on exit from this method
575       * @throws InterruptedException if thread interrupted while waiting
# Line 347 | Line 579 | public class Phaser {
579          throws InterruptedException, TimeoutException {
580          if (phase < 0)
581              return phase;
582 <        long nanos = unit.toNanos(timeout);
583 <        Thread current = Thread.currentThread();
584 <        if (current instanceof ForkJoinWorkerThread)
585 <            return timedHelpingWait(phase, nanos);
586 <        timedWait(current, phase, nanos);
587 <        return phaseOf(state.get());
582 >        long s = getReconciledState();
583 >        int p = phaseOf(s);
584 >        if (p != phase)
585 >            return p;
586 >        if (unarrivedOf(s) == 0 && parent != null)
587 >            parent.awaitAdvanceInterruptibly(phase, timeout, unit);
588 >        return timedWait(phase, unit.toNanos(timeout));
589      }
590  
591      /**
592       * Forces this barrier to enter termination state. Counts of
593 <     * arrived and registered parties are unaffected. This method may
594 <     * be useful for coordinating recovery after one or more tasks
595 <     * encounter unexpected exceptions.
593 >     * arrived and registered parties are unaffected. If this phaser
594 >     * has a parent, it too is terminated. This method may be useful
595 >     * for coordinating recovery after one or more tasks encounter
596 >     * unexpected exceptions.
597       */
598      public void forceTermination() {
365        final AtomicLong state = this.state;
599          for (;;) {
600 <            long s = state.get();
600 >            long s = getReconciledState();
601              int phase = phaseOf(s);
602              int parties = partiesOf(s);
603              int unarrived = unarrivedOf(s);
604              if (phase < 0 ||
605 <                state.compareAndSet(s, stateFor(-1, parties, unarrived))) {
606 <                if (head.get() != null)
607 <                    releaseWaiters(-1);
605 >                casState(s, stateFor(-1, parties, unarrived))) {
606 >                releaseWaiters(0);
607 >                releaseWaiters(1);
608 >                if (parent != null)
609 >                    parent.forceTermination();
610                  return;
611              }
612          }
613      }
614  
615      /**
616 <     * Resets the barrier with the given numbers of registered unarrived
617 <     * parties and phase number 0. This method allows repeated reuse
618 <     * of this barrier, but only if it is somehow known not to be in
619 <     * use for other purposes.
385 <     * @param parties the number of parties required to trip barrier.
386 <     * @throws IllegalArgumentException if parties less than zero
387 <     * or greater than the maximum number of parties supported.
616 >     * Returns the current phase number. The maximum phase number is
617 >     * {@code Integer.MAX_VALUE}, after which it restarts at
618 >     * zero. Upon termination, the phase number is negative.
619 >     * @return the phase number, or a negative value if terminated
620       */
621 <    public void reset(int parties) {
622 <        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);
621 >    public final int getPhase() {
622 >        return phaseOf(getReconciledState());
623      }
624  
625      /**
626 <     * Returns the current phase number. The maximum phase number is
627 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
628 <     * zero. Upon termination, the phase number is negative.
401 <     * @return the phase number, or a negative value if terminated
626 >     * Returns {@code true} if the current phase number equals the given phase.
627 >     * @param phase the phase
628 >     * @return {@code true} if the current phase number equals the given phase
629       */
630 <    public int getPhase() {
631 <        return phaseOf(state.get());
630 >    public final boolean hasPhase(int phase) {
631 >        return phaseOf(getReconciledState()) == phase;
632      }
633  
634      /**
# Line 409 | Line 636 | public class Phaser {
636       * @return the number of parties
637       */
638      public int getRegisteredParties() {
639 <        return partiesOf(state.get());
639 >        return partiesOf(state);
640      }
641  
642      /**
# Line 418 | Line 645 | public class Phaser {
645       * @return the number of arrived parties
646       */
647      public int getArrivedParties() {
648 <        return arrivedOf(state.get());
648 >        return arrivedOf(state);
649      }
650  
651      /**
# Line 427 | Line 654 | public class Phaser {
654       * @return the number of unarrived parties
655       */
656      public int getUnarrivedParties() {
657 <        return unarrivedOf(state.get());
657 >        return unarrivedOf(state);
658 >    }
659 >
660 >    /**
661 >     * Returns the parent of this phaser, or null if none.
662 >     * @return the parent of this phaser, or null if none
663 >     */
664 >    public Phaser getParent() {
665 >        return parent;
666      }
667  
668      /**
669 <     * Returns true if this barrier has been terminated.
670 <     * @return true if this barrier has been terminated
669 >     * Returns the root ancestor of this phaser, which is the same as
670 >     * this phaser if it has no parent.
671 >     * @return the root ancestor of this phaser
672 >     */
673 >    public Phaser getRoot() {
674 >        return root;
675 >    }
676 >
677 >    /**
678 >     * Returns {@code true} if this barrier has been terminated.
679 >     * @return {@code true} if this barrier has been terminated
680       */
681      public boolean isTerminated() {
682 <        return phaseOf(state.get()) < 0;
682 >        return getPhase() < 0;
683      }
684  
685      /**
# Line 444 | Line 688 | public class Phaser {
688       * barrier is tripped (and thus all other waiting parties are
689       * dormant). If it returns true, then, rather than advance the
690       * phase number, this barrier will be set to a final termination
691 <     * state, and subsequent calls to <tt>isTerminated</tt> will
691 >     * state, and subsequent calls to {@code isTerminated} will
692       * return true.
693       *
694       * <p> The default version returns true when the number of
# Line 452 | Line 696 | public class Phaser {
696       * termination for other reasons should also preserve this
697       * property.
698       *
699 +     * <p> You may override this method to perform an action with side
700 +     * effects visible to participating tasks, but it is in general
701 +     * only sensible to do so in designs where all parties register
702 +     * before any arrive, and all {@code awaitAdvance} at each phase.
703 +     * Otherwise, you cannot ensure lack of interference. In
704 +     * particular, this method may be invoked more than once per
705 +     * transition if other parties successfully register while the
706 +     * invocation of this method is in progress, thus postponing the
707 +     * transition until those parties also arrive, re-triggering this
708 +     * method.
709 +     *
710       * @param phase the phase number on entering the barrier
711 <     * @param registeredParties the current number of registered
712 <     * parties.
458 <     * @return true if this barrier should terminate
711 >     * @param registeredParties the current number of registered parties
712 >     * @return {@code true} if this barrier should terminate
713       */
714      protected boolean onAdvance(int phase, int registeredParties) {
715          return registeredParties <= 0;
716      }
717  
718      /**
719 <     * Returns a string identifying this barrier, as well as its
719 >     * Returns a string identifying this phaser, as well as its
720       * state.  The state, in brackets, includes the String {@code
721 <     * "phase ="} followed by the phase number, {@code "parties ="}
721 >     * "phase = "} followed by the phase number, {@code "parties = "}
722       * followed by the number of registered parties, and {@code
723 <     * "arrived ="} followed by the number of arrived parties
723 >     * "arrived = "} followed by the number of arrived parties.
724       *
725       * @return a string identifying this barrier, as well as its state
726       */
727      public String toString() {
728 <        long s = state.get();
729 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
728 >        long s = getReconciledState();
729 >        return super.toString() +
730 >            "[phase = " + phaseOf(s) +
731 >            " parties = " + partiesOf(s) +
732 >            " arrived = " + arrivedOf(s) + "]";
733      }
734  
735 <    // methods for tripping and waiting
735 >    // methods for waiting
736  
737      /**
738 <     * Advance the current phase (or terminate)
738 >     * Wait nodes for Treiber stack representing wait queue
739       */
740 <    private void trip(int phase, int parties) {
741 <        int next = onAdvance(phase, parties)? -1 : ((phase + 1) & phaseMask);
742 <        state.set(stateFor(next, parties, parties));
743 <        if (head.get() != null)
744 <            releaseWaiters(next);
745 <    }
746 <
747 <    private int helpingWait(int phase) {
748 <        final AtomicLong state = this.state;
749 <        int p;
750 <        while ((p = phaseOf(state.get())) == phase) {
751 <            ForkJoinTask<?> t = ForkJoinWorkerThread.pollTask();
752 <            if (t != null) {
753 <                if ((p = phaseOf(state.get())) == phase)
754 <                    t.exec();
755 <                else {   // push task and exit if barrier advanced
756 <                    t.fork();
757 <                    break;
758 <                }
740 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
741 >        final Phaser phaser;
742 >        final int phase;
743 >        final long startTime;
744 >        final long nanos;
745 >        final boolean timed;
746 >        final boolean interruptible;
747 >        volatile boolean wasInterrupted = false;
748 >        volatile Thread thread; // nulled to cancel wait
749 >        QNode next;
750 >        QNode(Phaser phaser, int phase, boolean interruptible,
751 >              boolean timed, long startTime, long nanos) {
752 >            this.phaser = phaser;
753 >            this.phase = phase;
754 >            this.timed = timed;
755 >            this.interruptible = interruptible;
756 >            this.startTime = startTime;
757 >            this.nanos = nanos;
758 >            thread = Thread.currentThread();
759 >        }
760 >        public boolean isReleasable() {
761 >            return (thread == null ||
762 >                    phaser.getPhase() != phase ||
763 >                    (interruptible && wasInterrupted) ||
764 >                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
765 >        }
766 >        public boolean block() {
767 >            if (Thread.interrupted()) {
768 >                wasInterrupted = true;
769 >                if (interruptible)
770 >                    return true;
771 >            }
772 >            if (!timed)
773 >                LockSupport.park(this);
774 >            else {
775 >                long waitTime = nanos - (System.nanoTime() - startTime);
776 >                if (waitTime <= 0)
777 >                    return true;
778 >                LockSupport.parkNanos(this, waitTime);
779              }
780 +            return isReleasable();
781          }
782 <        return p;
783 <    }
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();
782 >        void signal() {
783 >            Thread t = thread;
784              if (t != null) {
785 <                if ((p = phaseOf(state.get())) == phase)
786 <                    t.exec();
787 <                else {   // push task and exit if barrier advanced
788 <                    t.fork();
789 <                    break;
785 >                thread = null;
786 >                LockSupport.unpark(t);
787 >            }
788 >        }
789 >        boolean doWait() {
790 >            if (thread != null) {
791 >                try {
792 >                    ForkJoinPool.managedBlock(this, false);
793 >                } catch (InterruptedException ie) {
794                  }
795              }
796 +            return wasInterrupted;
797          }
798 <        return p;
798 >
799      }
800  
801      /**
802 <     * 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.
802 >     * Removes and signals waiting threads from wait queue
803       */
804 <    static final class QNode {
805 <        QNode next;
806 <        volatile Thread thread; // nulled to cancel wait
807 <        final int phase;
808 <        QNode(Thread t, int c) {
809 <            thread = t;
545 <            phase = c;
546 <        }
547 <    }
548 <
549 <    private void releaseWaiters(int currentPhase) {
550 <        final AtomicReference<QNode> head = this.head;
551 <        QNode p;
552 <        while ((p = head.get()) != null && p.phase != currentPhase) {
553 <            if (head.compareAndSet(p, null)) {
554 <                do {
555 <                    Thread t = p.thread;
556 <                    if (t != null) {
557 <                        p.thread = null;
558 <                        LockSupport.unpark(t);
559 <                    }
560 <                } while ((p = p.next) != null);
561 <            }
804 >    private void releaseWaiters(int phase) {
805 >        AtomicReference<QNode> head = queueFor(phase);
806 >        QNode q;
807 >        while ((q = head.get()) != null) {
808 >            if (head.compareAndSet(q, q.next))
809 >                q.signal();
810          }
811      }
812  
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
813      /**
814 <     * The number of times to spin before blocking in untimed waits.
815 <     * This is greater than timed value because untimed waits spin
577 <     * faster since they don't need to check times on each spin.
814 >     * Tries to enqueue given node in the appropriate wait queue
815 >     * @return true if successful
816       */
817 <    static final int maxUntimedSpins = maxTimedSpins * 32;
817 >    private boolean tryEnqueue(QNode node) {
818 >        AtomicReference<QNode> head = queueFor(node.phase);
819 >        return head.compareAndSet(node.next = head.get(), node);
820 >    }
821  
822      /**
823 <     * The number of nanoseconds for which it is faster to spin
824 <     * rather than to use timed park. A rough estimate suffices.
823 >     * Enqueues node and waits unless aborted or signalled.
824 >     * @return current phase
825       */
826 <    static final long spinForTimeoutThreshold = 1000L;
826 >    private int untimedWait(int phase) {
827 >        QNode node = null;
828 >        boolean queued = false;
829 >        boolean interrupted = false;
830 >        int p;
831 >        while ((p = getPhase()) == phase) {
832 >            if (Thread.interrupted())
833 >                interrupted = true;
834 >            else if (node == null)
835 >                node = new QNode(this, phase, false, false, 0, 0);
836 >            else if (!queued)
837 >                queued = tryEnqueue(node);
838 >            else
839 >                interrupted = node.doWait();
840 >        }
841 >        if (node != null)
842 >            node.thread = null;
843 >        releaseWaiters(phase);
844 >        if (interrupted)
845 >            Thread.currentThread().interrupt();
846 >        return p;
847 >    }
848  
849      /**
850 <     * Enqueues node and waits unless aborted or signalled.
850 >     * Interruptible version
851 >     * @return current phase
852       */
853 <    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;
853 >    private int interruptibleWait(int phase) throws InterruptedException {
854          QNode node = null;
855          boolean queued = false;
856 <        int spins = maxUntimedSpins;
857 <        while (phaseOf(state.get()) == currentPhase) {
858 <            QNode h;
859 <            if (node != null && queued) {
860 <                if (node.thread != null) {
861 <                    LockSupport.park();
862 <                    if (Thread.interrupted()) {
863 <                        wasInterrupted = true;
864 <                        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);
856 >        boolean interrupted = false;
857 >        int p;
858 >        while ((p = getPhase()) == phase && !interrupted) {
859 >            if (Thread.interrupted())
860 >                interrupted = true;
861 >            else if (node == null)
862 >                node = new QNode(this, phase, true, false, 0, 0);
863 >            else if (!queued)
864 >                queued = tryEnqueue(node);
865              else
866 <                --spins;
866 >                interrupted = node.doWait();
867          }
868          if (node != null)
869              node.thread = null;
870 <        return wasInterrupted;
870 >        if (p != phase || (p = getPhase()) != phase)
871 >            releaseWaiters(phase);
872 >        if (interrupted)
873 >            throw new InterruptedException();
874 >        return p;
875      }
876  
877      /**
878 <     * Messier timeout version
878 >     * Timeout version.
879 >     * @return current phase
880       */
881 <    private void timedWait(Thread thread, int currentPhase, long nanos)
881 >    private int timedWait(int phase, long nanos)
882          throws InterruptedException, TimeoutException {
883 <        final AtomicReference<QNode> head = this.head;
641 <        final AtomicLong state = this.state;
642 <        long lastTime = System.nanoTime();
883 >        long startTime = System.nanoTime();
884          QNode node = null;
885          boolean queued = false;
886 <        int spins = maxTimedSpins;
887 <        while (phaseOf(state.get()) == currentPhase) {
888 <            QNode h;
889 <            long now = System.nanoTime();
890 <            nanos -= now - lastTime;
891 <            lastTime = now;
892 <            if (nanos <= 0) {
893 <                if (node != null)
894 <                    node.thread = null;
895 <                if (phaseOf(state.get()) == currentPhase)
896 <                    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);
886 >        boolean interrupted = false;
887 >        int p;
888 >        while ((p = getPhase()) == phase && !interrupted) {
889 >            if (Thread.interrupted())
890 >                interrupted = true;
891 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
892 >                break;
893 >            else if (node == null)
894 >                node = new QNode(this, phase, true, true, startTime, nanos);
895 >            else if (!queued)
896 >                queued = tryEnqueue(node);
897              else
898 <                --spins;
898 >                interrupted = node.doWait();
899          }
900          if (node != null)
901              node.thread = null;
902 +        if (p != phase || (p = getPhase()) != phase)
903 +            releaseWaiters(phase);
904 +        if (interrupted)
905 +            throw new InterruptedException();
906 +        if (p == phase)
907 +            throw new TimeoutException();
908 +        return p;
909 +    }
910 +
911 +    // Temporary Unsafe mechanics for preliminary release
912 +    private static Unsafe getUnsafe() throws Throwable {
913 +        try {
914 +            return Unsafe.getUnsafe();
915 +        } catch (SecurityException se) {
916 +            try {
917 +                return java.security.AccessController.doPrivileged
918 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
919 +                        public Unsafe run() throws Exception {
920 +                            return getUnsafePrivileged();
921 +                        }});
922 +            } catch (java.security.PrivilegedActionException e) {
923 +                throw e.getCause();
924 +            }
925 +        }
926 +    }
927 +
928 +    private static Unsafe getUnsafePrivileged()
929 +            throws NoSuchFieldException, IllegalAccessException {
930 +        Field f = Unsafe.class.getDeclaredField("theUnsafe");
931 +        f.setAccessible(true);
932 +        return (Unsafe) f.get(null);
933 +    }
934 +
935 +    private static long fieldOffset(String fieldName)
936 +            throws NoSuchFieldException {
937 +        return _unsafe.objectFieldOffset
938 +            (Phaser.class.getDeclaredField(fieldName));
939 +    }
940 +
941 +    static final Unsafe _unsafe;
942 +    static final long stateOffset;
943 +
944 +    static {
945 +        try {
946 +            _unsafe = getUnsafe();
947 +            stateOffset = fieldOffset("state");
948 +        } catch (Throwable e) {
949 +            throw new RuntimeException("Could not initialize intrinsics", e);
950 +        }
951      }
952  
953 +    final boolean casState(long cmp, long val) {
954 +        return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
955 +    }
956   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines