ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.49
Committed: Fri Nov 5 23:01:47 2010 UTC (13 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.48: +98 -126 lines
Log Message:
Suppress register on advance; share root queues; misc touchups

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.1 import java.util.concurrent.*;
10 jsr166 1.20 import java.util.concurrent.atomic.AtomicReference;
11 dl 1.1 import java.util.concurrent.locks.LockSupport;
12    
13     /**
14 jsr166 1.37 * A reusable synchronization barrier, similar in functionality to
15 jsr166 1.9 * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
16     * {@link java.util.concurrent.CountDownLatch CountDownLatch}
17     * but supporting more flexible usage.
18 dl 1.1 *
19 dl 1.38 * <p> <b>Registration.</b> Unlike the case for other barriers, the
20     * number of parties <em>registered</em> to synchronize on a phaser
21     * may vary over time. Tasks may be registered at any time (using
22     * methods {@link #register}, {@link #bulkRegister}, or forms of
23     * constructors establishing initial numbers of parties), and
24     * optionally deregistered upon any arrival (using {@link
25 dl 1.35 * #arriveAndDeregister}). As is the case with most basic
26     * synchronization constructs, registration and deregistration affect
27     * only internal counts; they do not establish any further internal
28 jsr166 1.37 * bookkeeping, so tasks cannot query whether they are registered.
29     * (However, you can introduce such bookkeeping by subclassing this
30     * class.)
31 dl 1.1 *
32 dl 1.38 * <p> <b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
33     * Phaser} may be repeatedly awaited. Method {@link
34     * #arriveAndAwaitAdvance} has effect analogous to {@link
35     * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
36     * generation of a {@code Phaser} has an associated phase number. The
37 dl 1.39 * phase number starts at zero, and advances when all parties arrive
38 dl 1.38 * at the barrier, wrapping around to zero after reaching {@code
39     * Integer.MAX_VALUE}. The use of phase numbers enables independent
40     * control of actions upon arrival at a barrier and upon awaiting
41     * others, via two kinds of methods that may be invoked by any
42     * registered party:
43 dl 1.1 *
44     * <ul>
45     *
46 dl 1.38 * <li> <b>Arrival.</b> Methods {@link #arrive} and
47     * {@link #arriveAndDeregister} record arrival at a
48     * barrier. These methods do not block, but return an associated
49     * <em>arrival phase number</em>; that is, the phase number of
50     * the barrier to which the arrival applied. When the final
51     * party for a given phase arrives, an optional barrier action
52     * is performed and the phase advances. Barrier actions,
53     * performed by the party triggering a phase advance, are
54     * arranged by overriding method {@link #onAdvance(int, int)},
55     * which also controls termination. Overriding this method is
56     * similar to, but more flexible than, providing a barrier
57     * action to a {@code CyclicBarrier}.
58     *
59     * <li> <b>Waiting.</b> Method {@link #awaitAdvance} requires an
60     * argument indicating an arrival phase number, and returns when
61     * the barrier advances to (or is already at) a different phase.
62     * Unlike similar constructions using {@code CyclicBarrier},
63     * method {@code awaitAdvance} continues to wait even if the
64 dl 1.39 * waiting thread is interrupted. Interruptible and timeout
65     * versions are also available, but exceptions encountered while
66 dl 1.38 * tasks wait interruptibly or with timeout do not change the
67     * state of the barrier. If necessary, you can perform any
68     * associated recovery within handlers of those exceptions,
69     * often after invoking {@code forceTermination}. Phasers may
70     * also be used by tasks executing in a {@link ForkJoinPool},
71     * which will ensure sufficient parallelism to execute tasks
72     * when others are blocked waiting for a phase to advance.
73     *
74 dl 1.1 * </ul>
75     *
76 dl 1.38 * <p> <b>Termination.</b> A {@code Phaser} may enter a
77 dl 1.39 * <em>termination</em> state in which all synchronization methods
78     * immediately return without updating phaser state or waiting for
79     * advance, and indicating (via a negative phase value) that execution
80     * is complete. Termination is triggered when an invocation of {@code
81     * onAdvance} returns {@code true}. As illustrated below, when
82     * phasers control actions with a fixed number of iterations, it is
83     * often convenient to override this method to cause termination when
84     * the current phase number reaches a threshold. Method {@link
85     * #forceTermination} is also available to abruptly release waiting
86     * threads and allow them to terminate.
87 dl 1.4 *
88 dl 1.38 * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e., arranged
89     * in tree structures) to reduce contention. Phasers with large
90 dl 1.4 * numbers of parties that would otherwise experience heavy
91 dl 1.38 * synchronization contention costs may instead be set up so that
92     * groups of sub-phasers share a common parent. This may greatly
93     * increase throughput even though it incurs greater per-operation
94     * overhead.
95     *
96     * <p><b>Monitoring.</b> While synchronization methods may be invoked
97     * only by registered parties, the current state of a phaser may be
98     * monitored by any caller. At any given moment there are {@link
99 dl 1.40 * #getRegisteredParties} parties in total, of which {@link
100     * #getArrivedParties} have arrived at the current phase ({@link
101     * #getPhase}). When the remaining ({@link #getUnarrivedParties})
102 dl 1.42 * parties arrive, the phase advances. The values returned by these
103     * methods may reflect transient states and so are not in general
104     * useful for synchronization control. Method {@link #toString}
105     * returns snapshots of these state queries in a form convenient for
106     * informal monitoring.
107 dl 1.1 *
108 dl 1.4 * <p><b>Sample usages:</b>
109     *
110 jsr166 1.24 * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
111 dl 1.48 * to control a one-shot action serving a variable number of parties.
112     * The typical idiom is for the method setting this up to first
113     * register, then start the actions, then deregister, as in:
114 dl 1.1 *
115 jsr166 1.13 * <pre> {@code
116 jsr166 1.33 * void runTasks(List<Runnable> tasks) {
117 jsr166 1.13 * final Phaser phaser = new Phaser(1); // "1" to register self
118 dl 1.27 * // create and start threads
119 jsr166 1.33 * for (Runnable task : tasks) {
120 jsr166 1.13 * phaser.register();
121     * new Thread() {
122     * public void run() {
123     * phaser.arriveAndAwaitAdvance(); // await all creation
124 jsr166 1.33 * task.run();
125 jsr166 1.13 * }
126     * }.start();
127 dl 1.4 * }
128 dl 1.6 *
129 dl 1.27 * // allow threads to start and deregister self
130     * phaser.arriveAndDeregister();
131 jsr166 1.13 * }}</pre>
132 dl 1.1 *
133 dl 1.4 * <p>One way to cause a set of threads to repeatedly perform actions
134 jsr166 1.7 * for a given number of iterations is to override {@code onAdvance}:
135 dl 1.1 *
136 jsr166 1.13 * <pre> {@code
137 jsr166 1.33 * void startTasks(List<Runnable> tasks, final int iterations) {
138 jsr166 1.13 * final Phaser phaser = new Phaser() {
139 dl 1.38 * protected boolean onAdvance(int phase, int registeredParties) {
140 jsr166 1.13 * return phase >= iterations || registeredParties == 0;
141     * }
142     * };
143     * phaser.register();
144 jsr166 1.45 * for (final Runnable task : tasks) {
145 jsr166 1.13 * phaser.register();
146     * new Thread() {
147     * public void run() {
148     * do {
149 jsr166 1.33 * task.run();
150 jsr166 1.13 * phaser.arriveAndAwaitAdvance();
151 jsr166 1.45 * } while (!phaser.isTerminated());
152 dl 1.4 * }
153 jsr166 1.13 * }.start();
154 dl 1.1 * }
155 dl 1.4 * phaser.arriveAndDeregister(); // deregister self, don't wait
156 jsr166 1.13 * }}</pre>
157 dl 1.1 *
158 dl 1.38 * If the main task must later await termination, it
159     * may re-register and then execute a similar loop:
160 jsr166 1.45 * <pre> {@code
161 dl 1.38 * // ...
162     * phaser.register();
163     * while (!phaser.isTerminated())
164 jsr166 1.45 * phaser.arriveAndAwaitAdvance();}</pre>
165 dl 1.38 *
166 jsr166 1.45 * <p>Related constructions may be used to await particular phase numbers
167 dl 1.38 * in contexts where you are sure that the phase will never wrap around
168     * {@code Integer.MAX_VALUE}. For example:
169     *
170 jsr166 1.45 * <pre> {@code
171     * void awaitPhase(Phaser phaser, int phase) {
172     * int p = phaser.register(); // assumes caller not already registered
173     * while (p < phase) {
174     * if (phaser.isTerminated())
175     * // ... deal with unexpected termination
176     * else
177     * p = phaser.arriveAndAwaitAdvance();
178 dl 1.38 * }
179 jsr166 1.45 * phaser.arriveAndDeregister();
180     * }}</pre>
181 dl 1.38 *
182     *
183 jsr166 1.25 * <p>To create a set of tasks using a tree of phasers,
184 dl 1.4 * you could use code of the following form, assuming a
185 jsr166 1.24 * Task class with a constructor accepting a phaser that
186 dl 1.48 * it registers with upon construction:
187 jsr166 1.45 *
188 jsr166 1.13 * <pre> {@code
189 dl 1.44 * void build(Task[] actions, int lo, int hi, Phaser ph) {
190     * if (hi - lo > TASKS_PER_PHASER) {
191     * for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
192     * int j = Math.min(i + TASKS_PER_PHASER, hi);
193     * build(actions, i, j, new Phaser(ph));
194 jsr166 1.13 * }
195     * } else {
196     * for (int i = lo; i < hi; ++i)
197 dl 1.44 * actions[i] = new Task(ph);
198     * // assumes new Task(ph) performs ph.register()
199 jsr166 1.13 * }
200     * }
201     * // .. initially called, for n tasks via
202     * build(new Task[n], 0, n, new Phaser());}</pre>
203 dl 1.4 *
204 jsr166 1.7 * The best value of {@code TASKS_PER_PHASER} depends mainly on
205 dl 1.4 * expected barrier synchronization rates. A value as low as four may
206     * be appropriate for extremely small per-barrier task bodies (thus
207     * high rates), or up to hundreds for extremely large ones.
208     *
209 dl 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
210 dl 1.4 * maximum number of parties to 65535. Attempts to register additional
211 jsr166 1.32 * parties result in {@code IllegalStateException}. However, you can and
212 dl 1.4 * should create tiered phasers to accommodate arbitrarily large sets
213     * of participants.
214 jsr166 1.16 *
215     * @since 1.7
216     * @author Doug Lea
217 dl 1.1 */
218     public class Phaser {
219     /*
220     * This class implements an extension of X10 "clocks". Thanks to
221 dl 1.4 * Vijay Saraswat for the idea, and to Vivek Sarkar for
222     * enhancements to extend functionality.
223 dl 1.1 */
224    
225     /**
226     * Barrier state representation. Conceptually, a barrier contains
227     * four values:
228 jsr166 1.3 *
229 dl 1.1 * * parties -- the number of parties to wait (16 bits)
230     * * unarrived -- the number of parties yet to hit barrier (16 bits)
231     * * phase -- the generation of the barrier (31 bits)
232     * * terminated -- set if barrier is terminated (1 bit)
233     *
234     * However, to efficiently maintain atomicity, these values are
235 dl 1.4 * packed into a single (atomic) long. Termination uses the sign
236     * bit of 32 bit representation of phase, so phase is set to -1 on
237 jsr166 1.8 * termination. Good performance relies on keeping state decoding
238 dl 1.4 * and encoding simple, and keeping race windows short.
239     *
240     * Note: there are some cheats in arrive() that rely on unarrived
241 dl 1.10 * count being lowest 16 bits.
242 dl 1.1 */
243 dl 1.4 private volatile long state;
244 dl 1.1
245 dl 1.10 private static final int ushortMask = 0xffff;
246     private static final int phaseMask = 0x7fffffff;
247 dl 1.1
248     private static int unarrivedOf(long s) {
249 jsr166 1.18 return (int) (s & ushortMask);
250 dl 1.1 }
251    
252     private static int partiesOf(long s) {
253 jsr166 1.17 return ((int) s) >>> 16;
254 dl 1.1 }
255    
256     private static int phaseOf(long s) {
257 jsr166 1.17 return (int) (s >>> 32);
258 dl 1.1 }
259    
260     private static int arrivedOf(long s) {
261     return partiesOf(s) - unarrivedOf(s);
262     }
263    
264     private static long stateFor(int phase, int parties, int unarrived) {
265 jsr166 1.17 return ((((long) phase) << 32) | (((long) parties) << 16) |
266     (long) unarrived);
267 dl 1.1 }
268    
269 dl 1.4 private static long trippedStateFor(int phase, int parties) {
270 jsr166 1.17 long lp = (long) parties;
271     return (((long) phase) << 32) | (lp << 16) | lp;
272 dl 1.4 }
273    
274 dl 1.10 /**
275 jsr166 1.14 * Returns message string for bad bounds exceptions.
276 dl 1.10 */
277     private static String badBounds(int parties, int unarrived) {
278     return ("Attempt to set " + unarrived +
279     " unarrived of " + parties + " parties");
280 dl 1.4 }
281    
282     /**
283     * The parent of this phaser, or null if none
284     */
285     private final Phaser parent;
286    
287     /**
288 jsr166 1.24 * The root of phaser tree. Equals this if not in a tree. Used to
289 dl 1.4 * support faster state push-down.
290     */
291     private final Phaser root;
292    
293     // Wait queues
294    
295     /**
296 dl 1.10 * Heads of Treiber stacks for waiting threads. To eliminate
297 dl 1.49 * contention when releasing some threads while adding others, we
298 dl 1.4 * use two of them, alternating across even and odd phases.
299 dl 1.49 * Subphasers share queues with root to speed up releases.
300 dl 1.4 */
301     private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
302     private final AtomicReference<QNode> oddQ = new AtomicReference<QNode>();
303    
304     private AtomicReference<QNode> queueFor(int phase) {
305 dl 1.49 Phaser r = root;
306     return ((phase & 1) == 0) ? r.evenQ : r.oddQ;
307 dl 1.4 }
308    
309     /**
310     * Returns current state, first resolving lagged propagation from
311     * root if necessary.
312     */
313     private long getReconciledState() {
314 jsr166 1.18 return (parent == null) ? state : reconcileState();
315 dl 1.4 }
316    
317     /**
318     * Recursively resolves state.
319     */
320     private long reconcileState() {
321 dl 1.49 Phaser par = parent;
322 dl 1.4 long s = state;
323 dl 1.49 if (par != null) {
324     int phase, rootPhase;
325     while ((phase = phaseOf(s)) >= 0 &&
326     (rootPhase = phaseOf(root.state)) != phase &&
327     (rootPhase < 0 || unarrivedOf(s) == 0)) {
328     long parentState = par.getReconciledState();
329 dl 1.4 int parentPhase = phaseOf(parentState);
330 dl 1.49 int parties = partiesOf(s);
331     long next = trippedStateFor(parentPhase, parties);
332     if (phaseOf(root.state) == rootPhase &&
333     parentPhase != phase &&
334     state == s && casState(s, next)) {
335     releaseWaiters(phase);
336     if (parties == 0) // exit if the final deregistration
337     break;
338 dl 1.4 }
339 dl 1.49 s = state;
340 dl 1.4 }
341     }
342     return s;
343 dl 1.1 }
344    
345     /**
346 jsr166 1.24 * Creates a new phaser without any initially registered parties,
347 dl 1.10 * initial phase number 0, and no parent. Any thread using this
348 jsr166 1.24 * phaser will need to first register for it.
349 dl 1.1 */
350     public Phaser() {
351 dl 1.4 this(null);
352 dl 1.1 }
353    
354     /**
355 dl 1.48 * Creates a new phaser with the given number of registered
356 dl 1.4 * unarrived parties, initial phase number 0, and no parent.
357 jsr166 1.14 *
358     * @param parties the number of parties required to trip barrier
359 dl 1.1 * @throws IllegalArgumentException if parties less than zero
360 jsr166 1.14 * or greater than the maximum number of parties supported
361 dl 1.1 */
362     public Phaser(int parties) {
363 dl 1.4 this(null, parties);
364     }
365    
366     /**
367 jsr166 1.24 * Creates a new phaser with the given parent, without any
368 dl 1.4 * initially registered parties. If parent is non-null this phaser
369     * is registered with the parent and its initial phase number is
370     * the same as that of parent phaser.
371 jsr166 1.14 *
372     * @param parent the parent phaser
373 dl 1.4 */
374     public Phaser(Phaser parent) {
375     int phase = 0;
376     this.parent = parent;
377     if (parent != null) {
378     this.root = parent.root;
379     phase = parent.register();
380     }
381     else
382     this.root = this;
383     this.state = trippedStateFor(phase, 0);
384     }
385    
386     /**
387 dl 1.48 * Creates a new phaser with the given parent and number of
388 jsr166 1.14 * registered unarrived parties. If parent is non-null, this phaser
389 dl 1.4 * is registered with the parent and its initial phase number is
390     * the same as that of parent phaser.
391 jsr166 1.14 *
392     * @param parent the parent phaser
393     * @param parties the number of parties required to trip barrier
394 dl 1.4 * @throws IllegalArgumentException if parties less than zero
395 jsr166 1.14 * or greater than the maximum number of parties supported
396 dl 1.4 */
397     public Phaser(Phaser parent, int parties) {
398 dl 1.1 if (parties < 0 || parties > ushortMask)
399     throw new IllegalArgumentException("Illegal number of parties");
400 dl 1.4 int phase = 0;
401     this.parent = parent;
402     if (parent != null) {
403     this.root = parent.root;
404     phase = parent.register();
405     }
406     else
407     this.root = this;
408     this.state = trippedStateFor(phase, parties);
409 dl 1.1 }
410    
411     /**
412     * Adds a new unarrived party to this phaser.
413 dl 1.49 * If an ongoing invocation of {@link #onAdvance} is in progress,
414     * this method waits until its completion before registering.
415 jsr166 1.14 *
416 dl 1.35 * @return the arrival phase number to which this registration applied
417 dl 1.1 * @throws IllegalStateException if attempting to register more
418 jsr166 1.14 * than the maximum supported number of parties
419 dl 1.1 */
420 dl 1.4 public int register() {
421     return doRegister(1);
422     }
423    
424     /**
425     * Adds the given number of new unarrived parties to this phaser.
426 dl 1.49 * If an ongoing invocation of {@link #onAdvance} is in progress,
427     * this method waits until its completion before registering.
428 jsr166 1.14 *
429 dl 1.48 * @param parties the number of additional parties required to trip barrier
430 dl 1.35 * @return the arrival phase number to which this registration applied
431 dl 1.4 * @throws IllegalStateException if attempting to register more
432 jsr166 1.14 * than the maximum supported number of parties
433 dl 1.48 * @throws IllegalArgumentException if {@code parties < 0}
434 dl 1.4 */
435     public int bulkRegister(int parties) {
436     if (parties < 0)
437     throw new IllegalArgumentException();
438     if (parties == 0)
439     return getPhase();
440     return doRegister(parties);
441     }
442    
443     /**
444     * Shared code for register, bulkRegister
445     */
446     private int doRegister(int registrations) {
447 dl 1.49 Phaser par = parent;
448     long s;
449 dl 1.4 int phase;
450 dl 1.49 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
451     int p = partiesOf(s);
452     int u = unarrivedOf(s);
453     int unarrived = u + registrations;
454     int parties = p + registrations;
455     if (par == null || phase == phaseOf(root.state)) {
456     if (parties > ushortMask || unarrived > ushortMask)
457     throw new IllegalStateException(badBounds(parties,
458     unarrived));
459     else if (p != 0 && u == 0) // back off if advancing
460     Thread.yield(); // not worth actually blocking
461     else if (casState(s, stateFor(phase, parties, unarrived)))
462     break;
463     }
464 dl 1.1 }
465 dl 1.4 return phase;
466 dl 1.1 }
467    
468     /**
469     * Arrives at the barrier, but does not wait for others. (You can
470 dl 1.38 * in turn wait for others via {@link #awaitAdvance}). It is an
471     * unenforced usage error for an unregistered party to invoke this
472     * method.
473 dl 1.1 *
474 dl 1.35 * @return the arrival phase number, or a negative value if terminated
475 dl 1.4 * @throws IllegalStateException if not terminated and the number
476 jsr166 1.14 * of unarrived parties would become negative
477 dl 1.1 */
478 dl 1.4 public int arrive() {
479 dl 1.49 Phaser par = parent;
480     long s;
481 dl 1.4 int phase;
482 dl 1.49 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
483 dl 1.1 int parties = partiesOf(s);
484     int unarrived = unarrivedOf(s) - 1;
485 dl 1.49 if (parties == 0 || unarrived < 0)
486     throw new IllegalStateException(badBounds(parties,
487     unarrived));
488     else if (unarrived > 0) { // Not the last arrival
489     if (casState(s, s - 1)) // s-1 adds one arrival
490 dl 1.4 break;
491     }
492 dl 1.49 else if (par == null) { // directly trip
493     if (casState(s, trippedStateFor(onAdvance(phase, parties) ? -1 :
494     ((phase + 1) & phaseMask),
495     parties))) {
496     releaseWaiters(phase);
497     break;
498 dl 1.4 }
499     }
500 dl 1.49 else if (phaseOf(root.state) == phase && casState(s, s - 1)) {
501     par.arrive(); // cascade to parent
502 dl 1.4 reconcileState();
503 dl 1.49 break;
504     }
505 dl 1.1 }
506 dl 1.4 return phase;
507 dl 1.1 }
508    
509     /**
510 dl 1.27 * Arrives at the barrier and deregisters from it without waiting
511     * for others. Deregistration reduces the number of parties
512 dl 1.4 * required to trip the barrier in future phases. If this phaser
513     * has a parent, and deregistration causes this phaser to have
514 dl 1.27 * zero parties, this phaser also arrives at and is deregistered
515 dl 1.38 * from its parent. It is an unenforced usage error for an
516     * unregistered party to invoke this method.
517 dl 1.1 *
518 dl 1.35 * @return the arrival phase number, or a negative value if terminated
519 dl 1.4 * @throws IllegalStateException if not terminated and the number
520 jsr166 1.14 * of registered or unarrived parties would become negative
521 dl 1.1 */
522 dl 1.4 public int arriveAndDeregister() {
523 dl 1.49 // similar to arrive, but too different to merge
524 dl 1.4 Phaser par = parent;
525 dl 1.49 long s;
526 dl 1.4 int phase;
527 dl 1.49 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
528 dl 1.1 int parties = partiesOf(s) - 1;
529     int unarrived = unarrivedOf(s) - 1;
530 dl 1.49 if (parties < 0 || unarrived < 0)
531     throw new IllegalStateException(badBounds(parties,
532     unarrived));
533     else if (unarrived > 0) {
534     if (casState(s, stateFor(phase, parties, unarrived)))
535     break;
536     }
537     else if (par == null) {
538     if (casState(s, trippedStateFor(onAdvance(phase, parties)? -1:
539     (phase + 1) & phaseMask,
540     parties))) {
541     releaseWaiters(phase);
542     break;
543 dl 1.4 }
544 dl 1.1 }
545 dl 1.49 else if (phaseOf(root.state) == phase &&
546     casState(s, stateFor(phase, parties, 0))) {
547     if (parties == 0)
548     par.arriveAndDeregister();
549     else
550     par.arrive();
551     reconcileState();
552     break;
553     }
554 dl 1.1 }
555 dl 1.4 return phase;
556 dl 1.1 }
557    
558     /**
559 dl 1.4 * Arrives at the barrier and awaits others. Equivalent in effect
560 dl 1.27 * to {@code awaitAdvance(arrive())}. If you need to await with
561     * interruption or timeout, you can arrange this with an analogous
562 dl 1.48 * construction using one of the other forms of the {@code
563     * awaitAdvance} method. If instead you need to deregister upon
564     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
565     * usage error for an unregistered party to invoke this method.
566 jsr166 1.14 *
567 dl 1.35 * @return the arrival phase number, or a negative number if terminated
568 dl 1.4 * @throws IllegalStateException if not terminated and the number
569 jsr166 1.14 * of unarrived parties would become negative
570 dl 1.1 */
571     public int arriveAndAwaitAdvance() {
572 dl 1.4 return awaitAdvance(arrive());
573 dl 1.1 }
574    
575     /**
576 dl 1.27 * Awaits the phase of the barrier to advance from the given phase
577 dl 1.30 * value, returning immediately if the current phase of the
578     * barrier is not equal to the given phase value or this barrier
579 dl 1.38 * is terminated. It is an unenforced usage error for an
580     * unregistered party to invoke this method.
581 jsr166 1.14 *
582 dl 1.35 * @param phase an arrival phase number, or negative value if
583     * terminated; this argument is normally the value returned by a
584     * previous call to {@code arrive} or its variants
585     * @return the next arrival phase number, or a negative value
586     * if terminated or argument is negative
587 dl 1.1 */
588     public int awaitAdvance(int phase) {
589     if (phase < 0)
590     return phase;
591 dl 1.49 int p = getPhase();
592 dl 1.4 if (p != phase)
593     return p;
594     return untimedWait(phase);
595 dl 1.1 }
596    
597     /**
598 dl 1.30 * Awaits the phase of the barrier to advance from the given phase
599 dl 1.38 * value, throwing {@code InterruptedException} if interrupted
600     * while waiting, or returning immediately if the current phase of
601     * the barrier is not equal to the given phase value or this
602     * barrier is terminated. It is an unenforced usage error for an
603     * unregistered party to invoke this method.
604 jsr166 1.14 *
605 dl 1.35 * @param phase an arrival phase number, or negative value if
606     * terminated; this argument is normally the value returned by a
607     * previous call to {@code arrive} or its variants
608     * @return the next arrival phase number, or a negative value
609     * if terminated or argument is negative
610 dl 1.1 * @throws InterruptedException if thread interrupted while waiting
611     */
612 jsr166 1.12 public int awaitAdvanceInterruptibly(int phase)
613 dl 1.10 throws InterruptedException {
614 dl 1.1 if (phase < 0)
615     return phase;
616 dl 1.49 int p = getPhase();
617 dl 1.4 if (p != phase)
618     return p;
619     return interruptibleWait(phase);
620 dl 1.1 }
621    
622     /**
623 dl 1.30 * Awaits the phase of the barrier to advance from the given phase
624 dl 1.38 * value or the given timeout to elapse, throwing {@code
625     * InterruptedException} if interrupted while waiting, or
626     * returning immediately if the current phase of the barrier is
627     * not equal to the given phase value or this barrier is
628     * terminated. It is an unenforced usage error for an
629     * unregistered party to invoke this method.
630 jsr166 1.14 *
631 dl 1.35 * @param phase an arrival phase number, or negative value if
632     * terminated; this argument is normally the value returned by a
633     * previous call to {@code arrive} or its variants
634 dl 1.31 * @param timeout how long to wait before giving up, in units of
635     * {@code unit}
636     * @param unit a {@code TimeUnit} determining how to interpret the
637     * {@code timeout} parameter
638 dl 1.35 * @return the next arrival phase number, or a negative value
639     * if terminated or argument is negative
640 dl 1.1 * @throws InterruptedException if thread interrupted while waiting
641     * @throws TimeoutException if timed out while waiting
642     */
643 jsr166 1.18 public int awaitAdvanceInterruptibly(int phase,
644     long timeout, TimeUnit unit)
645 dl 1.1 throws InterruptedException, TimeoutException {
646 dl 1.49 long nanos = unit.toNanos(timeout);
647 dl 1.1 if (phase < 0)
648     return phase;
649 dl 1.49 int p = getPhase();
650 dl 1.4 if (p != phase)
651     return p;
652 dl 1.49 return timedWait(phase, nanos);
653 dl 1.1 }
654    
655     /**
656     * Forces this barrier to enter termination state. Counts of
657 dl 1.4 * arrived and registered parties are unaffected. If this phaser
658     * has a parent, it too is terminated. This method may be useful
659     * for coordinating recovery after one or more tasks encounter
660     * unexpected exceptions.
661 dl 1.1 */
662     public void forceTermination() {
663 dl 1.49 Phaser r = root; // force at root then reconcile
664     long s;
665     while (phaseOf(s = r.state) >= 0)
666     r.casState(s, stateFor(-1, partiesOf(s), unarrivedOf(s)));
667     reconcileState();
668     releaseWaiters(0); // ensure wakeups on both queues
669     releaseWaiters(1);
670 dl 1.1 }
671    
672     /**
673 dl 1.4 * Returns the current phase number. The maximum phase number is
674 jsr166 1.7 * {@code Integer.MAX_VALUE}, after which it restarts at
675 dl 1.4 * zero. Upon termination, the phase number is negative.
676 jsr166 1.14 *
677 dl 1.4 * @return the phase number, or a negative value if terminated
678 dl 1.1 */
679 dl 1.4 public final int getPhase() {
680     return phaseOf(getReconciledState());
681 dl 1.1 }
682    
683     /**
684     * Returns the number of parties registered at this barrier.
685 jsr166 1.14 *
686 dl 1.1 * @return the number of parties
687     */
688     public int getRegisteredParties() {
689 dl 1.49 return partiesOf(getReconciledState());
690 dl 1.1 }
691    
692     /**
693 dl 1.36 * Returns the number of registered parties that have arrived at
694     * the current phase of this barrier.
695 jsr166 1.14 *
696 dl 1.1 * @return the number of arrived parties
697     */
698     public int getArrivedParties() {
699 dl 1.49 return arrivedOf(getReconciledState());
700 dl 1.1 }
701    
702     /**
703     * Returns the number of registered parties that have not yet
704     * arrived at the current phase of this barrier.
705 jsr166 1.14 *
706 dl 1.1 * @return the number of unarrived parties
707     */
708     public int getUnarrivedParties() {
709 dl 1.49 return unarrivedOf(getReconciledState());
710 dl 1.4 }
711    
712     /**
713 jsr166 1.23 * Returns the parent of this phaser, or {@code null} if none.
714 jsr166 1.14 *
715 jsr166 1.23 * @return the parent of this phaser, or {@code null} if none
716 dl 1.4 */
717     public Phaser getParent() {
718     return parent;
719     }
720    
721     /**
722     * Returns the root ancestor of this phaser, which is the same as
723     * this phaser if it has no parent.
724 jsr166 1.14 *
725 jsr166 1.9 * @return the root ancestor of this phaser
726 dl 1.4 */
727     public Phaser getRoot() {
728     return root;
729 dl 1.1 }
730    
731     /**
732 jsr166 1.9 * Returns {@code true} if this barrier has been terminated.
733 jsr166 1.14 *
734 jsr166 1.9 * @return {@code true} if this barrier has been terminated
735 dl 1.1 */
736     public boolean isTerminated() {
737 dl 1.4 return getPhase() < 0;
738 dl 1.1 }
739    
740     /**
741 dl 1.43 * Overridable method to perform an action upon impending phase
742     * advance, and to control termination. This method is invoked
743     * upon arrival of the party tripping the barrier (when all other
744     * waiting parties are dormant). If this method returns {@code
745     * true}, then, rather than advance the phase number, this barrier
746     * will be set to a final termination state, and subsequent calls
747     * to {@link #isTerminated} will return true. Any (unchecked)
748     * Exception or Error thrown by an invocation of this method is
749     * propagated to the party attempting to trip the barrier, in
750     * which case no advance occurs.
751 dl 1.42 *
752     * <p>The arguments to this method provide the state of the phaser
753     * prevailing for the current transition. (When called from within
754     * an implementation of {@code onAdvance} the values returned by
755     * methods such as {@code getPhase} may or may not reliably
756     * indicate the state to which this transition applies.)
757 jsr166 1.3 *
758 jsr166 1.25 * <p>The default version returns {@code true} when the number of
759 dl 1.1 * registered parties is zero. Normally, overrides that arrange
760     * termination for other reasons should also preserve this
761     * property.
762     *
763     * @param phase the phase number on entering the barrier
764 jsr166 1.9 * @param registeredParties the current number of registered parties
765     * @return {@code true} if this barrier should terminate
766 dl 1.1 */
767     protected boolean onAdvance(int phase, int registeredParties) {
768     return registeredParties <= 0;
769     }
770    
771     /**
772 dl 1.4 * Returns a string identifying this phaser, as well as its
773 dl 1.1 * state. The state, in brackets, includes the String {@code
774 jsr166 1.9 * "phase = "} followed by the phase number, {@code "parties = "}
775 dl 1.1 * followed by the number of registered parties, and {@code
776 jsr166 1.9 * "arrived = "} followed by the number of arrived parties.
777 dl 1.1 *
778     * @return a string identifying this barrier, as well as its state
779     */
780     public String toString() {
781 dl 1.4 long s = getReconciledState();
782 jsr166 1.9 return super.toString() +
783     "[phase = " + phaseOf(s) +
784     " parties = " + partiesOf(s) +
785     " arrived = " + arrivedOf(s) + "]";
786 dl 1.1 }
787    
788 dl 1.4 // methods for waiting
789 dl 1.1
790     /**
791 dl 1.10 * Wait nodes for Treiber stack representing wait queue
792 dl 1.1 */
793 dl 1.10 static final class QNode implements ForkJoinPool.ManagedBlocker {
794     final Phaser phaser;
795     final int phase;
796     final long startTime;
797     final long nanos;
798     final boolean timed;
799     final boolean interruptible;
800     volatile boolean wasInterrupted = false;
801     volatile Thread thread; // nulled to cancel wait
802 dl 1.4 QNode next;
803 dl 1.48
804 dl 1.10 QNode(Phaser phaser, int phase, boolean interruptible,
805     boolean timed, long startTime, long nanos) {
806     this.phaser = phaser;
807     this.phase = phase;
808     this.timed = timed;
809     this.interruptible = interruptible;
810     this.startTime = startTime;
811     this.nanos = nanos;
812 dl 1.4 thread = Thread.currentThread();
813     }
814 dl 1.48
815 dl 1.10 public boolean isReleasable() {
816     return (thread == null ||
817     phaser.getPhase() != phase ||
818     (interruptible && wasInterrupted) ||
819     (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
820     }
821 dl 1.48
822 dl 1.10 public boolean block() {
823     if (Thread.interrupted()) {
824     wasInterrupted = true;
825     if (interruptible)
826     return true;
827     }
828     if (!timed)
829     LockSupport.park(this);
830     else {
831     long waitTime = nanos - (System.nanoTime() - startTime);
832     if (waitTime <= 0)
833     return true;
834     LockSupport.parkNanos(this, waitTime);
835     }
836     return isReleasable();
837     }
838 dl 1.48
839 dl 1.4 void signal() {
840     Thread t = thread;
841     if (t != null) {
842     thread = null;
843     LockSupport.unpark(t);
844     }
845     }
846 dl 1.48
847 dl 1.10 boolean doWait() {
848     if (thread != null) {
849     try {
850 dl 1.47 ForkJoinPool.managedBlock(this);
851 dl 1.10 } catch (InterruptedException ie) {
852 dl 1.48 wasInterrupted = true; // can't currently happen
853 jsr166 1.12 }
854 dl 1.10 }
855     return wasInterrupted;
856     }
857 dl 1.4 }
858    
859     /**
860 jsr166 1.14 * Removes and signals waiting threads from wait queue.
861 dl 1.4 */
862     private void releaseWaiters(int phase) {
863     AtomicReference<QNode> head = queueFor(phase);
864     QNode q;
865     while ((q = head.get()) != null) {
866     if (head.compareAndSet(q, q.next))
867     q.signal();
868     }
869     }
870    
871     /**
872 jsr166 1.14 * Tries to enqueue given node in the appropriate wait queue.
873     *
874 dl 1.10 * @return true if successful
875     */
876     private boolean tryEnqueue(QNode node) {
877     AtomicReference<QNode> head = queueFor(node.phase);
878     return head.compareAndSet(node.next = head.get(), node);
879     }
880    
881     /**
882 dl 1.1 * Enqueues node and waits unless aborted or signalled.
883 jsr166 1.14 *
884 dl 1.10 * @return current phase
885 dl 1.1 */
886 dl 1.4 private int untimedWait(int phase) {
887 dl 1.1 QNode node = null;
888 dl 1.10 boolean queued = false;
889 dl 1.4 boolean interrupted = false;
890     int p;
891     while ((p = getPhase()) == phase) {
892 dl 1.10 if (Thread.interrupted())
893     interrupted = true;
894     else if (node == null)
895     node = new QNode(this, phase, false, false, 0, 0);
896     else if (!queued)
897     queued = tryEnqueue(node);
898 dl 1.48 else if (node.doWait())
899     interrupted = true;
900 dl 1.4 }
901     if (node != null)
902     node.thread = null;
903 dl 1.10 releaseWaiters(phase);
904 dl 1.4 if (interrupted)
905     Thread.currentThread().interrupt();
906     return p;
907     }
908    
909     /**
910 dl 1.10 * Interruptible version
911     * @return current phase
912 dl 1.4 */
913     private int interruptibleWait(int phase) throws InterruptedException {
914     QNode node = null;
915     boolean queued = false;
916     boolean interrupted = false;
917     int p;
918 dl 1.10 while ((p = getPhase()) == phase && !interrupted) {
919     if (Thread.interrupted())
920     interrupted = true;
921     else if (node == null)
922     node = new QNode(this, phase, true, false, 0, 0);
923     else if (!queued)
924     queued = tryEnqueue(node);
925 dl 1.48 else if (node.doWait())
926     interrupted = true;
927 dl 1.1 }
928     if (node != null)
929     node.thread = null;
930 dl 1.10 if (p != phase || (p = getPhase()) != phase)
931     releaseWaiters(phase);
932 dl 1.4 if (interrupted)
933     throw new InterruptedException();
934     return p;
935 dl 1.1 }
936    
937     /**
938 dl 1.10 * Timeout version.
939     * @return current phase
940 dl 1.1 */
941 dl 1.4 private int timedWait(int phase, long nanos)
942 dl 1.1 throws InterruptedException, TimeoutException {
943 dl 1.10 long startTime = System.nanoTime();
944     QNode node = null;
945     boolean queued = false;
946     boolean interrupted = false;
947 dl 1.4 int p;
948 dl 1.10 while ((p = getPhase()) == phase && !interrupted) {
949     if (Thread.interrupted())
950     interrupted = true;
951     else if (nanos - (System.nanoTime() - startTime) <= 0)
952     break;
953     else if (node == null)
954     node = new QNode(this, phase, true, true, startTime, nanos);
955     else if (!queued)
956     queued = tryEnqueue(node);
957 dl 1.48 else if (node.doWait())
958     interrupted = true;
959 dl 1.4 }
960 dl 1.10 if (node != null)
961     node.thread = null;
962     if (p != phase || (p = getPhase()) != phase)
963     releaseWaiters(phase);
964     if (interrupted)
965     throw new InterruptedException();
966     if (p == phase)
967     throw new TimeoutException();
968 dl 1.4 return p;
969     }
970    
971 jsr166 1.22 // Unsafe mechanics
972    
973     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
974     private static final long stateOffset =
975     objectFieldOffset("state", Phaser.class);
976    
977     private final boolean casState(long cmp, long val) {
978     return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
979     }
980    
981     private static long objectFieldOffset(String field, Class<?> klazz) {
982     try {
983     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
984     } catch (NoSuchFieldException e) {
985     // Convert Exception to corresponding Error
986     NoSuchFieldError error = new NoSuchFieldError(field);
987     error.initCause(e);
988     throw error;
989     }
990     }
991    
992     /**
993     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
994     * Replace with a simple call to Unsafe.getUnsafe when integrating
995     * into a jdk.
996     *
997     * @return a sun.misc.Unsafe
998     */
999 jsr166 1.19 private static sun.misc.Unsafe getUnsafe() {
1000 jsr166 1.11 try {
1001 jsr166 1.19 return sun.misc.Unsafe.getUnsafe();
1002 jsr166 1.11 } catch (SecurityException se) {
1003     try {
1004     return java.security.AccessController.doPrivileged
1005 jsr166 1.22 (new java.security
1006     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1007 jsr166 1.19 public sun.misc.Unsafe run() throws Exception {
1008 jsr166 1.22 java.lang.reflect.Field f = sun.misc
1009     .Unsafe.class.getDeclaredField("theUnsafe");
1010     f.setAccessible(true);
1011     return (sun.misc.Unsafe) f.get(null);
1012 jsr166 1.11 }});
1013     } catch (java.security.PrivilegedActionException e) {
1014 jsr166 1.19 throw new RuntimeException("Could not initialize intrinsics",
1015     e.getCause());
1016 jsr166 1.11 }
1017     }
1018     }
1019 dl 1.1 }