ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.22
Committed: Sun Nov 14 20:44:11 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.21: +4 -5 lines
Log Message:
tidying

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package java.util.concurrent;
8    
9 dl 1.17 import java.util.concurrent.TimeUnit;
10     import java.util.concurrent.TimeoutException;
11 jsr166 1.1 import java.util.concurrent.atomic.AtomicReference;
12     import java.util.concurrent.locks.LockSupport;
13    
14     /**
15 jsr166 1.10 * A reusable synchronization barrier, similar in functionality to
16 jsr166 1.1 * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
17     * {@link java.util.concurrent.CountDownLatch CountDownLatch}
18     * but supporting more flexible usage.
19     *
20 jsr166 1.10 * <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     * <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 jsr166 1.1 * <ul>
46     *
47 jsr166 1.10 * <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 jsr166 1.1 *
75     * </ul>
76     *
77 jsr166 1.10 * <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}. As illustrated below, when
83     * phasers control actions with a fixed number of iterations, it is
84 jsr166 1.7 * often convenient to override this method to cause termination when
85     * the current phase number reaches a threshold. Method {@link
86     * #forceTermination} is also available to abruptly release waiting
87     * threads and allow them to terminate.
88 jsr166 1.1 *
89 jsr166 1.10 * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e., arranged
90     * in tree structures) to reduce contention. Phasers with large
91 jsr166 1.1 * numbers of parties that would otherwise experience heavy
92 jsr166 1.10 * synchronization contention costs may instead be set up so that
93     * groups of sub-phasers share a common parent. This may greatly
94     * increase throughput even though it incurs greater per-operation
95     * overhead.
96     *
97     * <p><b>Monitoring.</b> While synchronization methods may be invoked
98     * only by registered parties, the current state of a phaser may be
99     * monitored by any caller. At any given moment there are {@link
100     * #getRegisteredParties} parties in total, of which {@link
101     * #getArrivedParties} have arrived at the current phase ({@link
102     * #getPhase}). When the remaining ({@link #getUnarrivedParties})
103     * parties arrive, the phase advances. The values returned by these
104     * methods may reflect transient states and so are not in general
105     * useful for synchronization control. Method {@link #toString}
106     * returns snapshots of these state queries in a form convenient for
107     * informal monitoring.
108 jsr166 1.1 *
109     * <p><b>Sample usages:</b>
110     *
111 jsr166 1.4 * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
112 jsr166 1.12 * to control a one-shot action serving a variable number of parties.
113     * The typical idiom is for the method setting this up to first
114     * register, then start the actions, then deregister, as in:
115 jsr166 1.1 *
116     * <pre> {@code
117 jsr166 1.8 * void runTasks(List<Runnable> tasks) {
118 jsr166 1.1 * final Phaser phaser = new Phaser(1); // "1" to register self
119 jsr166 1.7 * // create and start threads
120 jsr166 1.8 * for (Runnable task : tasks) {
121 jsr166 1.1 * phaser.register();
122     * new Thread() {
123     * public void run() {
124     * phaser.arriveAndAwaitAdvance(); // await all creation
125 jsr166 1.8 * task.run();
126 jsr166 1.1 * }
127     * }.start();
128     * }
129     *
130 jsr166 1.7 * // allow threads to start and deregister self
131     * phaser.arriveAndDeregister();
132 jsr166 1.1 * }}</pre>
133     *
134     * <p>One way to cause a set of threads to repeatedly perform actions
135     * for a given number of iterations is to override {@code onAdvance}:
136     *
137     * <pre> {@code
138 jsr166 1.8 * void startTasks(List<Runnable> tasks, final int iterations) {
139 jsr166 1.1 * final Phaser phaser = new Phaser() {
140 jsr166 1.10 * protected boolean onAdvance(int phase, int registeredParties) {
141 jsr166 1.1 * return phase >= iterations || registeredParties == 0;
142     * }
143     * };
144     * phaser.register();
145 jsr166 1.10 * for (final Runnable task : tasks) {
146 jsr166 1.1 * phaser.register();
147     * new Thread() {
148     * public void run() {
149     * do {
150 jsr166 1.8 * task.run();
151 jsr166 1.1 * phaser.arriveAndAwaitAdvance();
152 jsr166 1.10 * } while (!phaser.isTerminated());
153 jsr166 1.1 * }
154     * }.start();
155     * }
156     * phaser.arriveAndDeregister(); // deregister self, don't wait
157     * }}</pre>
158     *
159 jsr166 1.10 * If the main task must later await termination, it
160     * may re-register and then execute a similar loop:
161     * <pre> {@code
162     * // ...
163     * phaser.register();
164     * while (!phaser.isTerminated())
165     * phaser.arriveAndAwaitAdvance();}</pre>
166     *
167     * <p>Related constructions may be used to await particular phase numbers
168     * in contexts where you are sure that the phase will never wrap around
169     * {@code Integer.MAX_VALUE}. For example:
170     *
171     * <pre> {@code
172     * void awaitPhase(Phaser phaser, int phase) {
173     * int p = phaser.register(); // assumes caller not already registered
174     * while (p < phase) {
175     * if (phaser.isTerminated())
176     * // ... deal with unexpected termination
177     * else
178     * p = phaser.arriveAndAwaitAdvance();
179     * }
180     * phaser.arriveAndDeregister();
181     * }}</pre>
182     *
183     *
184 jsr166 1.5 * <p>To create a set of tasks using a tree of phasers,
185 jsr166 1.1 * you could use code of the following form, assuming a
186 jsr166 1.4 * Task class with a constructor accepting a phaser that
187 jsr166 1.12 * it registers with upon construction:
188 jsr166 1.10 *
189 jsr166 1.1 * <pre> {@code
190 jsr166 1.10 * void build(Task[] actions, int lo, int hi, Phaser ph) {
191     * if (hi - lo > TASKS_PER_PHASER) {
192     * for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
193     * int j = Math.min(i + TASKS_PER_PHASER, hi);
194     * build(actions, i, j, new Phaser(ph));
195 jsr166 1.1 * }
196     * } else {
197     * for (int i = lo; i < hi; ++i)
198 jsr166 1.10 * actions[i] = new Task(ph);
199     * // assumes new Task(ph) performs ph.register()
200 jsr166 1.1 * }
201     * }
202     * // .. initially called, for n tasks via
203     * build(new Task[n], 0, n, new Phaser());}</pre>
204     *
205     * The best value of {@code TASKS_PER_PHASER} depends mainly on
206     * expected barrier synchronization rates. A value as low as four may
207     * be appropriate for extremely small per-barrier task bodies (thus
208     * high rates), or up to hundreds for extremely large ones.
209     *
210     * <p><b>Implementation notes</b>: This implementation restricts the
211     * maximum number of parties to 65535. Attempts to register additional
212 jsr166 1.8 * parties result in {@code IllegalStateException}. However, you can and
213 jsr166 1.1 * should create tiered phasers to accommodate arbitrarily large sets
214     * of participants.
215     *
216     * @since 1.7
217     * @author Doug Lea
218     */
219     public class Phaser {
220     /*
221     * This class implements an extension of X10 "clocks". Thanks to
222     * Vijay Saraswat for the idea, and to Vivek Sarkar for
223     * enhancements to extend functionality.
224     */
225    
226     /**
227     * Barrier state representation. Conceptually, a barrier contains
228     * four values:
229     *
230 dl 1.17 * * unarrived -- the number of parties yet to hit barrier (bits 0-15)
231     * * parties -- the number of parties to wait (bits 16-31)
232     * * phase -- the generation of the barrier (bits 32-62)
233     * * terminated -- set if barrier is terminated (bit 63 / sign)
234 jsr166 1.1 *
235     * However, to efficiently maintain atomicity, these values are
236     * packed into a single (atomic) long. Termination uses the sign
237     * bit of 32 bit representation of phase, so phase is set to -1 on
238     * termination. Good performance relies on keeping state decoding
239     * and encoding simple, and keeping race windows short.
240     */
241     private volatile long state;
242    
243 dl 1.17 private static final int MAX_COUNT = 0xffff;
244     private static final int MAX_PHASE = 0x7fffffff;
245     private static final int PARTIES_SHIFT = 16;
246     private static final int PHASE_SHIFT = 32;
247     private static final long UNARRIVED_MASK = 0xffffL;
248     private static final long PARTIES_MASK = 0xffff0000L;
249     private static final long ONE_ARRIVAL = 1L;
250     private static final long ONE_PARTY = 1L << PARTIES_SHIFT;
251     private static final long TERMINATION_PHASE = -1L << PHASE_SHIFT;
252    
253     // The following unpacking methods are usually manually inlined
254 jsr166 1.1
255     private static int unarrivedOf(long s) {
256 dl 1.17 return (int) (s & UNARRIVED_MASK);
257 jsr166 1.1 }
258    
259     private static int partiesOf(long s) {
260 dl 1.17 return ((int) (s & PARTIES_MASK)) >>> PARTIES_SHIFT;
261 jsr166 1.1 }
262    
263     private static int phaseOf(long s) {
264 dl 1.17 return (int) (s >>> PHASE_SHIFT);
265 jsr166 1.1 }
266    
267     private static int arrivedOf(long s) {
268     return partiesOf(s) - unarrivedOf(s);
269     }
270    
271     /**
272     * The parent of this phaser, or null if none
273     */
274     private final Phaser parent;
275    
276     /**
277 jsr166 1.4 * The root of phaser tree. Equals this if not in a tree. Used to
278 jsr166 1.1 * support faster state push-down.
279     */
280     private final Phaser root;
281    
282     /**
283     * Heads of Treiber stacks for waiting threads. To eliminate
284 dl 1.14 * contention when releasing some threads while adding others, we
285 jsr166 1.1 * use two of them, alternating across even and odd phases.
286 dl 1.14 * Subphasers share queues with root to speed up releases.
287 jsr166 1.1 */
288 dl 1.15 private final AtomicReference<QNode> evenQ;
289     private final AtomicReference<QNode> oddQ;
290 jsr166 1.1
291     private AtomicReference<QNode> queueFor(int phase) {
292 dl 1.15 return ((phase & 1) == 0) ? evenQ : oddQ;
293 jsr166 1.1 }
294    
295     /**
296 dl 1.17 * Main implementation for methods arrive and arriveAndDeregister.
297     * Manually tuned to speed up and minimize race windows for the
298     * common case of just decrementing unarrived field.
299     *
300     * @param adj - adjustment to apply to state -- either
301     * ONE_ARRIVAL (for arrive) or
302     * ONE_ARRIVAL|ONE_PARTY (for arriveAndDeregister)
303     */
304     private int doArrive(long adj) {
305 dl 1.21 for (;;) {
306     long s;
307     int phase, unarrived;
308     if ((phase = (int)((s = state) >>> PHASE_SHIFT)) < 0)
309     return phase;
310     else if ((unarrived = (int)(s & UNARRIVED_MASK)) == 0)
311     checkBadArrive(s);
312     else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s -= adj)){
313     if (unarrived == 1) {
314     Phaser par;
315     long p = s & PARTIES_MASK; // unshifted parties field
316     long lu = p >>> PARTIES_SHIFT;
317     int u = (int)lu;
318     int nextPhase = (phase + 1) & MAX_PHASE;
319     long next = ((long)nextPhase << PHASE_SHIFT) | p | lu;
320     if ((par = parent) == null) {
321     UNSAFE.compareAndSwapLong
322     (this, stateOffset, s, onAdvance(phase, u)?
323     next | TERMINATION_PHASE : next);
324     releaseWaiters(phase);
325     }
326     else {
327     par.doArrive(u == 0?
328     ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL);
329     if ((int)(par.state >>> PHASE_SHIFT) != nextPhase ||
330     ((int)(state >>> PHASE_SHIFT) != nextPhase &&
331     !UNSAFE.compareAndSwapLong(this, stateOffset,
332     s, next)))
333     reconcileState();
334 dl 1.17 }
335     }
336 dl 1.21 return phase;
337 dl 1.17 }
338     }
339     }
340    
341     /**
342 dl 1.21 * Rechecks state and throws bounds exceptions on arrival -- called
343     * only if unarrived is apparently zero.
344 dl 1.17 */
345 dl 1.21 private void checkBadArrive(long s) {
346     if (reconcileState() == s)
347     throw new IllegalStateException
348     ("Attempted arrival of unregistered party for " +
349     stateToString(s));
350 dl 1.17 }
351    
352     /**
353     * Implementation of register, bulkRegister
354     *
355     * @param registrations number to add to both parties and unarrived fields
356 jsr166 1.1 */
357 dl 1.17 private int doRegister(int registrations) {
358     long adj = (long)registrations; // adjustment to state
359     adj |= adj << PARTIES_SHIFT;
360     Phaser par = parent;
361 dl 1.21 for (;;) {
362     int phase, parties;
363     long s = par == null? state : reconcileState();
364     if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
365     return phase;
366     if ((parties = ((int)(s & PARTIES_MASK)) >>> PARTIES_SHIFT) != 0 &&
367     (s & UNARRIVED_MASK) == 0)
368 dl 1.17 internalAwaitAdvance(phase, null); // wait for onAdvance
369     else if (parties + registrations > MAX_COUNT)
370 dl 1.21 throw new IllegalStateException(badRegister(s));
371 dl 1.17 else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s + adj))
372 dl 1.21 return phase;
373 dl 1.17 }
374     }
375    
376     /**
377 jsr166 1.22 * Returns message string for out of bounds exceptions on registration.
378 dl 1.17 */
379 dl 1.21 private String badRegister(long s) {
380 jsr166 1.20 return "Attempt to register more than " +
381 dl 1.21 MAX_COUNT + " parties for " + stateToString(s);
382 jsr166 1.1 }
383    
384     /**
385 jsr166 1.22 * Recursively resolves lagged phase propagation from root if necessary.
386 jsr166 1.1 */
387     private long reconcileState() {
388 dl 1.14 Phaser par = parent;
389 dl 1.17 if (par == null)
390     return state;
391     Phaser rt = root;
392 dl 1.21 for (;;) {
393     long s, u;
394     int phase, rPhase, pPhase;
395     if ((phase = (int)((s = state)>>> PHASE_SHIFT)) < 0 ||
396     (rPhase = (int)(rt.state >>> PHASE_SHIFT)) == phase)
397     return s;
398     long pState = par.parent == null? par.state : par.reconcileState();
399     if (state == s) {
400     if ((rPhase < 0 || (s & UNARRIVED_MASK) == 0) &&
401     ((pPhase = (int)(pState >>> PHASE_SHIFT)) < 0 ||
402     pPhase == ((phase + 1) & MAX_PHASE)))
403     UNSAFE.compareAndSwapLong
404     (this, stateOffset, s,
405     (((long) pPhase) << PHASE_SHIFT) |
406     (u = s & PARTIES_MASK) |
407     (u >>> PARTIES_SHIFT)); // reset unarrived to parties
408     else
409     releaseWaiters(phase); // help release others
410 jsr166 1.1 }
411     }
412     }
413    
414     /**
415 jsr166 1.4 * Creates a new phaser without any initially registered parties,
416 jsr166 1.1 * initial phase number 0, and no parent. Any thread using this
417 jsr166 1.4 * phaser will need to first register for it.
418 jsr166 1.1 */
419     public Phaser() {
420 dl 1.15 this(null, 0);
421 jsr166 1.1 }
422    
423     /**
424 jsr166 1.12 * Creates a new phaser with the given number of registered
425 jsr166 1.1 * unarrived parties, initial phase number 0, and no parent.
426     *
427     * @param parties the number of parties required to trip barrier
428     * @throws IllegalArgumentException if parties less than zero
429     * or greater than the maximum number of parties supported
430     */
431     public Phaser(int parties) {
432     this(null, parties);
433     }
434    
435     /**
436 jsr166 1.4 * Creates a new phaser with the given parent, without any
437 jsr166 1.1 * initially registered parties. If parent is non-null this phaser
438     * is registered with the parent and its initial phase number is
439     * the same as that of parent phaser.
440     *
441     * @param parent the parent phaser
442     */
443     public Phaser(Phaser parent) {
444 dl 1.15 this(parent, 0);
445 jsr166 1.1 }
446    
447     /**
448 jsr166 1.12 * Creates a new phaser with the given parent and number of
449 jsr166 1.1 * registered unarrived parties. If parent is non-null, this phaser
450     * is registered with the parent and its initial phase number is
451     * the same as that of parent phaser.
452     *
453     * @param parent the parent phaser
454     * @param parties the number of parties required to trip barrier
455     * @throws IllegalArgumentException if parties less than zero
456     * or greater than the maximum number of parties supported
457     */
458     public Phaser(Phaser parent, int parties) {
459 dl 1.17 if (parties < 0 || parties > MAX_COUNT)
460 jsr166 1.1 throw new IllegalArgumentException("Illegal number of parties");
461 dl 1.15 int phase;
462 jsr166 1.1 this.parent = parent;
463     if (parent != null) {
464 dl 1.15 Phaser r = parent.root;
465     this.root = r;
466     this.evenQ = r.evenQ;
467     this.oddQ = r.oddQ;
468 jsr166 1.1 phase = parent.register();
469     }
470 dl 1.15 else {
471 jsr166 1.1 this.root = this;
472 dl 1.15 this.evenQ = new AtomicReference<QNode>();
473     this.oddQ = new AtomicReference<QNode>();
474     phase = 0;
475     }
476 dl 1.17 long p = (long)parties;
477     this.state = (((long) phase) << PHASE_SHIFT) | p | (p << PARTIES_SHIFT);
478 jsr166 1.1 }
479    
480     /**
481     * Adds a new unarrived party to this phaser.
482 dl 1.14 * If an ongoing invocation of {@link #onAdvance} is in progress,
483 dl 1.15 * this method may wait until its completion before registering.
484 jsr166 1.1 *
485 jsr166 1.10 * @return the arrival phase number to which this registration applied
486 jsr166 1.1 * @throws IllegalStateException if attempting to register more
487     * than the maximum supported number of parties
488     */
489     public int register() {
490     return doRegister(1);
491     }
492    
493     /**
494     * Adds the given number of new unarrived parties to this phaser.
495 dl 1.14 * If an ongoing invocation of {@link #onAdvance} is in progress,
496 dl 1.15 * this method may wait until its completion before registering.
497 jsr166 1.1 *
498 jsr166 1.12 * @param parties the number of additional parties required to trip barrier
499 jsr166 1.10 * @return the arrival phase number to which this registration applied
500 jsr166 1.1 * @throws IllegalStateException if attempting to register more
501     * than the maximum supported number of parties
502 dl 1.13 * @throws IllegalArgumentException if {@code parties < 0}
503 jsr166 1.1 */
504     public int bulkRegister(int parties) {
505     if (parties < 0)
506     throw new IllegalArgumentException();
507 dl 1.17 if (parties > MAX_COUNT)
508 dl 1.21 throw new IllegalStateException(badRegister(state));
509 jsr166 1.1 if (parties == 0)
510     return getPhase();
511     return doRegister(parties);
512     }
513    
514     /**
515     * Arrives at the barrier, but does not wait for others. (You can
516 jsr166 1.10 * in turn wait for others via {@link #awaitAdvance}). It is an
517     * unenforced usage error for an unregistered party to invoke this
518     * method.
519 jsr166 1.1 *
520 jsr166 1.10 * @return the arrival phase number, or a negative value if terminated
521 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
522     * of unarrived parties would become negative
523     */
524     public int arrive() {
525 dl 1.17 return doArrive(ONE_ARRIVAL);
526 jsr166 1.1 }
527    
528     /**
529 jsr166 1.7 * Arrives at the barrier and deregisters from it without waiting
530     * for others. Deregistration reduces the number of parties
531 jsr166 1.1 * required to trip the barrier in future phases. If this phaser
532     * has a parent, and deregistration causes this phaser to have
533 jsr166 1.7 * zero parties, this phaser also arrives at and is deregistered
534 jsr166 1.10 * from its parent. It is an unenforced usage error for an
535     * unregistered party to invoke this method.
536 jsr166 1.1 *
537 jsr166 1.10 * @return the arrival phase number, or a negative value if terminated
538 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
539     * of registered or unarrived parties would become negative
540     */
541     public int arriveAndDeregister() {
542 dl 1.17 return doArrive(ONE_ARRIVAL|ONE_PARTY);
543 jsr166 1.1 }
544    
545     /**
546     * Arrives at the barrier and awaits others. Equivalent in effect
547 jsr166 1.7 * to {@code awaitAdvance(arrive())}. If you need to await with
548     * interruption or timeout, you can arrange this with an analogous
549 jsr166 1.12 * construction using one of the other forms of the {@code
550     * awaitAdvance} method. If instead you need to deregister upon
551     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
552     * usage error for an unregistered party to invoke this method.
553 jsr166 1.1 *
554 jsr166 1.10 * @return the arrival phase number, or a negative number if terminated
555 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
556     * of unarrived parties would become negative
557     */
558     public int arriveAndAwaitAdvance() {
559     return awaitAdvance(arrive());
560     }
561    
562     /**
563 jsr166 1.7 * Awaits the phase of the barrier to advance from the given phase
564 jsr166 1.8 * value, returning immediately if the current phase of the
565     * barrier is not equal to the given phase value or this barrier
566 dl 1.15 * is terminated.
567 jsr166 1.1 *
568 jsr166 1.10 * @param phase an arrival phase number, or negative value if
569     * terminated; this argument is normally the value returned by a
570     * previous call to {@code arrive} or its variants
571     * @return the next arrival phase number, or a negative value
572     * if terminated or argument is negative
573 jsr166 1.1 */
574     public int awaitAdvance(int phase) {
575     if (phase < 0)
576     return phase;
577 dl 1.17 int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
578 jsr166 1.1 if (p != phase)
579     return p;
580 dl 1.17 return internalAwaitAdvance(phase, null);
581 jsr166 1.1 }
582    
583     /**
584 jsr166 1.8 * Awaits the phase of the barrier to advance from the given phase
585 jsr166 1.10 * value, throwing {@code InterruptedException} if interrupted
586     * while waiting, or returning immediately if the current phase of
587     * the barrier is not equal to the given phase value or this
588 dl 1.15 * barrier is terminated.
589 jsr166 1.10 *
590     * @param phase an arrival phase number, or negative value if
591     * terminated; this argument is normally the value returned by a
592     * previous call to {@code arrive} or its variants
593     * @return the next arrival phase number, or a negative value
594     * if terminated or argument is negative
595 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
596     */
597     public int awaitAdvanceInterruptibly(int phase)
598     throws InterruptedException {
599     if (phase < 0)
600     return phase;
601 dl 1.17 int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
602 jsr166 1.1 if (p != phase)
603     return p;
604 dl 1.17 QNode node = new QNode(this, phase, true, false, 0L);
605     p = internalAwaitAdvance(phase, node);
606     if (node.wasInterrupted)
607     throw new InterruptedException();
608     else
609     return p;
610 jsr166 1.1 }
611    
612     /**
613 jsr166 1.8 * Awaits the phase of the barrier to advance from the given phase
614 jsr166 1.10 * value or the given timeout to elapse, throwing {@code
615     * InterruptedException} if interrupted while waiting, or
616     * returning immediately if the current phase of the barrier is
617     * not equal to the given phase value or this barrier is
618 dl 1.15 * terminated.
619 jsr166 1.10 *
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 jsr166 1.8 * @param timeout how long to wait before giving up, in units of
624     * {@code unit}
625     * @param unit a {@code TimeUnit} determining how to interpret the
626     * {@code timeout} parameter
627 jsr166 1.10 * @return the next arrival phase number, or a negative value
628     * if terminated or argument is negative
629 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
630     * @throws TimeoutException if timed out while waiting
631     */
632     public int awaitAdvanceInterruptibly(int phase,
633     long timeout, TimeUnit unit)
634     throws InterruptedException, TimeoutException {
635 dl 1.14 long nanos = unit.toNanos(timeout);
636 jsr166 1.1 if (phase < 0)
637     return phase;
638 dl 1.17 int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
639 jsr166 1.1 if (p != phase)
640     return p;
641 dl 1.17 QNode node = new QNode(this, phase, true, true, nanos);
642     p = internalAwaitAdvance(phase, node);
643     if (node.wasInterrupted)
644     throw new InterruptedException();
645     else if (p == phase)
646     throw new TimeoutException();
647     else
648     return p;
649 jsr166 1.1 }
650    
651     /**
652     * Forces this barrier to enter termination state. Counts of
653     * arrived and registered parties are unaffected. If this phaser
654     * has a parent, it too is terminated. This method may be useful
655     * for coordinating recovery after one or more tasks encounter
656     * unexpected exceptions.
657     */
658     public void forceTermination() {
659 dl 1.14 Phaser r = root; // force at root then reconcile
660     long s;
661 dl 1.17 while ((s = r.state) >= 0)
662     UNSAFE.compareAndSwapLong(r, stateOffset, s, s | TERMINATION_PHASE);
663 dl 1.14 reconcileState();
664 dl 1.17 releaseWaiters(0); // signal all threads
665 dl 1.14 releaseWaiters(1);
666 jsr166 1.1 }
667    
668     /**
669     * Returns the current phase number. The maximum phase number is
670     * {@code Integer.MAX_VALUE}, after which it restarts at
671     * zero. Upon termination, the phase number is negative.
672     *
673     * @return the phase number, or a negative value if terminated
674     */
675     public final int getPhase() {
676 dl 1.21 return (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
677 jsr166 1.1 }
678    
679     /**
680     * Returns the number of parties registered at this barrier.
681     *
682     * @return the number of parties
683     */
684     public int getRegisteredParties() {
685 dl 1.21 return partiesOf(parent==null? state : reconcileState());
686 jsr166 1.1 }
687    
688     /**
689 jsr166 1.10 * Returns the number of registered parties that have arrived at
690     * the current phase of this barrier.
691 jsr166 1.1 *
692     * @return the number of arrived parties
693     */
694     public int getArrivedParties() {
695 dl 1.21 return arrivedOf(parent==null? state : reconcileState());
696 jsr166 1.1 }
697    
698     /**
699     * Returns the number of registered parties that have not yet
700     * arrived at the current phase of this barrier.
701     *
702     * @return the number of unarrived parties
703     */
704     public int getUnarrivedParties() {
705 dl 1.21 return unarrivedOf(parent==null? state : reconcileState());
706 jsr166 1.1 }
707    
708     /**
709 jsr166 1.4 * Returns the parent of this phaser, or {@code null} if none.
710 jsr166 1.1 *
711 jsr166 1.4 * @return the parent of this phaser, or {@code null} if none
712 jsr166 1.1 */
713     public Phaser getParent() {
714     return parent;
715     }
716    
717     /**
718     * Returns the root ancestor of this phaser, which is the same as
719     * this phaser if it has no parent.
720     *
721     * @return the root ancestor of this phaser
722     */
723     public Phaser getRoot() {
724     return root;
725     }
726    
727     /**
728     * Returns {@code true} if this barrier has been terminated.
729     *
730     * @return {@code true} if this barrier has been terminated
731     */
732     public boolean isTerminated() {
733 dl 1.17 return (parent == null? state : reconcileState()) < 0;
734 jsr166 1.1 }
735    
736     /**
737 jsr166 1.10 * Overridable method to perform an action upon impending phase
738     * advance, and to control termination. This method is invoked
739     * upon arrival of the party tripping the barrier (when all other
740     * waiting parties are dormant). If this method returns {@code
741     * true}, then, rather than advance the phase number, this barrier
742     * will be set to a final termination state, and subsequent calls
743     * to {@link #isTerminated} will return true. Any (unchecked)
744     * Exception or Error thrown by an invocation of this method is
745     * propagated to the party attempting to trip the barrier, in
746     * which case no advance occurs.
747     *
748     * <p>The arguments to this method provide the state of the phaser
749 dl 1.17 * prevailing for the current transition. The effects of invoking
750     * arrival, registration, and waiting methods on this Phaser from
751 dl 1.15 * within {@code onAdvance} are unspecified and should not be
752 dl 1.17 * relied on.
753     *
754     * <p>If this Phaser is a member of a tiered set of Phasers, then
755     * {@code onAdvance} is invoked only for its root Phaser on each
756     * advance.
757 jsr166 1.1 *
758 jsr166 1.5 * <p>The default version returns {@code true} when the number of
759 jsr166 1.1 * registered parties is zero. Normally, overrides that arrange
760     * termination for other reasons should also preserve this
761     * property.
762     *
763     * @param phase the phase number on entering the barrier
764     * @param registeredParties the current number of registered parties
765     * @return {@code true} if this barrier should terminate
766     */
767     protected boolean onAdvance(int phase, int registeredParties) {
768     return registeredParties <= 0;
769     }
770    
771     /**
772 dl 1.21 * Returns a string identifying this phaser, as well as its
773     * state. The state, in brackets, includes the String {@code
774     * "phase = "} followed by the phase number, {@code "parties = "}
775     * followed by the number of registered parties, and {@code
776     * "arrived = "} followed by the number of arrived parties.
777 jsr166 1.1 *
778     * @return a string identifying this barrier, as well as its state
779     */
780     public String toString() {
781 dl 1.21 return stateToString(reconcileState());
782     }
783    
784     /**
785     * Implementation of toString and string-based error messages
786     */
787     private String stateToString(long s) {
788 jsr166 1.1 return super.toString() +
789     "[phase = " + phaseOf(s) +
790     " parties = " + partiesOf(s) +
791     " arrived = " + arrivedOf(s) + "]";
792     }
793    
794 dl 1.21 // Waiting mechanics
795    
796 jsr166 1.1 /**
797 dl 1.21 * Removes and signals threads from queue for phase
798 jsr166 1.1 */
799     private void releaseWaiters(int phase) {
800     AtomicReference<QNode> head = queueFor(phase);
801     QNode q;
802 dl 1.17 int p;
803     while ((q = head.get()) != null &&
804     ((p = q.phase) == phase ||
805     (int)(root.state >>> PHASE_SHIFT) != p)) {
806 jsr166 1.1 if (head.compareAndSet(q, q.next))
807     q.signal();
808     }
809     }
810    
811     /**
812     * Tries to enqueue given node in the appropriate wait queue.
813     *
814     * @return true if successful
815     */
816 dl 1.17 private boolean tryEnqueue(int phase, QNode node) {
817     releaseWaiters(phase-1); // ensure old queue clean
818     AtomicReference<QNode> head = queueFor(phase);
819     QNode q = head.get();
820     return ((q == null || q.phase == phase) &&
821     (int)(root.state >>> PHASE_SHIFT) == phase &&
822     head.compareAndSet(node.next = q, node));
823 jsr166 1.1 }
824    
825 dl 1.17 /** The number of CPUs, for spin control */
826     private static final int NCPU = Runtime.getRuntime().availableProcessors();
827    
828 jsr166 1.1 /**
829 dl 1.17 * The number of times to spin before blocking while waiting for
830     * advance, per arrival while waiting. On multiprocessors, fully
831     * blocking and waking up a large number of threads all at once is
832     * usually a very slow process, so we use rechargeable spins to
833     * avoid it when threads regularly arrive: When a thread in
834     * internalAwaitAdvance notices another arrival before blocking,
835     * and there appear to be enough CPUs available, it spins
836     * SPINS_PER_ARRIVAL more times before continuing to try to
837     * block. The value trades off good-citizenship vs big unnecessary
838     * slowdowns.
839 dl 1.15 */
840 jsr166 1.22 static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
841 dl 1.15
842     /**
843 dl 1.17 * Possibly blocks and waits for phase to advance unless aborted.
844 jsr166 1.1 *
845 dl 1.17 * @param phase current phase
846 jsr166 1.22 * @param node if non-null, the wait node to track interrupt and timeout;
847 dl 1.17 * if null, denotes noninterruptible wait
848 jsr166 1.1 * @return current phase
849     */
850 dl 1.17 private int internalAwaitAdvance(int phase, QNode node) {
851     Phaser current = this; // to eventually wait at root if tiered
852 dl 1.21 boolean queued = false; // true when node is enqueued
853     int lastUnarrived = -1; // to increase spins upon change
854 dl 1.17 int spins = SPINS_PER_ARRIVAL;
855 dl 1.21 for (;;) {
856     int p, unarrived;
857     Phaser par;
858     long s = current.state;
859     if ((p = (int)(s >>> PHASE_SHIFT)) != phase) {
860     if (node != null)
861     node.onRelease();
862     releaseWaiters(phase);
863     return p;
864     }
865     else if ((unarrived = (int)(s & UNARRIVED_MASK)) != lastUnarrived) {
866 dl 1.17 if ((lastUnarrived = unarrived) < NCPU)
867     spins += SPINS_PER_ARRIVAL;
868     }
869 dl 1.21 else if (unarrived == 0 && (par = current.parent) != null) {
870 dl 1.17 current = par; // if all arrived, use parent
871     par = par.parent;
872 dl 1.21 lastUnarrived = -1;
873 dl 1.15 }
874 dl 1.17 else if (spins > 0)
875     --spins;
876 dl 1.21 else if (node == null) // must be noninterruptible
877 dl 1.17 node = new QNode(this, phase, false, false, 0L);
878 dl 1.21 else if (node.isReleasable()) {
879     if ((int)(reconcileState() >>> PHASE_SHIFT) == phase)
880     return phase; // aborted
881     }
882 jsr166 1.1 else if (!queued)
883 dl 1.17 queued = tryEnqueue(phase, node);
884     else {
885     try {
886     ForkJoinPool.managedBlock(node);
887     } catch (InterruptedException ie) {
888     node.wasInterrupted = true;
889     }
890     }
891     }
892 jsr166 1.1 }
893    
894     /**
895 dl 1.17 * Wait nodes for Treiber stack representing wait queue
896 jsr166 1.1 */
897 dl 1.17 static final class QNode implements ForkJoinPool.ManagedBlocker {
898     final Phaser phaser;
899     final int phase;
900     final boolean interruptible;
901     final boolean timed;
902     boolean wasInterrupted;
903     long nanos;
904     long lastTime;
905     volatile Thread thread; // nulled to cancel wait
906     QNode next;
907    
908     QNode(Phaser phaser, int phase, boolean interruptible,
909     boolean timed, long nanos) {
910     this.phaser = phaser;
911     this.phase = phase;
912     this.interruptible = interruptible;
913     this.nanos = nanos;
914     this.timed = timed;
915     this.lastTime = timed? System.nanoTime() : 0L;
916     thread = Thread.currentThread();
917     }
918    
919     public boolean isReleasable() {
920     Thread t = thread;
921     if (t != null) {
922     if (phaser.getPhase() != phase)
923     t = null;
924     else {
925     if (Thread.interrupted())
926     wasInterrupted = true;
927     if (interruptible && wasInterrupted)
928     t = null;
929     else if (timed) {
930     if (nanos > 0) {
931     long now = System.nanoTime();
932     nanos -= now - lastTime;
933     lastTime = now;
934     }
935     if (nanos <= 0)
936     t = null;
937     }
938     }
939     if (t != null)
940     return false;
941     thread = null;
942 dl 1.15 }
943 dl 1.17 return true;
944     }
945    
946     public boolean block() {
947     if (isReleasable())
948     return true;
949     else if (!timed)
950     LockSupport.park(this);
951     else if (nanos > 0)
952     LockSupport.parkNanos(this, nanos);
953     return isReleasable();
954     }
955 jsr166 1.1
956 dl 1.17 void signal() {
957     Thread t = thread;
958     if (t != null) {
959     thread = null;
960     LockSupport.unpark(t);
961 dl 1.15 }
962 dl 1.17 }
963 dl 1.21
964     void onRelease() { // actions upon return from internalAwaitAdvance
965     if (!interruptible && wasInterrupted)
966     Thread.currentThread().interrupt();
967     if (thread != null)
968     thread = null;
969     }
970    
971 jsr166 1.1 }
972    
973     // Unsafe mechanics
974    
975     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
976 jsr166 1.2 private static final long stateOffset =
977 jsr166 1.3 objectFieldOffset("state", Phaser.class);
978 jsr166 1.1
979 jsr166 1.3 private static long objectFieldOffset(String field, Class<?> klazz) {
980     try {
981     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
982     } catch (NoSuchFieldException e) {
983     // Convert Exception to corresponding Error
984     NoSuchFieldError error = new NoSuchFieldError(field);
985     error.initCause(e);
986     throw error;
987     }
988     }
989 jsr166 1.1 }