ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.12
Committed: Fri Oct 15 22:52:05 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +17 -14 lines
Log Message:
javadoc and style improvements

File Contents

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