ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.49
Committed: Fri Dec 3 23:18:12 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.48: +2 -1 lines
Log Message:
make @return spec of await methods more precise

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