ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.30
Committed: Wed Aug 19 15:23:18 2009 UTC (14 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.29: +13 -10 lines
Log Message:
Improve awaitAdvance* spec wording

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