ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.44
Committed: Fri Dec 3 21:41:30 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.43: +15 -11 lines
Log Message:
improve auto-registration description in javadoc

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.10 * @return the arrival phase number, or a negative number if terminated
624 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
625     * of unarrived parties would become negative
626     */
627     public int arriveAndAwaitAdvance() {
628 dl 1.39 return awaitAdvance(doArrive(false));
629 jsr166 1.1 }
630    
631     /**
632 dl 1.37 * Awaits the phase of this phaser to advance from the given phase
633     * value, returning immediately if the current phase is not equal
634     * to the given phase value or this phaser is terminated.
635 jsr166 1.1 *
636 jsr166 1.10 * @param phase an arrival phase number, or negative value if
637     * terminated; this argument is normally the value returned by a
638 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
639 jsr166 1.10 * @return the next arrival phase number, or a negative value
640     * if terminated or argument is negative
641 jsr166 1.1 */
642     public int awaitAdvance(int phase) {
643 dl 1.36 Phaser rt;
644 dl 1.34 int p = (int)(state >>> PHASE_SHIFT);
645 jsr166 1.1 if (phase < 0)
646     return phase;
647 dl 1.39 if (p == phase) {
648     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase)
649     return rt.internalAwaitAdvance(phase, null);
650     reconcileState();
651     }
652 dl 1.34 return p;
653 jsr166 1.1 }
654    
655     /**
656 dl 1.37 * Awaits the phase of this phaser to advance from the given phase
657 jsr166 1.10 * value, throwing {@code InterruptedException} if interrupted
658 dl 1.37 * while waiting, or returning immediately if the current phase is
659     * not equal to the given phase value or this phaser is
660     * terminated.
661 jsr166 1.10 *
662     * @param phase an arrival phase number, or negative value if
663     * terminated; this argument is normally the value returned by a
664 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
665 jsr166 1.10 * @return the next arrival phase number, or a negative value
666     * if terminated or argument is negative
667 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
668     */
669     public int awaitAdvanceInterruptibly(int phase)
670     throws InterruptedException {
671 dl 1.36 Phaser rt;
672 dl 1.34 int p = (int)(state >>> PHASE_SHIFT);
673 jsr166 1.1 if (phase < 0)
674     return phase;
675 dl 1.39 if (p == phase) {
676     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
677     QNode node = new QNode(this, phase, true, false, 0L);
678     p = rt.internalAwaitAdvance(phase, node);
679     if (node.wasInterrupted)
680     throw new InterruptedException();
681     }
682     else
683     reconcileState();
684 dl 1.24 }
685     return p;
686 jsr166 1.1 }
687    
688     /**
689 dl 1.37 * Awaits the phase of this phaser to advance from the given phase
690 jsr166 1.10 * value or the given timeout to elapse, throwing {@code
691     * InterruptedException} if interrupted while waiting, or
692 dl 1.37 * returning immediately if the current phase is not equal to the
693     * given phase value or this phaser is terminated.
694 jsr166 1.10 *
695     * @param phase an arrival phase number, or negative value if
696     * terminated; this argument is normally the value returned by a
697 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
698 jsr166 1.8 * @param timeout how long to wait before giving up, in units of
699     * {@code unit}
700     * @param unit a {@code TimeUnit} determining how to interpret the
701     * {@code timeout} parameter
702 jsr166 1.10 * @return the next arrival phase number, or a negative value
703     * if terminated or argument is negative
704 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
705     * @throws TimeoutException if timed out while waiting
706     */
707     public int awaitAdvanceInterruptibly(int phase,
708     long timeout, TimeUnit unit)
709     throws InterruptedException, TimeoutException {
710 dl 1.34 long nanos = unit.toNanos(timeout);
711 dl 1.36 Phaser rt;
712 dl 1.34 int p = (int)(state >>> PHASE_SHIFT);
713 jsr166 1.1 if (phase < 0)
714     return phase;
715 dl 1.39 if (p == phase) {
716     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
717     QNode node = new QNode(this, phase, true, true, nanos);
718     p = rt.internalAwaitAdvance(phase, node);
719     if (node.wasInterrupted)
720     throw new InterruptedException();
721     else if (p == phase)
722     throw new TimeoutException();
723     }
724     else
725     reconcileState();
726 dl 1.24 }
727     return p;
728 jsr166 1.1 }
729    
730     /**
731 dl 1.37 * Forces this phaser to enter termination state. Counts of
732 dl 1.39 * registered parties are unaffected. If this phaser is a member
733     * of a tiered set of phasers, then all of the phasers in the set
734     * are terminated. If this phaser is already terminated, this
735     * method has no effect. This method may be useful for
736     * coordinating recovery after one or more tasks encounter
737     * unexpected exceptions.
738 jsr166 1.1 */
739     public void forceTermination() {
740 jsr166 1.23 // Only need to change root state
741     final Phaser root = this.root;
742 dl 1.14 long s;
743 jsr166 1.23 while ((s = root.state) >= 0) {
744 dl 1.39 long next = (s & ~(long)(MAX_PARTIES)) | TERMINATION_BIT;
745     if (UNSAFE.compareAndSwapLong(root, stateOffset, s, next)) {
746 jsr166 1.23 releaseWaiters(0); // signal all threads
747     releaseWaiters(1);
748     return;
749     }
750     }
751 jsr166 1.1 }
752    
753     /**
754     * Returns the current phase number. The maximum phase number is
755     * {@code Integer.MAX_VALUE}, after which it restarts at
756 dl 1.37 * zero. Upon termination, the phase number is negative,
757     * in which case the prevailing phase prior to termination
758     * may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
759 jsr166 1.1 *
760     * @return the phase number, or a negative value if terminated
761     */
762     public final int getPhase() {
763 dl 1.31 return (int)(root.state >>> PHASE_SHIFT);
764 jsr166 1.1 }
765    
766     /**
767 dl 1.37 * Returns the number of parties registered at this phaser.
768 jsr166 1.1 *
769     * @return the number of parties
770     */
771     public int getRegisteredParties() {
772 dl 1.31 return partiesOf(state);
773 jsr166 1.1 }
774    
775     /**
776 jsr166 1.10 * Returns the number of registered parties that have arrived at
777 dl 1.37 * the current phase of this phaser.
778 jsr166 1.1 *
779     * @return the number of arrived parties
780     */
781     public int getArrivedParties() {
782 dl 1.39 return arrivedOf(reconcileState());
783 jsr166 1.1 }
784    
785     /**
786     * Returns the number of registered parties that have not yet
787 dl 1.37 * arrived at the current phase of this phaser.
788 jsr166 1.1 *
789     * @return the number of unarrived parties
790     */
791     public int getUnarrivedParties() {
792 dl 1.39 return unarrivedOf(reconcileState());
793 jsr166 1.1 }
794    
795     /**
796 dl 1.37 * Returns the parent of this phaser, or {@code null} if none.
797 jsr166 1.1 *
798 dl 1.37 * @return the parent of this phaser, or {@code null} if none
799 jsr166 1.1 */
800     public Phaser getParent() {
801     return parent;
802     }
803    
804     /**
805 dl 1.37 * Returns the root ancestor of this phaser, which is the same as
806     * this phaser if it has no parent.
807 jsr166 1.1 *
808 dl 1.37 * @return the root ancestor of this phaser
809 jsr166 1.1 */
810     public Phaser getRoot() {
811     return root;
812     }
813    
814     /**
815 dl 1.37 * Returns {@code true} if this phaser has been terminated.
816 jsr166 1.1 *
817 dl 1.37 * @return {@code true} if this phaser has been terminated
818 jsr166 1.1 */
819     public boolean isTerminated() {
820 dl 1.31 return root.state < 0L;
821 jsr166 1.1 }
822    
823     /**
824 jsr166 1.10 * Overridable method to perform an action upon impending phase
825     * advance, and to control termination. This method is invoked
826 dl 1.37 * upon arrival of the party advancing this phaser (when all other
827 jsr166 1.10 * waiting parties are dormant). If this method returns {@code
828 dl 1.39 * true}, this phaser will be set to a final termination state
829     * upon advance, and subsequent calls to {@link #isTerminated}
830     * will return true. Any (unchecked) Exception or Error thrown by
831     * an invocation of this method is propagated to the party
832     * attempting to advance this phaser, in which case no advance
833     * occurs.
834 jsr166 1.10 *
835 dl 1.37 * <p>The arguments to this method provide the state of the phaser
836 dl 1.17 * prevailing for the current transition. The effects of invoking
837 dl 1.37 * arrival, registration, and waiting methods on this phaser from
838 dl 1.15 * within {@code onAdvance} are unspecified and should not be
839 dl 1.17 * relied on.
840     *
841 dl 1.37 * <p>If this phaser is a member of a tiered set of phasers, then
842     * {@code onAdvance} is invoked only for its root phaser on each
843 dl 1.17 * advance.
844 jsr166 1.1 *
845 dl 1.33 * <p>To support the most common use cases, the default
846     * implementation of this method returns {@code true} when the
847     * number of registered parties has become zero as the result of a
848     * party invoking {@code arriveAndDeregister}. You can disable
849     * this behavior, thus enabling continuation upon future
850     * registrations, by overriding this method to always return
851     * {@code false}:
852     *
853     * <pre> {@code
854     * Phaser phaser = new Phaser() {
855     * protected boolean onAdvance(int phase, int parties) { return false; }
856     * }}</pre>
857 jsr166 1.1 *
858 dl 1.37 * @param phase the current phase number on entry to this method,
859     * before this phaser is advanced
860 jsr166 1.1 * @param registeredParties the current number of registered parties
861 dl 1.37 * @return {@code true} if this phaser should terminate
862 jsr166 1.1 */
863     protected boolean onAdvance(int phase, int registeredParties) {
864 dl 1.36 return registeredParties == 0;
865 jsr166 1.1 }
866    
867     /**
868 dl 1.37 * Returns a string identifying this phaser, as well as its
869 dl 1.21 * state. The state, in brackets, includes the String {@code
870     * "phase = "} followed by the phase number, {@code "parties = "}
871     * followed by the number of registered parties, and {@code
872     * "arrived = "} followed by the number of arrived parties.
873 jsr166 1.1 *
874 dl 1.37 * @return a string identifying this phaser, as well as its state
875 jsr166 1.1 */
876     public String toString() {
877 dl 1.21 return stateToString(reconcileState());
878     }
879    
880     /**
881     * Implementation of toString and string-based error messages
882     */
883     private String stateToString(long s) {
884 jsr166 1.1 return super.toString() +
885     "[phase = " + phaseOf(s) +
886     " parties = " + partiesOf(s) +
887     " arrived = " + arrivedOf(s) + "]";
888     }
889    
890 dl 1.21 // Waiting mechanics
891    
892 jsr166 1.1 /**
893 jsr166 1.30 * Removes and signals threads from queue for phase.
894 jsr166 1.1 */
895     private void releaseWaiters(int phase) {
896 dl 1.37 QNode q; // first element of queue
897     int p; // its phase
898     Thread t; // its thread
899 dl 1.39 // assert phase != phaseOf(root.state);
900 dl 1.36 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
901 dl 1.17 while ((q = head.get()) != null &&
902 dl 1.39 q.phase != (int)(root.state >>> PHASE_SHIFT)) {
903 dl 1.37 if (head.compareAndSet(q, q.next) &&
904     (t = q.thread) != null) {
905     q.thread = null;
906     LockSupport.unpark(t);
907     }
908 jsr166 1.1 }
909     }
910    
911 dl 1.17 /** The number of CPUs, for spin control */
912     private static final int NCPU = Runtime.getRuntime().availableProcessors();
913    
914 jsr166 1.1 /**
915 dl 1.17 * The number of times to spin before blocking while waiting for
916     * advance, per arrival while waiting. On multiprocessors, fully
917     * blocking and waking up a large number of threads all at once is
918     * usually a very slow process, so we use rechargeable spins to
919     * avoid it when threads regularly arrive: When a thread in
920     * internalAwaitAdvance notices another arrival before blocking,
921     * and there appear to be enough CPUs available, it spins
922 dl 1.36 * SPINS_PER_ARRIVAL more times before blocking. The value trades
923     * off good-citizenship vs big unnecessary slowdowns.
924 dl 1.15 */
925 jsr166 1.22 static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
926 dl 1.15
927     /**
928 dl 1.17 * Possibly blocks and waits for phase to advance unless aborted.
929 dl 1.34 * Call only from root node.
930 jsr166 1.1 *
931 dl 1.17 * @param phase current phase
932 jsr166 1.22 * @param node if non-null, the wait node to track interrupt and timeout;
933 dl 1.17 * if null, denotes noninterruptible wait
934 jsr166 1.1 * @return current phase
935     */
936 dl 1.17 private int internalAwaitAdvance(int phase, QNode node) {
937 dl 1.37 releaseWaiters(phase-1); // ensure old queue clean
938     boolean queued = false; // true when node is enqueued
939     int lastUnarrived = 0; // to increase spins upon change
940 dl 1.17 int spins = SPINS_PER_ARRIVAL;
941 dl 1.31 long s;
942     int p;
943 dl 1.34 while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
944 dl 1.37 if (node == null) { // spinning in noninterruptible mode
945     int unarrived = (int)s & UNARRIVED_MASK;
946     if (unarrived != lastUnarrived &&
947     (lastUnarrived = unarrived) < NCPU)
948 dl 1.31 spins += SPINS_PER_ARRIVAL;
949 dl 1.37 boolean interrupted = Thread.interrupted();
950     if (interrupted || --spins < 0) { // need node to record intr
951     node = new QNode(this, phase, false, false, 0L);
952     node.wasInterrupted = interrupted;
953     }
954 dl 1.21 }
955 dl 1.37 else if (node.isReleasable()) // done or aborted
956     break;
957     else if (!queued) { // push onto queue
958 dl 1.36 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
959 dl 1.37 QNode q = node.next = head.get();
960     if ((q == null || q.phase == phase) &&
961     (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
962 dl 1.36 queued = head.compareAndSet(q, node);
963 dl 1.31 }
964 dl 1.17 else {
965     try {
966     ForkJoinPool.managedBlock(node);
967     } catch (InterruptedException ie) {
968     node.wasInterrupted = true;
969     }
970     }
971     }
972 dl 1.34
973     if (node != null) {
974     if (node.thread != null)
975 dl 1.37 node.thread = null; // avoid need for unpark()
976 dl 1.36 if (node.wasInterrupted && !node.interruptible)
977 dl 1.34 Thread.currentThread().interrupt();
978 dl 1.39 if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
979 dl 1.37 return p; // recheck abort
980 dl 1.34 }
981 dl 1.37 releaseWaiters(phase);
982 dl 1.31 return p;
983 jsr166 1.1 }
984    
985     /**
986 dl 1.17 * Wait nodes for Treiber stack representing wait queue
987 jsr166 1.1 */
988 dl 1.17 static final class QNode implements ForkJoinPool.ManagedBlocker {
989     final Phaser phaser;
990     final int phase;
991     final boolean interruptible;
992     final boolean timed;
993     boolean wasInterrupted;
994     long nanos;
995     long lastTime;
996     volatile Thread thread; // nulled to cancel wait
997     QNode next;
998    
999     QNode(Phaser phaser, int phase, boolean interruptible,
1000     boolean timed, long nanos) {
1001     this.phaser = phaser;
1002     this.phase = phase;
1003     this.interruptible = interruptible;
1004     this.nanos = nanos;
1005     this.timed = timed;
1006 jsr166 1.38 this.lastTime = timed ? System.nanoTime() : 0L;
1007 dl 1.17 thread = Thread.currentThread();
1008     }
1009    
1010     public boolean isReleasable() {
1011 dl 1.37 if (thread == null)
1012     return true;
1013     if (phaser.getPhase() != phase) {
1014     thread = null;
1015     return true;
1016     }
1017     if (Thread.interrupted())
1018     wasInterrupted = true;
1019     if (wasInterrupted && interruptible) {
1020     thread = null;
1021     return true;
1022     }
1023     if (timed) {
1024     if (nanos > 0L) {
1025     long now = System.nanoTime();
1026     nanos -= now - lastTime;
1027     lastTime = now;
1028     }
1029     if (nanos <= 0L) {
1030     thread = null;
1031     return true;
1032 dl 1.17 }
1033 dl 1.15 }
1034 dl 1.37 return false;
1035 dl 1.17 }
1036    
1037     public boolean block() {
1038     if (isReleasable())
1039     return true;
1040     else if (!timed)
1041     LockSupport.park(this);
1042     else if (nanos > 0)
1043     LockSupport.parkNanos(this, nanos);
1044     return isReleasable();
1045     }
1046 jsr166 1.1 }
1047    
1048     // Unsafe mechanics
1049    
1050     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1051 jsr166 1.2 private static final long stateOffset =
1052 jsr166 1.3 objectFieldOffset("state", Phaser.class);
1053 jsr166 1.1
1054 jsr166 1.3 private static long objectFieldOffset(String field, Class<?> klazz) {
1055     try {
1056     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1057     } catch (NoSuchFieldException e) {
1058     // Convert Exception to corresponding Error
1059     NoSuchFieldError error = new NoSuchFieldError(field);
1060     error.initCause(e);
1061     throw error;
1062     }
1063     }
1064 jsr166 1.1 }