ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.7
Committed: Wed Aug 12 04:10:59 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.6: +33 -46 lines
Log Message:
sync with jsr166 package

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