ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.35
Committed: Sun Aug 23 13:37:08 2009 UTC (14 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.34: +36 -30 lines
Log Message:
Clarify meaning of phase arguments and return values

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