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.59 by dl, Sat Nov 27 16:46:53 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines