ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.43
Committed: Fri Dec 3 21:29:34 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.42: +1 -1 lines
Log Message:
typo

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