ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.15
Committed: Sat Nov 6 16:11:50 2010 UTC (13 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.14: +95 -77 lines
Log Message:
Performance (and other) 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 dl 1.14 * contention when releasing some threads while adding others, we
297 jsr166 1.1 * use two of them, alternating across even and odd phases.
298 dl 1.14 * Subphasers share queues with root to speed up releases.
299 jsr166 1.1 */
300 dl 1.15 private final AtomicReference<QNode> evenQ;
301     private final AtomicReference<QNode> oddQ;
302 jsr166 1.1
303     private AtomicReference<QNode> queueFor(int phase) {
304 dl 1.15 return ((phase & 1) == 0) ? evenQ : oddQ;
305 jsr166 1.1 }
306    
307     /**
308     * Returns current state, first resolving lagged propagation from
309     * root if necessary.
310     */
311     private long getReconciledState() {
312     return (parent == null) ? state : reconcileState();
313     }
314    
315     /**
316     * Recursively resolves state.
317     */
318     private long reconcileState() {
319 dl 1.14 Phaser par = parent;
320 jsr166 1.1 long s = state;
321 dl 1.14 if (par != null) {
322     int phase, rootPhase;
323     while ((phase = phaseOf(s)) >= 0 &&
324     (rootPhase = phaseOf(root.state)) != phase &&
325     (rootPhase < 0 || unarrivedOf(s) == 0)) {
326 dl 1.15 int parentPhase = phaseOf(par.getReconciledState());
327     if (parentPhase != phase) {
328     long next = trippedStateFor(parentPhase, partiesOf(s));
329     if (state == s)
330     UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
331 jsr166 1.1 }
332 dl 1.14 s = state;
333 jsr166 1.1 }
334     }
335     return s;
336     }
337    
338     /**
339 jsr166 1.4 * Creates a new phaser without any initially registered parties,
340 jsr166 1.1 * initial phase number 0, and no parent. Any thread using this
341 jsr166 1.4 * phaser will need to first register for it.
342 jsr166 1.1 */
343     public Phaser() {
344 dl 1.15 this(null, 0);
345 jsr166 1.1 }
346    
347     /**
348 jsr166 1.12 * Creates a new phaser with the given number of registered
349 jsr166 1.1 * unarrived parties, initial phase number 0, and no parent.
350     *
351     * @param parties the number of parties required to trip barrier
352     * @throws IllegalArgumentException if parties less than zero
353     * or greater than the maximum number of parties supported
354     */
355     public Phaser(int parties) {
356     this(null, parties);
357     }
358    
359     /**
360 jsr166 1.4 * Creates a new phaser with the given parent, without any
361 jsr166 1.1 * initially registered parties. If parent is non-null this phaser
362     * is registered with the parent and its initial phase number is
363     * the same as that of parent phaser.
364     *
365     * @param parent the parent phaser
366     */
367     public Phaser(Phaser parent) {
368 dl 1.15 this(parent, 0);
369 jsr166 1.1 }
370    
371     /**
372 jsr166 1.12 * Creates a new phaser with the given parent and number of
373 jsr166 1.1 * registered unarrived parties. If parent is non-null, this phaser
374     * is registered with the parent and its initial phase number is
375     * the same as that of parent phaser.
376     *
377     * @param parent the parent phaser
378     * @param parties the number of parties required to trip barrier
379     * @throws IllegalArgumentException if parties less than zero
380     * or greater than the maximum number of parties supported
381     */
382     public Phaser(Phaser parent, int parties) {
383     if (parties < 0 || parties > ushortMask)
384     throw new IllegalArgumentException("Illegal number of parties");
385 dl 1.15 int phase;
386 jsr166 1.1 this.parent = parent;
387     if (parent != null) {
388 dl 1.15 Phaser r = parent.root;
389     this.root = r;
390     this.evenQ = r.evenQ;
391     this.oddQ = r.oddQ;
392 jsr166 1.1 phase = parent.register();
393     }
394 dl 1.15 else {
395 jsr166 1.1 this.root = this;
396 dl 1.15 this.evenQ = new AtomicReference<QNode>();
397     this.oddQ = new AtomicReference<QNode>();
398     phase = 0;
399     }
400 jsr166 1.1 this.state = trippedStateFor(phase, parties);
401     }
402    
403     /**
404     * Adds a new unarrived party to this phaser.
405 dl 1.14 * If an ongoing invocation of {@link #onAdvance} is in progress,
406 dl 1.15 * this method may wait until its completion before registering.
407 jsr166 1.1 *
408 jsr166 1.10 * @return the arrival phase number to which this registration applied
409 jsr166 1.1 * @throws IllegalStateException if attempting to register more
410     * than the maximum supported number of parties
411     */
412     public int register() {
413     return doRegister(1);
414     }
415    
416     /**
417     * Adds the given number of new unarrived parties to this phaser.
418 dl 1.14 * If an ongoing invocation of {@link #onAdvance} is in progress,
419 dl 1.15 * this method may wait until its completion before registering.
420 jsr166 1.1 *
421 jsr166 1.12 * @param parties the number of additional parties required to trip barrier
422 jsr166 1.10 * @return the arrival phase number to which this registration applied
423 jsr166 1.1 * @throws IllegalStateException if attempting to register more
424     * than the maximum supported number of parties
425 dl 1.13 * @throws IllegalArgumentException if {@code parties < 0}
426 jsr166 1.1 */
427     public int bulkRegister(int parties) {
428     if (parties < 0)
429     throw new IllegalArgumentException();
430     if (parties == 0)
431     return getPhase();
432     return doRegister(parties);
433     }
434    
435     /**
436     * Shared code for register, bulkRegister
437     */
438     private int doRegister(int registrations) {
439 dl 1.14 Phaser par = parent;
440     long s;
441 jsr166 1.1 int phase;
442 dl 1.14 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
443     int p = partiesOf(s);
444     int u = unarrivedOf(s);
445     int unarrived = u + registrations;
446     int parties = p + registrations;
447 dl 1.15 if (u == 0 && p != 0) // if tripped, wait for advance
448     untimedWait(phase);
449     else if (parties > ushortMask)
450     throw new IllegalStateException(badBounds(parties, unarrived));
451     else if (par == null || phaseOf(root.state) == phase) {
452     long next = stateFor(phase, parties, unarrived);
453     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
454 dl 1.14 break;
455     }
456 jsr166 1.1 }
457     return phase;
458     }
459    
460     /**
461     * Arrives at the barrier, but does not wait for others. (You can
462 jsr166 1.10 * in turn wait for others via {@link #awaitAdvance}). It is an
463     * unenforced usage error for an unregistered party to invoke this
464     * method.
465 jsr166 1.1 *
466 jsr166 1.10 * @return the arrival phase number, or a negative value if terminated
467 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
468     * of unarrived parties would become negative
469     */
470     public int arrive() {
471 dl 1.14 Phaser par = parent;
472     long s;
473 jsr166 1.1 int phase;
474 dl 1.14 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
475 jsr166 1.1 int parties = partiesOf(s);
476     int unarrived = unarrivedOf(s) - 1;
477 dl 1.15 if (unarrived > 0) { // Not the last arrival
478     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s - 1))
479     break; // s-1 adds one arrival
480 jsr166 1.1 }
481 dl 1.15 else if (unarrived < 0)
482     throw new IllegalStateException(badBounds(parties, unarrived));
483 dl 1.14 else if (par == null) { // directly trip
484 dl 1.15 long next = trippedStateFor(onAdvance(phase, parties) ? -1 :
485     ((phase + 1) & phaseMask),
486     parties);
487     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
488 dl 1.14 releaseWaiters(phase);
489     break;
490 jsr166 1.1 }
491     }
492 dl 1.15 else if (phaseOf(root.state) == phase &&
493     UNSAFE.compareAndSwapLong(this, stateOffset, s, s - 1)) {
494 dl 1.14 par.arrive(); // cascade to parent
495 jsr166 1.1 reconcileState();
496 dl 1.14 break;
497     }
498 jsr166 1.1 }
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 dl 1.14 // similar to arrive, but too different to merge
517 jsr166 1.1 Phaser par = parent;
518 dl 1.14 long s;
519 jsr166 1.1 int phase;
520 dl 1.14 while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
521 jsr166 1.1 int parties = partiesOf(s) - 1;
522     int unarrived = unarrivedOf(s) - 1;
523 dl 1.15 if (unarrived > 0) {
524     long next = stateFor(phase, parties, unarrived);
525     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
526 dl 1.14 break;
527     }
528 dl 1.15 else if (unarrived < 0)
529     throw new IllegalStateException(badBounds(parties, unarrived));
530 dl 1.14 else if (par == null) {
531 dl 1.15 long next = trippedStateFor(onAdvance(phase, parties)? -1:
532     (phase + 1) & phaseMask,
533     parties);
534     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
535 dl 1.14 releaseWaiters(phase);
536     break;
537 jsr166 1.1 }
538     }
539 dl 1.15 else if (phaseOf(root.state) == phase) {
540     long next = stateFor(phase, parties, 0);
541     if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
542     if (parties == 0)
543     par.arriveAndDeregister();
544     else
545     par.arrive();
546     reconcileState();
547     break;
548     }
549 dl 1.14 }
550 jsr166 1.1 }
551     return phase;
552     }
553    
554     /**
555     * Arrives at the barrier and awaits others. Equivalent in effect
556 jsr166 1.7 * to {@code awaitAdvance(arrive())}. If you need to await with
557     * interruption or timeout, you can arrange this with an analogous
558 jsr166 1.12 * construction using one of the other forms of the {@code
559     * awaitAdvance} method. If instead you need to deregister upon
560     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
561     * usage error for an unregistered party to invoke this method.
562 jsr166 1.1 *
563 jsr166 1.10 * @return the arrival phase number, or a negative number if terminated
564 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
565     * of unarrived parties would become negative
566     */
567     public int arriveAndAwaitAdvance() {
568     return awaitAdvance(arrive());
569     }
570    
571     /**
572 jsr166 1.7 * Awaits the phase of the barrier to advance from the given phase
573 jsr166 1.8 * value, returning immediately if the current phase of the
574     * barrier is not equal to the given phase value or this barrier
575 dl 1.15 * is terminated.
576 jsr166 1.1 *
577 jsr166 1.10 * @param phase an arrival phase number, or negative value if
578     * terminated; this argument is normally the value returned by a
579     * previous call to {@code arrive} or its variants
580     * @return the next arrival phase number, or a negative value
581     * if terminated or argument is negative
582 jsr166 1.1 */
583     public int awaitAdvance(int phase) {
584     if (phase < 0)
585     return phase;
586 dl 1.14 int p = getPhase();
587 jsr166 1.1 if (p != phase)
588     return p;
589     return untimedWait(phase);
590     }
591    
592     /**
593 jsr166 1.8 * Awaits the phase of the barrier to advance from the given phase
594 jsr166 1.10 * value, throwing {@code InterruptedException} if interrupted
595     * while waiting, or returning immediately if the current phase of
596     * the barrier is not equal to the given phase value or this
597 dl 1.15 * barrier is terminated.
598 jsr166 1.10 *
599     * @param phase an arrival phase number, or negative value if
600     * terminated; this argument is normally the value returned by a
601     * previous call to {@code arrive} or its variants
602     * @return the next arrival phase number, or a negative value
603     * if terminated or argument is negative
604 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
605     */
606     public int awaitAdvanceInterruptibly(int phase)
607     throws InterruptedException {
608     if (phase < 0)
609     return phase;
610 dl 1.14 int p = getPhase();
611 jsr166 1.1 if (p != phase)
612     return p;
613     return interruptibleWait(phase);
614     }
615    
616     /**
617 jsr166 1.8 * Awaits the phase of the barrier to advance from the given phase
618 jsr166 1.10 * value or the given timeout to elapse, throwing {@code
619     * InterruptedException} if interrupted while waiting, or
620     * returning immediately if the current phase of the barrier is
621     * not equal to the given phase value or this barrier is
622 dl 1.15 * terminated.
623 jsr166 1.10 *
624     * @param phase an arrival phase number, or negative value if
625     * terminated; this argument is normally the value returned by a
626     * previous call to {@code arrive} or its variants
627 jsr166 1.8 * @param timeout how long to wait before giving up, in units of
628     * {@code unit}
629     * @param unit a {@code TimeUnit} determining how to interpret the
630     * {@code timeout} parameter
631 jsr166 1.10 * @return the next arrival phase number, or a negative value
632     * if terminated or argument is negative
633 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
634     * @throws TimeoutException if timed out while waiting
635     */
636     public int awaitAdvanceInterruptibly(int phase,
637     long timeout, TimeUnit unit)
638     throws InterruptedException, TimeoutException {
639 dl 1.14 long nanos = unit.toNanos(timeout);
640 jsr166 1.1 if (phase < 0)
641     return phase;
642 dl 1.14 int p = getPhase();
643 jsr166 1.1 if (p != phase)
644     return p;
645 dl 1.14 return timedWait(phase, nanos);
646 jsr166 1.1 }
647    
648     /**
649     * Forces this barrier to enter termination state. Counts of
650     * arrived and registered parties are unaffected. If this phaser
651     * has a parent, it too is terminated. This method may be useful
652     * for coordinating recovery after one or more tasks encounter
653     * unexpected exceptions.
654     */
655     public void forceTermination() {
656 dl 1.14 Phaser r = root; // force at root then reconcile
657     long s;
658     while (phaseOf(s = r.state) >= 0)
659 dl 1.15 UNSAFE.compareAndSwapLong(r, stateOffset, s,
660     stateFor(-1, partiesOf(s),
661     unarrivedOf(s)));
662 dl 1.14 reconcileState();
663     releaseWaiters(0); // ensure wakeups on both queues
664     releaseWaiters(1);
665 jsr166 1.1 }
666    
667     /**
668     * Returns the current phase number. The maximum phase number is
669     * {@code Integer.MAX_VALUE}, after which it restarts at
670     * zero. Upon termination, the phase number is negative.
671     *
672     * @return the phase number, or a negative value if terminated
673     */
674     public final int getPhase() {
675     return phaseOf(getReconciledState());
676     }
677    
678     /**
679     * Returns the number of parties registered at this barrier.
680     *
681     * @return the number of parties
682     */
683     public int getRegisteredParties() {
684 dl 1.14 return partiesOf(getReconciledState());
685 jsr166 1.1 }
686    
687     /**
688 jsr166 1.10 * Returns the number of registered parties that have arrived at
689     * the current phase of this barrier.
690 jsr166 1.1 *
691     * @return the number of arrived parties
692     */
693     public int getArrivedParties() {
694 dl 1.14 return arrivedOf(getReconciledState());
695 jsr166 1.1 }
696    
697     /**
698     * Returns the number of registered parties that have not yet
699     * arrived at the current phase of this barrier.
700     *
701     * @return the number of unarrived parties
702     */
703     public int getUnarrivedParties() {
704 dl 1.14 return unarrivedOf(getReconciledState());
705 jsr166 1.1 }
706    
707     /**
708 jsr166 1.4 * Returns the parent of this phaser, or {@code null} if none.
709 jsr166 1.1 *
710 jsr166 1.4 * @return the parent of this phaser, or {@code null} if none
711 jsr166 1.1 */
712     public Phaser getParent() {
713     return parent;
714     }
715    
716     /**
717     * Returns the root ancestor of this phaser, which is the same as
718     * this phaser if it has no parent.
719     *
720     * @return the root ancestor of this phaser
721     */
722     public Phaser getRoot() {
723     return root;
724     }
725    
726     /**
727     * Returns {@code true} if this barrier has been terminated.
728     *
729     * @return {@code true} if this barrier has been terminated
730     */
731     public boolean isTerminated() {
732     return getPhase() < 0;
733     }
734    
735     /**
736 jsr166 1.10 * Overridable method to perform an action upon impending phase
737     * advance, and to control termination. This method is invoked
738     * upon arrival of the party tripping the barrier (when all other
739     * waiting parties are dormant). If this method returns {@code
740     * true}, then, rather than advance the phase number, this barrier
741     * will be set to a final termination state, and subsequent calls
742     * to {@link #isTerminated} will return true. Any (unchecked)
743     * Exception or Error thrown by an invocation of this method is
744     * propagated to the party attempting to trip the barrier, in
745     * which case no advance occurs.
746     *
747     * <p>The arguments to this method provide the state of the phaser
748 dl 1.15 * prevailing for the current transition. The results and effects
749     * of invoking phase-related methods (including {@code getPhase}
750     * as well as arrival, registration, and waiting methods) from
751     * within {@code onAdvance} are unspecified and should not be
752     * relied on. Similarly, while it is possible to override this
753     * method to produce side-effects visible to participating tasks,
754     * it is in general safe to do so only in designs in which all
755     * parties register before any arrive, and all {@link
756     * #awaitAdvance} at each phase.
757 jsr166 1.1 *
758 jsr166 1.5 * <p>The default version returns {@code true} when the number of
759 jsr166 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     * @param registeredParties the current number of registered parties
765     * @return {@code true} if this barrier should terminate
766     */
767     protected boolean onAdvance(int phase, int registeredParties) {
768     return registeredParties <= 0;
769     }
770    
771     /**
772     * Returns a string identifying this phaser, as well as its
773     * state. The state, in brackets, includes the String {@code
774     * "phase = "} followed by the phase number, {@code "parties = "}
775     * followed by the number of registered parties, and {@code
776     * "arrived = "} followed by the number of arrived parties.
777     *
778     * @return a string identifying this barrier, as well as its state
779     */
780     public String toString() {
781     long s = getReconciledState();
782     return super.toString() +
783     "[phase = " + phaseOf(s) +
784     " parties = " + partiesOf(s) +
785     " arrived = " + arrivedOf(s) + "]";
786     }
787    
788     // methods for waiting
789    
790     /**
791     * Wait nodes for Treiber stack representing wait queue
792     */
793     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     QNode next;
803 jsr166 1.12
804 jsr166 1.1 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     thread = Thread.currentThread();
813     }
814 jsr166 1.12
815 jsr166 1.1 public boolean isReleasable() {
816     return (thread == null ||
817     phaser.getPhase() != phase ||
818     (interruptible && wasInterrupted) ||
819     (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
820     }
821 jsr166 1.12
822 jsr166 1.1 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 jsr166 1.12
839 jsr166 1.1 void signal() {
840     Thread t = thread;
841     if (t != null) {
842     thread = null;
843     LockSupport.unpark(t);
844     }
845     }
846 jsr166 1.12
847 jsr166 1.1 boolean doWait() {
848     if (thread != null) {
849     try {
850 dl 1.11 ForkJoinPool.managedBlock(this);
851 jsr166 1.1 } catch (InterruptedException ie) {
852 dl 1.13 wasInterrupted = true; // can't currently happen
853 jsr166 1.1 }
854     }
855     return wasInterrupted;
856     }
857     }
858    
859     /**
860     * Removes and signals waiting threads from wait queue.
861     */
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     * Tries to enqueue given node in the appropriate wait queue.
873     *
874     * @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.15 * The number of times to spin before blocking waiting for advance.
883     */
884     static final int MAX_SPINS =
885     Runtime.getRuntime().availableProcessors() == 1 ? 0 : 1 << 8;
886    
887     /**
888 jsr166 1.1 * Enqueues node and waits unless aborted or signalled.
889     *
890     * @return current phase
891     */
892     private int untimedWait(int phase) {
893     QNode node = null;
894     boolean queued = false;
895     boolean interrupted = false;
896 dl 1.15 int spins = MAX_SPINS;
897 jsr166 1.1 int p;
898     while ((p = getPhase()) == phase) {
899     if (Thread.interrupted())
900     interrupted = true;
901 dl 1.15 else if (spins > 0) {
902     if (--spins == 0)
903     Thread.yield();
904     }
905 jsr166 1.1 else if (node == null)
906     node = new QNode(this, phase, false, false, 0, 0);
907     else if (!queued)
908     queued = tryEnqueue(node);
909 dl 1.13 else if (node.doWait())
910     interrupted = true;
911 jsr166 1.1 }
912     if (node != null)
913     node.thread = null;
914     releaseWaiters(phase);
915     if (interrupted)
916     Thread.currentThread().interrupt();
917     return p;
918     }
919    
920     /**
921     * Interruptible version
922     * @return current phase
923     */
924     private int interruptibleWait(int phase) throws InterruptedException {
925     QNode node = null;
926     boolean queued = false;
927     boolean interrupted = false;
928 dl 1.15 int spins = MAX_SPINS;
929 jsr166 1.1 int p;
930     while ((p = getPhase()) == phase && !interrupted) {
931     if (Thread.interrupted())
932     interrupted = true;
933 dl 1.15 else if (spins > 0) {
934     if (--spins == 0)
935     Thread.yield();
936     }
937 jsr166 1.1 else if (node == null)
938     node = new QNode(this, phase, true, false, 0, 0);
939     else if (!queued)
940     queued = tryEnqueue(node);
941 dl 1.13 else if (node.doWait())
942     interrupted = true;
943 jsr166 1.1 }
944     if (node != null)
945     node.thread = null;
946     if (p != phase || (p = getPhase()) != phase)
947     releaseWaiters(phase);
948     if (interrupted)
949     throw new InterruptedException();
950     return p;
951     }
952    
953     /**
954     * Timeout version.
955     * @return current phase
956     */
957     private int timedWait(int phase, long nanos)
958     throws InterruptedException, TimeoutException {
959     long startTime = System.nanoTime();
960     QNode node = null;
961     boolean queued = false;
962     boolean interrupted = false;
963 dl 1.15 int spins = MAX_SPINS;
964 jsr166 1.1 int p;
965     while ((p = getPhase()) == phase && !interrupted) {
966     if (Thread.interrupted())
967     interrupted = true;
968     else if (nanos - (System.nanoTime() - startTime) <= 0)
969     break;
970 dl 1.15 else if (spins > 0) {
971     if (--spins == 0)
972     Thread.yield();
973     }
974 jsr166 1.1 else if (node == null)
975     node = new QNode(this, phase, true, true, startTime, nanos);
976     else if (!queued)
977     queued = tryEnqueue(node);
978 dl 1.13 else if (node.doWait())
979     interrupted = true;
980 jsr166 1.1 }
981     if (node != null)
982     node.thread = null;
983     if (p != phase || (p = getPhase()) != phase)
984     releaseWaiters(phase);
985     if (interrupted)
986     throw new InterruptedException();
987     if (p == phase)
988     throw new TimeoutException();
989     return p;
990     }
991    
992     // Unsafe mechanics
993    
994     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
995 jsr166 1.2 private static final long stateOffset =
996 jsr166 1.3 objectFieldOffset("state", Phaser.class);
997 jsr166 1.1
998 jsr166 1.3 private static long objectFieldOffset(String field, Class<?> klazz) {
999     try {
1000     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1001     } catch (NoSuchFieldException e) {
1002     // Convert Exception to corresponding Error
1003     NoSuchFieldError error = new NoSuchFieldError(field);
1004     error.initCause(e);
1005     throw error;
1006     }
1007     }
1008 jsr166 1.1 }