ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.66
Committed: Wed Dec 1 19:12:53 2010 UTC (13 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.65: +5 -5 lines
Log Message:
ternary operator coding style

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.65 * <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.45 *
193 jsr166 1.13 * <pre> {@code
194 dl 1.65 * void build(Task[] tasks, int lo, int hi, Phaser ph) {
195 dl 1.44 * 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.65 * build(tasks, i, j, new Phaser(ph));
199 jsr166 1.13 * }
200     * } else {
201     * for (int i = lo; i < hi; ++i)
202 dl 1.65 * tasks[i] = new Task(ph);
203 dl 1.44 * // assumes new Task(ph) performs ph.register()
204 jsr166 1.13 * }
205 dl 1.65 * }}</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 dl 1.65 * 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 dl 1.1 */
257 dl 1.4 private volatile long state;
258 dl 1.1
259 dl 1.59 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.51
267 dl 1.65 // 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.51 // The following unpacking methods are usually manually inlined
273 dl 1.1
274     private static int unarrivedOf(long s) {
275 dl 1.65 int counts = (int)s;
276 jsr166 1.66 return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK;
277 dl 1.1 }
278    
279     private static int partiesOf(long s) {
280 dl 1.65 int counts = (int)s;
281 jsr166 1.66 return (counts == EMPTY) ? 0 : counts >>> PARTIES_SHIFT;
282 dl 1.1 }
283    
284     private static int phaseOf(long s) {
285 dl 1.51 return (int) (s >>> PHASE_SHIFT);
286 dl 1.1 }
287    
288     private static int arrivedOf(long s) {
289 dl 1.65 int counts = (int)s;
290 jsr166 1.66 return (counts == EMPTY) ? 0 :
291 dl 1.65 (counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
292 dl 1.1 }
293    
294 dl 1.4 /**
295     * The parent of this phaser, or null if none
296     */
297     private final Phaser parent;
298    
299     /**
300 dl 1.65 * The root of phaser tree. Equals this if not in a tree.
301 dl 1.4 */
302     private final Phaser root;
303    
304     /**
305 dl 1.10 * Heads of Treiber stacks for waiting threads. To eliminate
306 dl 1.49 * contention when releasing some threads while adding others, we
307 dl 1.4 * use two of them, alternating across even and odd phases.
308 dl 1.49 * Subphasers share queues with root to speed up releases.
309 dl 1.4 */
310 dl 1.50 private final AtomicReference<QNode> evenQ;
311     private final AtomicReference<QNode> oddQ;
312 dl 1.4
313     private AtomicReference<QNode> queueFor(int phase) {
314 dl 1.50 return ((phase & 1) == 0) ? evenQ : oddQ;
315 dl 1.4 }
316    
317     /**
318 dl 1.59 * Returns message string for bounds exceptions on arrival.
319     */
320     private String badArrive(long s) {
321     return "Attempted arrival of unregistered party for " +
322     stateToString(s);
323     }
324    
325     /**
326     * Returns message string for bounds exceptions on registration.
327     */
328     private String badRegister(long s) {
329     return "Attempt to register more than " +
330     MAX_PARTIES + " parties for " + stateToString(s);
331     }
332    
333     /**
334 dl 1.51 * Main implementation for methods arrive and arriveAndDeregister.
335     * Manually tuned to speed up and minimize race windows for the
336     * common case of just decrementing unarrived field.
337     *
338 dl 1.65 * @param deregister false for arrive, true for arriveAndDeregister
339 dl 1.4 */
340 dl 1.65 private int doArrive(boolean deregister) {
341     int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
342     long s;
343     int phase;
344     while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0) {
345     int counts = (int)s;
346     int unarrived = counts & UNARRIVED_MASK;
347     if (counts == EMPTY || unarrived == 0) {
348     if (reconcileState() == s)
349 dl 1.59 throw new IllegalStateException(badArrive(s));
350     }
351 dl 1.55 else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
352 dl 1.54 if (unarrived == 1) {
353 dl 1.65 long n = s & PARTIES_MASK; // unshifted parties field
354     int u = ((int)n) >>> PARTIES_SHIFT;
355     Phaser par = parent;
356     if (par != null) {
357     par.doArrive(u == 0);
358     reconcileState();
359     }
360     else {
361     n |= (((long)((phase+1) & MAX_PHASE)) << PHASE_SHIFT);
362 dl 1.55 if (onAdvance(phase, u))
363 dl 1.65 n |= TERMINATION_BIT;
364     else if (u == 0)
365     n |= EMPTY; // reset to unregistered
366     else
367     n |= (long)u; // reset unarr to parties
368     // assert state == s || isTerminated();
369     UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
370 dl 1.54 releaseWaiters(phase);
371     }
372 dl 1.51 }
373 dl 1.65 break;
374 dl 1.51 }
375     }
376 dl 1.65 return phase;
377 dl 1.51 }
378    
379     /**
380     * Implementation of register, bulkRegister
381     *
382 dl 1.58 * @param registrations number to add to both parties and
383     * unarrived fields. Must be greater than zero.
384 dl 1.51 */
385     private int doRegister(int registrations) {
386 dl 1.57 // adjustment to state
387     long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
388 dl 1.65 Phaser par = parent;
389     int phase;
390 dl 1.54 for (;;) {
391 dl 1.65 long s = state;
392     int counts = (int)s;
393     int parties = counts >>> PARTIES_SHIFT;
394     int unarrived = counts & UNARRIVED_MASK;
395     if (registrations > MAX_PARTIES - parties)
396 dl 1.54 throw new IllegalStateException(badRegister(s));
397 dl 1.65 else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
398     break;
399     else if (counts != EMPTY) { // not 1st registration
400     if (par == null || reconcileState() == s) {
401     if (unarrived == 0) // wait out advance
402     root.internalAwaitAdvance(phase, null);
403     else if (UNSAFE.compareAndSwapLong(this, stateOffset,
404     s, s + adj))
405     break;
406     }
407     }
408     else if (par == null) { // 1st root registration
409     long next = (((long) phase) << PHASE_SHIFT) | adj;
410     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
411     break;
412     }
413     else {
414 jsr166 1.66 synchronized (this) { // 1st sub registration
415 dl 1.65 if (state == s) { // recheck under lock
416     par.doRegister(1);
417     do { // force current phase
418     phase = (int)(root.state >>> PHASE_SHIFT);
419     // assert phase < 0 || (int)state == EMPTY;
420     } while (!UNSAFE.compareAndSwapLong
421     (this, stateOffset, state,
422     (((long) phase) << PHASE_SHIFT) | adj));
423     break;
424 dl 1.59 }
425     }
426     }
427 dl 1.51 }
428 dl 1.65 return phase;
429 dl 1.51 }
430    
431     /**
432 dl 1.65 * Resolves lagged phase propagation from root if necessary.
433 dl 1.4 */
434     private long reconcileState() {
435 dl 1.65 Phaser rt = root;
436 dl 1.57 long s = state;
437 dl 1.65 if (rt != this) {
438     int phase;
439     while ((phase = (int)(rt.state >>> PHASE_SHIFT)) !=
440     (int)(s >>> PHASE_SHIFT)) {
441     // assert phase < 0 || unarrivedOf(s) == 0
442     long t; // to reread s
443     long p = s & PARTIES_MASK; // unshifted parties field
444     long n = (((long) phase) << PHASE_SHIFT) | p;
445     if (phase >= 0) {
446     if (p == 0L)
447     n |= EMPTY; // reset to empty
448     else
449     n |= p >>> PARTIES_SHIFT; // set unarr to parties
450 dl 1.57 }
451 dl 1.65 if ((t = state) == s &&
452     UNSAFE.compareAndSwapLong(this, stateOffset, s, s = n))
453     break;
454     s = t;
455 dl 1.4 }
456     }
457 dl 1.57 return s;
458 dl 1.1 }
459    
460     /**
461 dl 1.63 * Creates a new phaser with no initially registered parties, no
462     * parent, and initial phase number 0. Any thread using this
463     * phaser will need to first register for it.
464 dl 1.1 */
465     public Phaser() {
466 dl 1.50 this(null, 0);
467 dl 1.1 }
468    
469     /**
470 dl 1.63 * Creates a new phaser with the given number of registered
471     * unarrived parties, no parent, and initial phase number 0.
472 jsr166 1.14 *
473 dl 1.63 * @param parties the number of parties required to advance to the
474     * next phase
475 dl 1.1 * @throws IllegalArgumentException if parties less than zero
476 jsr166 1.14 * or greater than the maximum number of parties supported
477 dl 1.1 */
478     public Phaser(int parties) {
479 dl 1.4 this(null, parties);
480     }
481    
482     /**
483 dl 1.58 * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
484 jsr166 1.14 *
485 dl 1.63 * @param parent the parent phaser
486 dl 1.4 */
487     public Phaser(Phaser parent) {
488 dl 1.50 this(parent, 0);
489 dl 1.4 }
490    
491     /**
492 dl 1.63 * Creates a new phaser with the given parent and number of
493 dl 1.60 * registered unarrived parties. Registration and deregistration
494 dl 1.63 * of this child phaser with its parent are managed automatically.
495     * If the given parent is non-null, whenever this child phaser has
496 dl 1.60 * any registered parties (as established in this constructor,
497 dl 1.63 * {@link #register}, or {@link #bulkRegister}), this child phaser
498 dl 1.60 * is registered with its parent. Whenever the number of
499     * registered parties becomes zero as the result of an invocation
500 dl 1.63 * of {@link #arriveAndDeregister}, this child phaser is
501 dl 1.60 * deregistered from its parent.
502 jsr166 1.14 *
503 dl 1.63 * @param parent the parent phaser
504     * @param parties the number of parties required to advance to the
505     * next phase
506 dl 1.4 * @throws IllegalArgumentException if parties less than zero
507 jsr166 1.14 * or greater than the maximum number of parties supported
508 dl 1.4 */
509     public Phaser(Phaser parent, int parties) {
510 dl 1.55 if (parties >>> PARTIES_SHIFT != 0)
511 dl 1.1 throw new IllegalArgumentException("Illegal number of parties");
512 dl 1.65 int phase = 0;
513 dl 1.4 this.parent = parent;
514     if (parent != null) {
515 dl 1.50 Phaser r = parent.root;
516     this.root = r;
517     this.evenQ = r.evenQ;
518     this.oddQ = r.oddQ;
519 dl 1.60 if (parties != 0)
520 dl 1.65 phase = parent.doRegister(1);
521 dl 1.4 }
522 dl 1.50 else {
523 dl 1.4 this.root = this;
524 dl 1.50 this.evenQ = new AtomicReference<QNode>();
525     this.oddQ = new AtomicReference<QNode>();
526     }
527 jsr166 1.66 this.state = (parties == 0) ? ((long) EMPTY) :
528 dl 1.65 ((((long) phase) << PHASE_SHIFT) |
529     (((long) parties) << PARTIES_SHIFT) |
530     ((long) parties));
531 dl 1.1 }
532    
533     /**
534 dl 1.63 * Adds a new unarrived party to this phaser. If an ongoing
535 dl 1.59 * invocation of {@link #onAdvance} is in progress, this method
536 dl 1.63 * may await its completion before returning. If this phaser has
537     * a parent, and this phaser previously had no registered parties,
538     * this phaser is also registered with its parent.
539 jsr166 1.14 *
540 dl 1.35 * @return the arrival phase number to which this registration applied
541 dl 1.1 * @throws IllegalStateException if attempting to register more
542 jsr166 1.14 * than the maximum supported number of parties
543 dl 1.1 */
544 dl 1.4 public int register() {
545     return doRegister(1);
546     }
547    
548     /**
549 dl 1.63 * Adds the given number of new unarrived parties to this phaser.
550 dl 1.49 * If an ongoing invocation of {@link #onAdvance} is in progress,
551 dl 1.60 * this method may await its completion before returning. If this
552 dl 1.63 * phaser has a parent, and the given number of parities is
553     * greater than zero, and this phaser previously had no registered
554     * parties, this phaser is also registered with its parent.
555 jsr166 1.14 *
556 dl 1.63 * @param parties the number of additional parties required to
557     * advance to the next phase
558 dl 1.35 * @return the arrival phase number to which this registration applied
559 dl 1.4 * @throws IllegalStateException if attempting to register more
560 jsr166 1.14 * than the maximum supported number of parties
561 dl 1.48 * @throws IllegalArgumentException if {@code parties < 0}
562 dl 1.4 */
563     public int bulkRegister(int parties) {
564     if (parties < 0)
565     throw new IllegalArgumentException();
566 dl 1.60 if (parties == 0)
567 dl 1.4 return getPhase();
568     return doRegister(parties);
569     }
570    
571     /**
572 dl 1.63 * Arrives at this phaser, without waiting for others to arrive.
573 dl 1.60 *
574     * <p>It is a usage error for an unregistered party to invoke this
575     * method. However, this error may result in an {@code
576     * IllegalStateException} only upon some subsequent operation on
577 dl 1.63 * this phaser, if ever.
578 dl 1.1 *
579 dl 1.35 * @return the arrival phase number, or a negative value if terminated
580 dl 1.4 * @throws IllegalStateException if not terminated and the number
581 jsr166 1.14 * of unarrived parties would become negative
582 dl 1.1 */
583 dl 1.4 public int arrive() {
584 dl 1.65 return doArrive(false);
585 dl 1.1 }
586    
587     /**
588 dl 1.63 * Arrives at this phaser and deregisters from it without waiting
589 dl 1.60 * for others to arrive. Deregistration reduces the number of
590 dl 1.63 * parties required to advance in future phases. If this phaser
591     * has a parent, and deregistration causes this phaser to have
592     * zero parties, this phaser is also deregistered from its parent.
593 dl 1.60 *
594     * <p>It is a usage error for an unregistered party to invoke this
595     * method. However, this error may result in an {@code
596     * IllegalStateException} only upon some subsequent operation on
597 dl 1.63 * this phaser, if ever.
598 dl 1.1 *
599 dl 1.35 * @return the arrival phase number, or a negative value if terminated
600 dl 1.4 * @throws IllegalStateException if not terminated and the number
601 jsr166 1.14 * of registered or unarrived parties would become negative
602 dl 1.1 */
603 dl 1.4 public int arriveAndDeregister() {
604 dl 1.65 return doArrive(true);
605 dl 1.1 }
606    
607     /**
608 dl 1.63 * Arrives at this phaser and awaits others. Equivalent in effect
609 dl 1.27 * to {@code awaitAdvance(arrive())}. If you need to await with
610     * interruption or timeout, you can arrange this with an analogous
611 dl 1.48 * construction using one of the other forms of the {@code
612     * awaitAdvance} method. If instead you need to deregister upon
613 dl 1.60 * arrival, use {@code awaitAdvance(arriveAndDeregister())}.
614     *
615     * <p>It is a usage error for an unregistered party to invoke this
616     * method. However, this error may result in an {@code
617     * IllegalStateException} only upon some subsequent operation on
618 dl 1.63 * this phaser, if ever.
619 jsr166 1.14 *
620 dl 1.35 * @return the arrival phase number, or a negative number if terminated
621 dl 1.4 * @throws IllegalStateException if not terminated and the number
622 jsr166 1.14 * of unarrived parties would become negative
623 dl 1.1 */
624     public int arriveAndAwaitAdvance() {
625 dl 1.65 return awaitAdvance(doArrive(false));
626 dl 1.1 }
627    
628     /**
629 dl 1.63 * Awaits the phase of this phaser to advance from the given phase
630     * value, returning immediately if the current phase is not equal
631     * to the given phase value or this phaser is terminated.
632 jsr166 1.14 *
633 dl 1.35 * @param phase an arrival phase number, or negative value if
634     * terminated; this argument is normally the value returned by a
635 dl 1.63 * previous call to {@code arrive} or {@code arriveAndDeregister}.
636 dl 1.35 * @return the next arrival phase number, or a negative value
637     * if terminated or argument is negative
638 dl 1.1 */
639     public int awaitAdvance(int phase) {
640 dl 1.62 Phaser rt;
641 dl 1.60 int p = (int)(state >>> PHASE_SHIFT);
642 dl 1.1 if (phase < 0)
643     return phase;
644 dl 1.65 if (p == phase) {
645     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase)
646     return rt.internalAwaitAdvance(phase, null);
647     reconcileState();
648     }
649 dl 1.60 return p;
650 dl 1.1 }
651    
652     /**
653 dl 1.63 * Awaits the phase of this phaser to advance from the given phase
654 dl 1.38 * value, throwing {@code InterruptedException} if interrupted
655 dl 1.63 * while waiting, or returning immediately if the current phase is
656     * not equal to the given phase value or this phaser is
657     * terminated.
658 jsr166 1.14 *
659 dl 1.35 * @param phase an arrival phase number, or negative value if
660     * terminated; this argument is normally the value returned by a
661 dl 1.63 * previous call to {@code arrive} or {@code arriveAndDeregister}.
662 dl 1.35 * @return the next arrival phase number, or a negative value
663     * if terminated or argument is negative
664 dl 1.1 * @throws InterruptedException if thread interrupted while waiting
665     */
666 jsr166 1.12 public int awaitAdvanceInterruptibly(int phase)
667 dl 1.10 throws InterruptedException {
668 dl 1.62 Phaser rt;
669 dl 1.60 int p = (int)(state >>> PHASE_SHIFT);
670 dl 1.1 if (phase < 0)
671     return phase;
672 dl 1.65 if (p == phase) {
673     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
674     QNode node = new QNode(this, phase, true, false, 0L);
675     p = rt.internalAwaitAdvance(phase, node);
676     if (node.wasInterrupted)
677     throw new InterruptedException();
678     }
679     else
680     reconcileState();
681 dl 1.55 }
682     return p;
683 dl 1.1 }
684    
685     /**
686 dl 1.63 * Awaits the phase of this phaser to advance from the given phase
687 dl 1.38 * value or the given timeout to elapse, throwing {@code
688     * InterruptedException} if interrupted while waiting, or
689 dl 1.63 * returning immediately if the current phase is not equal to the
690     * given phase value or this phaser is terminated.
691 jsr166 1.14 *
692 dl 1.35 * @param phase an arrival phase number, or negative value if
693     * terminated; this argument is normally the value returned by a
694 dl 1.63 * previous call to {@code arrive} or {@code arriveAndDeregister}.
695 dl 1.31 * @param timeout how long to wait before giving up, in units of
696     * {@code unit}
697     * @param unit a {@code TimeUnit} determining how to interpret the
698     * {@code timeout} parameter
699 dl 1.35 * @return the next arrival phase number, or a negative value
700     * if terminated or argument is negative
701 dl 1.1 * @throws InterruptedException if thread interrupted while waiting
702     * @throws TimeoutException if timed out while waiting
703     */
704 jsr166 1.18 public int awaitAdvanceInterruptibly(int phase,
705     long timeout, TimeUnit unit)
706 dl 1.1 throws InterruptedException, TimeoutException {
707 dl 1.60 long nanos = unit.toNanos(timeout);
708 dl 1.62 Phaser rt;
709 dl 1.60 int p = (int)(state >>> PHASE_SHIFT);
710 dl 1.1 if (phase < 0)
711     return phase;
712 dl 1.65 if (p == phase) {
713     if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
714     QNode node = new QNode(this, phase, true, true, nanos);
715     p = rt.internalAwaitAdvance(phase, node);
716     if (node.wasInterrupted)
717     throw new InterruptedException();
718     else if (p == phase)
719     throw new TimeoutException();
720     }
721     else
722     reconcileState();
723 dl 1.55 }
724     return p;
725 dl 1.1 }
726    
727     /**
728 dl 1.63 * Forces this phaser to enter termination state. Counts of
729 dl 1.65 * registered parties are unaffected. If this phaser is a member
730     * of a tiered set of phasers, then all of the phasers in the set
731     * are terminated. If this phaser is already terminated, this
732     * method has no effect. This method may be useful for
733     * coordinating recovery after one or more tasks encounter
734     * unexpected exceptions.
735 dl 1.1 */
736     public void forceTermination() {
737 dl 1.55 // Only need to change root state
738     final Phaser root = this.root;
739 dl 1.49 long s;
740 dl 1.55 while ((s = root.state) >= 0) {
741 dl 1.65 long next = (s & ~(long)(MAX_PARTIES)) | TERMINATION_BIT;
742     if (UNSAFE.compareAndSwapLong(root, stateOffset, s, next)) {
743 dl 1.55 releaseWaiters(0); // signal all threads
744     releaseWaiters(1);
745     return;
746     }
747     }
748 dl 1.1 }
749    
750     /**
751 dl 1.4 * Returns the current phase number. The maximum phase number is
752 jsr166 1.7 * {@code Integer.MAX_VALUE}, after which it restarts at
753 dl 1.63 * zero. Upon termination, the phase number is negative,
754     * in which case the prevailing phase prior to termination
755     * may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
756 jsr166 1.14 *
757 dl 1.4 * @return the phase number, or a negative value if terminated
758 dl 1.1 */
759 dl 1.4 public final int getPhase() {
760 dl 1.57 return (int)(root.state >>> PHASE_SHIFT);
761 dl 1.1 }
762    
763     /**
764 dl 1.63 * Returns the number of parties registered at this phaser.
765 jsr166 1.14 *
766 dl 1.1 * @return the number of parties
767     */
768     public int getRegisteredParties() {
769 dl 1.57 return partiesOf(state);
770 dl 1.1 }
771    
772     /**
773 dl 1.36 * Returns the number of registered parties that have arrived at
774 dl 1.63 * the current phase of this phaser.
775 jsr166 1.14 *
776 dl 1.1 * @return the number of arrived parties
777     */
778     public int getArrivedParties() {
779 dl 1.65 return arrivedOf(reconcileState());
780 dl 1.1 }
781    
782     /**
783     * Returns the number of registered parties that have not yet
784 dl 1.63 * arrived at the current phase of this phaser.
785 jsr166 1.14 *
786 dl 1.1 * @return the number of unarrived parties
787     */
788     public int getUnarrivedParties() {
789 dl 1.65 return unarrivedOf(reconcileState());
790 dl 1.4 }
791    
792     /**
793 dl 1.63 * Returns the parent of this phaser, or {@code null} if none.
794 jsr166 1.14 *
795 dl 1.63 * @return the parent of this phaser, or {@code null} if none
796 dl 1.4 */
797     public Phaser getParent() {
798     return parent;
799     }
800    
801     /**
802 dl 1.63 * Returns the root ancestor of this phaser, which is the same as
803     * this phaser if it has no parent.
804 jsr166 1.14 *
805 dl 1.63 * @return the root ancestor of this phaser
806 dl 1.4 */
807     public Phaser getRoot() {
808     return root;
809 dl 1.1 }
810    
811     /**
812 dl 1.63 * Returns {@code true} if this phaser has been terminated.
813 jsr166 1.14 *
814 dl 1.63 * @return {@code true} if this phaser has been terminated
815 dl 1.1 */
816     public boolean isTerminated() {
817 dl 1.57 return root.state < 0L;
818 dl 1.1 }
819    
820     /**
821 dl 1.43 * Overridable method to perform an action upon impending phase
822     * advance, and to control termination. This method is invoked
823 dl 1.63 * upon arrival of the party advancing this phaser (when all other
824 dl 1.43 * waiting parties are dormant). If this method returns {@code
825 dl 1.65 * true}, this phaser will be set to a final termination state
826     * upon advance, and subsequent calls to {@link #isTerminated}
827     * will return true. Any (unchecked) Exception or Error thrown by
828     * an invocation of this method is propagated to the party
829     * attempting to advance this phaser, in which case no advance
830     * occurs.
831 dl 1.42 *
832 dl 1.63 * <p>The arguments to this method provide the state of the phaser
833 dl 1.51 * prevailing for the current transition. The effects of invoking
834 dl 1.63 * arrival, registration, and waiting methods on this phaser from
835 dl 1.50 * within {@code onAdvance} are unspecified and should not be
836 dl 1.51 * relied on.
837     *
838 dl 1.63 * <p>If this phaser is a member of a tiered set of phasers, then
839     * {@code onAdvance} is invoked only for its root phaser on each
840 dl 1.51 * advance.
841 jsr166 1.3 *
842 dl 1.59 * <p>To support the most common use cases, the default
843     * implementation of this method returns {@code true} when the
844     * number of registered parties has become zero as the result of a
845     * party invoking {@code arriveAndDeregister}. You can disable
846     * this behavior, thus enabling continuation upon future
847     * registrations, by overriding this method to always return
848     * {@code false}:
849     *
850     * <pre> {@code
851     * Phaser phaser = new Phaser() {
852     * protected boolean onAdvance(int phase, int parties) { return false; }
853     * }}</pre>
854 dl 1.1 *
855 dl 1.63 * @param phase the current phase number on entry to this method,
856     * before this phaser is advanced
857 jsr166 1.9 * @param registeredParties the current number of registered parties
858 dl 1.63 * @return {@code true} if this phaser should terminate
859 dl 1.1 */
860     protected boolean onAdvance(int phase, int registeredParties) {
861 dl 1.62 return registeredParties == 0;
862 dl 1.1 }
863    
864     /**
865 dl 1.63 * Returns a string identifying this phaser, as well as its
866 dl 1.1 * state. The state, in brackets, includes the String {@code
867 jsr166 1.9 * "phase = "} followed by the phase number, {@code "parties = "}
868 dl 1.1 * followed by the number of registered parties, and {@code
869 jsr166 1.9 * "arrived = "} followed by the number of arrived parties.
870 dl 1.1 *
871 dl 1.63 * @return a string identifying this phaser, as well as its state
872 dl 1.1 */
873     public String toString() {
874 dl 1.54 return stateToString(reconcileState());
875     }
876    
877     /**
878     * Implementation of toString and string-based error messages
879     */
880     private String stateToString(long s) {
881 jsr166 1.9 return super.toString() +
882     "[phase = " + phaseOf(s) +
883     " parties = " + partiesOf(s) +
884     " arrived = " + arrivedOf(s) + "]";
885 dl 1.1 }
886    
887 dl 1.54 // Waiting mechanics
888    
889 dl 1.4 /**
890 dl 1.57 * Removes and signals threads from queue for phase.
891 dl 1.4 */
892     private void releaseWaiters(int phase) {
893 dl 1.63 QNode q; // first element of queue
894     int p; // its phase
895     Thread t; // its thread
896 dl 1.65 // assert phase != phaseOf(root.state);
897 dl 1.62 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
898 dl 1.51 while ((q = head.get()) != null &&
899 dl 1.65 q.phase != (int)(root.state >>> PHASE_SHIFT)) {
900 dl 1.63 if (head.compareAndSet(q, q.next) &&
901     (t = q.thread) != null) {
902     q.thread = null;
903     LockSupport.unpark(t);
904     }
905 dl 1.4 }
906     }
907    
908 dl 1.51 /** The number of CPUs, for spin control */
909     private static final int NCPU = Runtime.getRuntime().availableProcessors();
910    
911 dl 1.10 /**
912 dl 1.51 * The number of times to spin before blocking while waiting for
913     * advance, per arrival while waiting. On multiprocessors, fully
914     * blocking and waking up a large number of threads all at once is
915     * usually a very slow process, so we use rechargeable spins to
916     * avoid it when threads regularly arrive: When a thread in
917     * internalAwaitAdvance notices another arrival before blocking,
918     * and there appear to be enough CPUs available, it spins
919 dl 1.62 * SPINS_PER_ARRIVAL more times before blocking. The value trades
920     * off good-citizenship vs big unnecessary slowdowns.
921 dl 1.50 */
922 dl 1.55 static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
923 dl 1.50
924     /**
925 dl 1.51 * Possibly blocks and waits for phase to advance unless aborted.
926 dl 1.60 * Call only from root node.
927 jsr166 1.14 *
928 dl 1.51 * @param phase current phase
929 jsr166 1.53 * @param node if non-null, the wait node to track interrupt and timeout;
930 dl 1.51 * if null, denotes noninterruptible wait
931 dl 1.10 * @return current phase
932 dl 1.1 */
933 dl 1.51 private int internalAwaitAdvance(int phase, QNode node) {
934 dl 1.63 releaseWaiters(phase-1); // ensure old queue clean
935     boolean queued = false; // true when node is enqueued
936     int lastUnarrived = 0; // to increase spins upon change
937 dl 1.51 int spins = SPINS_PER_ARRIVAL;
938 dl 1.57 long s;
939     int p;
940 dl 1.60 while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
941 dl 1.63 if (node == null) { // spinning in noninterruptible mode
942     int unarrived = (int)s & UNARRIVED_MASK;
943     if (unarrived != lastUnarrived &&
944     (lastUnarrived = unarrived) < NCPU)
945 dl 1.57 spins += SPINS_PER_ARRIVAL;
946 dl 1.63 boolean interrupted = Thread.interrupted();
947     if (interrupted || --spins < 0) { // need node to record intr
948     node = new QNode(this, phase, false, false, 0L);
949     node.wasInterrupted = interrupted;
950     }
951 dl 1.54 }
952 dl 1.63 else if (node.isReleasable()) // done or aborted
953     break;
954     else if (!queued) { // push onto queue
955 dl 1.62 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
956 dl 1.63 QNode q = node.next = head.get();
957     if ((q == null || q.phase == phase) &&
958     (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
959 dl 1.62 queued = head.compareAndSet(q, node);
960 dl 1.57 }
961 dl 1.51 else {
962     try {
963     ForkJoinPool.managedBlock(node);
964     } catch (InterruptedException ie) {
965     node.wasInterrupted = true;
966     }
967     }
968 dl 1.4 }
969 dl 1.60
970     if (node != null) {
971     if (node.thread != null)
972 dl 1.63 node.thread = null; // avoid need for unpark()
973 dl 1.62 if (node.wasInterrupted && !node.interruptible)
974 dl 1.60 Thread.currentThread().interrupt();
975 dl 1.65 if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
976 dl 1.63 return p; // recheck abort
977 dl 1.60 }
978 dl 1.63 releaseWaiters(phase);
979 dl 1.57 return p;
980 dl 1.4 }
981    
982     /**
983 dl 1.51 * Wait nodes for Treiber stack representing wait queue
984 dl 1.4 */
985 dl 1.51 static final class QNode implements ForkJoinPool.ManagedBlocker {
986     final Phaser phaser;
987     final int phase;
988     final boolean interruptible;
989     final boolean timed;
990     boolean wasInterrupted;
991     long nanos;
992     long lastTime;
993     volatile Thread thread; // nulled to cancel wait
994     QNode next;
995    
996     QNode(Phaser phaser, int phase, boolean interruptible,
997     boolean timed, long nanos) {
998     this.phaser = phaser;
999     this.phase = phase;
1000     this.interruptible = interruptible;
1001     this.nanos = nanos;
1002     this.timed = timed;
1003 jsr166 1.64 this.lastTime = timed ? System.nanoTime() : 0L;
1004 dl 1.51 thread = Thread.currentThread();
1005     }
1006    
1007     public boolean isReleasable() {
1008 dl 1.63 if (thread == null)
1009     return true;
1010     if (phaser.getPhase() != phase) {
1011     thread = null;
1012     return true;
1013     }
1014     if (Thread.interrupted())
1015     wasInterrupted = true;
1016     if (wasInterrupted && interruptible) {
1017     thread = null;
1018     return true;
1019     }
1020     if (timed) {
1021     if (nanos > 0L) {
1022     long now = System.nanoTime();
1023     nanos -= now - lastTime;
1024     lastTime = now;
1025     }
1026     if (nanos <= 0L) {
1027     thread = null;
1028     return true;
1029 dl 1.51 }
1030 dl 1.50 }
1031 dl 1.63 return false;
1032 dl 1.51 }
1033    
1034     public boolean block() {
1035     if (isReleasable())
1036     return true;
1037     else if (!timed)
1038     LockSupport.park(this);
1039     else if (nanos > 0)
1040     LockSupport.parkNanos(this, nanos);
1041     return isReleasable();
1042 dl 1.1 }
1043 dl 1.4 }
1044    
1045 jsr166 1.22 // Unsafe mechanics
1046    
1047     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1048     private static final long stateOffset =
1049     objectFieldOffset("state", Phaser.class);
1050    
1051     private static long objectFieldOffset(String field, Class<?> klazz) {
1052     try {
1053     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1054     } catch (NoSuchFieldException e) {
1055     // Convert Exception to corresponding Error
1056     NoSuchFieldError error = new NoSuchFieldError(field);
1057     error.initCause(e);
1058     throw error;
1059     }
1060     }
1061    
1062     /**
1063     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1064     * Replace with a simple call to Unsafe.getUnsafe when integrating
1065     * into a jdk.
1066     *
1067     * @return a sun.misc.Unsafe
1068     */
1069 jsr166 1.19 private static sun.misc.Unsafe getUnsafe() {
1070 jsr166 1.11 try {
1071 jsr166 1.19 return sun.misc.Unsafe.getUnsafe();
1072 jsr166 1.11 } catch (SecurityException se) {
1073     try {
1074     return java.security.AccessController.doPrivileged
1075 jsr166 1.22 (new java.security
1076     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1077 jsr166 1.19 public sun.misc.Unsafe run() throws Exception {
1078 jsr166 1.22 java.lang.reflect.Field f = sun.misc
1079     .Unsafe.class.getDeclaredField("theUnsafe");
1080     f.setAccessible(true);
1081     return (sun.misc.Unsafe) f.get(null);
1082 jsr166 1.11 }});
1083     } catch (java.security.PrivilegedActionException e) {
1084 jsr166 1.19 throw new RuntimeException("Could not initialize intrinsics",
1085     e.getCause());
1086 jsr166 1.11 }
1087     }
1088     }
1089 dl 1.1 }