ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.63
Committed: Mon Nov 29 15:47:19 2010 UTC (13 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.62: +167 -176 lines
Log Message:
improve javadocs; strengthen getPhase spec; streamline waiting

File Contents

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