ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.43
Committed: Mon Aug 24 23:08:18 2009 UTC (14 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.42: +16 -15 lines
Log Message:
Clarify onAdvance

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