ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.3
Committed: Sun Jul 26 17:48:58 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.2: +12 -12 lines
Log Message:
sync with jsr166y 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     * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
34     * Method {@code arriveAndAwaitAdvance} has effect analogous to
35     * {@code CyclicBarrier.await}. However, Phasers separate two
36     * aspects of coordination, that may also be invoked independently:
37     *
38     * <ul>
39     *
40     * <li> Arriving at a barrier. Methods {@code arrive} and
41     * {@code arriveAndDeregister} do not block, but return
42     * the phase value current upon entry to the method.
43     *
44     * <li> Awaiting others. Method {@code awaitAdvance} requires an
45     * argument indicating the entry phase, and returns when the
46     * barrier advances to a new phase.
47     * </ul>
48     *
49     *
50     * <li> Barrier actions, performed by the task triggering a phase
51     * advance while others may be waiting, are arranged by overriding
52     * method {@code onAdvance}, that also controls termination.
53     * Overriding this method may be used to similar but more flexible
54     * effect as providing a barrier action to a CyclicBarrier.
55     *
56     * <li> Phasers may enter a <em>termination</em> state in which all
57     * actions immediately return without updating phaser state or waiting
58     * for advance, and indicating (via a negative phase value) that
59     * execution is complete. Termination is triggered by executing the
60     * overridable {@code onAdvance} method that is invoked each time the
61     * barrier is about to be tripped. When a Phaser is controlling an
62     * action with a fixed number of iterations, it is often convenient to
63     * override this method to cause termination when the current phase
64     * number reaches a threshold. Method {@code forceTermination} is also
65     * available to abruptly release waiting threads and allow them to
66     * terminate.
67     *
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     * CyclicBarriers, exceptions encountered while tasks wait
77     * 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     * <li>Phasers ensure lack of starvation when used by ForkJoinTasks.
83     *
84     * </ul>
85     *
86     * <p><b>Sample usages:</b>
87     *
88     * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
89     * a one-shot action serving a variable number of parties. The typical
90     * idiom is for the method setting this up to first register, then
91     * start the actions, then deregister, as in:
92     *
93     * <pre> {@code
94     * void runTasks(List<Runnable> list) {
95     * final Phaser phaser = new Phaser(1); // "1" to register self
96     * for (Runnable r : list) {
97     * phaser.register();
98     * new Thread() {
99     * public void run() {
100     * phaser.arriveAndAwaitAdvance(); // await all creation
101     * r.run();
102     * phaser.arriveAndDeregister(); // signal completion
103     * }
104     * }.start();
105     * }
106     *
107     * doSomethingOnBehalfOfWorkers();
108     * phaser.arrive(); // allow threads to start
109     * int p = phaser.arriveAndDeregister(); // deregister self ...
110     * p = phaser.awaitAdvance(p); // ... and await arrival
111     * otherActions(); // do other things while tasks execute
112     * phaser.awaitAdvance(p); // await final completion
113     * }}</pre>
114     *
115     * <p>One way to cause a set of threads to repeatedly perform actions
116     * for a given number of iterations is to override {@code onAdvance}:
117     *
118     * <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     * }
135     * }.start();
136     * }
137     * phaser.arriveAndDeregister(); // deregister self, don't wait
138     * }}</pre>
139     *
140     * <p> To create a set of tasks using a tree of Phasers,
141     * you could use code of the following form, assuming a
142     * Task class with a constructor accepting a Phaser that
143     * it registers for upon construction:
144     * <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     *
163     * The best value of {@code TASKS_PER_PHASER} depends mainly on
164     * 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     * <p><b>Implementation notes</b>: This implementation restricts the
171     * 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     *
176     * @since 1.7
177     * @author Doug Lea
178     */
179     public class Phaser {
180     /*
181     * This class implements an extension of X10 "clocks". Thanks to
182     * Vijay Saraswat for the idea, and to Vivek Sarkar for
183     * enhancements to extend functionality.
184     */
185    
186     /**
187     * Barrier state representation. Conceptually, a barrier contains
188     * four values:
189     *
190     * * 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     * 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     * termination. Good performance relies on keeping state decoding
199     * and encoding simple, and keeping race windows short.
200     *
201     * Note: there are some cheats in arrive() that rely on unarrived
202     * count being lowest 16 bits.
203     */
204     private volatile long state;
205    
206     private static final int ushortBits = 16;
207     private static final int ushortMask = 0xffff;
208     private static final int phaseMask = 0x7fffffff;
209    
210     private static int unarrivedOf(long s) {
211     return (int) (s & ushortMask);
212     }
213    
214     private static int partiesOf(long s) {
215     return ((int) s) >>> 16;
216     }
217    
218     private static int phaseOf(long s) {
219     return (int) (s >>> 32);
220     }
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     return ((((long) phase) << 32) | (((long) parties) << 16) |
228     (long) unarrived);
229     }
230    
231     private static long trippedStateFor(int phase, int parties) {
232     long lp = (long) parties;
233     return (((long) phase) << 32) | (lp << 16) | lp;
234     }
235    
236     /**
237     * Returns message string for bad bounds exceptions.
238     */
239     private static String badBounds(int parties, int unarrived) {
240     return ("Attempt to set " + unarrived +
241     " unarrived of " + parties + " parties");
242     }
243    
244     /**
245     * The parent of this phaser, or null if none
246     */
247     private final Phaser parent;
248    
249     /**
250     * The root of Phaser tree. Equals this if not in a tree. Used to
251     * support faster state push-down.
252     */
253     private final Phaser root;
254    
255     // Wait queues
256    
257     /**
258     * Heads of Treiber stacks for waiting threads. To eliminate
259     * 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     return ((phase & 1) == 0) ? evenQ : oddQ;
267     }
268    
269     /**
270     * Returns current state, first resolving lagged propagation from
271     * root if necessary.
272     */
273     private long getReconciledState() {
274     return (parent == null) ? state : reconcileState();
275     }
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     }
299    
300     /**
301     * Creates a new Phaser without any initially registered parties,
302     * initial phase number 0, and no parent. Any thread using this
303     * Phaser will need to first register for it.
304     */
305     public Phaser() {
306     this(null);
307     }
308    
309     /**
310     * Creates a new Phaser with the given numbers of registered
311     * unarrived parties, initial phase number 0, and no parent.
312     *
313     * @param parties the number of parties required to trip barrier
314     * @throws IllegalArgumentException if parties less than zero
315     * or greater than the maximum number of parties supported
316     */
317     public Phaser(int parties) {
318     this(null, parties);
319     }
320    
321     /**
322     * Creates a new Phaser with the given parent, without any
323     * 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     *
327     * @param parent the parent phaser
328     */
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     * Creates a new Phaser with the given parent and numbers of
343     * registered unarrived parties. If parent is non-null, this phaser
344     * is registered with the parent and its initial phase number is
345     * the same as that of parent phaser.
346     *
347     * @param parent the parent phaser
348     * @param parties the number of parties required to trip barrier
349     * @throws IllegalArgumentException if parties less than zero
350     * or greater than the maximum number of parties supported
351     */
352     public Phaser(Phaser parent, int parties) {
353     if (parties < 0 || parties > ushortMask)
354     throw new IllegalArgumentException("Illegal number of parties");
355     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     }
365    
366     /**
367     * Adds a new unarrived party to this phaser.
368     *
369     * @return the current barrier phase number upon registration
370     * @throws IllegalStateException if attempting to register more
371     * than the maximum supported number of parties
372     */
373     public int register() {
374     return doRegister(1);
375     }
376    
377     /**
378     * Adds the given number of new unarrived parties to this phaser.
379     *
380     * @param parties the number of parties required to trip barrier
381     * @return the current barrier phase number upon registration
382     * @throws IllegalStateException if attempting to register more
383     * than the maximum supported number of parties
384     */
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     for (;;) {
399     long s = getReconciledState();
400     phase = phaseOf(s);
401     int unarrived = unarrivedOf(s) + registrations;
402     int parties = partiesOf(s) + registrations;
403     if (phase < 0)
404     break;
405     if (parties > ushortMask || unarrived > ushortMask)
406     throw new IllegalStateException(badBounds(parties, unarrived));
407     if (phase == phaseOf(root.state) &&
408     casState(s, stateFor(phase, parties, unarrived)))
409     break;
410     }
411     return phase;
412     }
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     * @return the barrier phase number upon entry to this method, or a
419     * negative value if terminated
420     * @throws IllegalStateException if not terminated and the number
421     * of unarrived parties would become negative
422     */
423     public int arrive() {
424     int phase;
425     for (;;) {
426     long s = state;
427     phase = phaseOf(s);
428     if (phase < 0)
429     break;
430     int parties = partiesOf(s);
431     int unarrived = unarrivedOf(s) - 1;
432     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     trippedStateFor(onAdvance(phase, parties) ? -1 :
442     ((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     throw new IllegalStateException(badBounds(parties, unarrived));
459     }
460     return phase;
461     }
462    
463     /**
464     * Arrives at the barrier, and deregisters from it, without
465     * waiting for others. Deregistration reduces number of parties
466     * required to trip the barrier in future phases. If this phaser
467     * has a parent, and deregistration causes this phaser to have
468     * zero parties, this phaser is also deregistered from its parent.
469     *
470     * @return the current barrier phase number upon entry to
471     * this method, or a negative value if terminated
472     * @throws IllegalStateException if not terminated and the number
473     * of registered or unarrived parties would become negative
474     */
475     public int arriveAndDeregister() {
476     // similar code to arrive, but too different to merge
477     Phaser par = parent;
478     int phase;
479     for (;;) {
480     long s = state;
481     phase = phaseOf(s);
482     if (phase < 0)
483     break;
484     int parties = partiesOf(s) - 1;
485     int unarrived = unarrivedOf(s) - 1;
486     if (parties >= 0) {
487     if (unarrived > 0 || (unarrived == 0 && par != null)) {
488     if (casState
489     (s,
490     stateFor(phase, parties, unarrived))) {
491     if (unarrived == 0) {
492     par.arriveAndDeregister();
493     reconcileState();
494     }
495     break;
496     }
497     continue;
498     }
499     if (unarrived == 0) {
500     if (casState
501     (s,
502     trippedStateFor(onAdvance(phase, parties) ? -1 :
503     ((phase + 1) & phaseMask), parties))) {
504     releaseWaiters(phase);
505     break;
506     }
507     continue;
508     }
509     if (par != null && phase != phaseOf(root.state)) {
510     reconcileState();
511     continue;
512     }
513     }
514     throw new IllegalStateException(badBounds(parties, unarrived));
515     }
516     return phase;
517     }
518    
519     /**
520     * Arrives at the barrier and awaits others. Equivalent in effect
521     * to {@code awaitAdvance(arrive())}. If you instead need to
522     * await with interruption of timeout, and/or deregister upon
523     * arrival, you can arrange them using analogous constructions.
524     *
525     * @return the phase on entry to this method
526     * @throws IllegalStateException if not terminated and the number
527     * of unarrived parties would become negative
528     */
529     public int arriveAndAwaitAdvance() {
530     return awaitAdvance(arrive());
531     }
532    
533     /**
534     * Awaits the phase of the barrier to advance from the given
535     * value, or returns immediately if argument is negative or this
536     * barrier is terminated.
537     *
538     * @param phase the phase on entry to this method
539     * @return the phase on exit from this method
540     */
541     public int awaitAdvance(int phase) {
542     if (phase < 0)
543     return phase;
544     long s = getReconciledState();
545     int p = phaseOf(s);
546     if (p != phase)
547     return p;
548     if (unarrivedOf(s) == 0 && parent != null)
549     parent.awaitAdvance(phase);
550     // Fall here even if parent waited, to reconcile and help release
551     return untimedWait(phase);
552     }
553    
554     /**
555     * Awaits the phase of the barrier to advance from the given
556     * value, or returns immediately if argument is negative or this
557     * barrier is terminated, or throws InterruptedException if
558     * interrupted while waiting.
559     *
560     * @param phase the phase on entry to this method
561     * @return the phase on exit from this method
562     * @throws InterruptedException if thread interrupted while waiting
563     */
564     public int awaitAdvanceInterruptibly(int phase)
565     throws InterruptedException {
566     if (phase < 0)
567     return phase;
568     long s = getReconciledState();
569     int p = phaseOf(s);
570     if (p != phase)
571     return p;
572     if (unarrivedOf(s) == 0 && parent != null)
573     parent.awaitAdvanceInterruptibly(phase);
574     return interruptibleWait(phase);
575     }
576    
577     /**
578     * Awaits the phase of the barrier to advance from the given value
579     * or the given timeout elapses, or returns immediately if
580     * argument is negative or this barrier is terminated.
581     *
582     * @param phase the phase on entry to this method
583     * @return the phase on exit from this method
584     * @throws InterruptedException if thread interrupted while waiting
585     * @throws TimeoutException if timed out while waiting
586     */
587     public int awaitAdvanceInterruptibly(int phase,
588     long timeout, TimeUnit unit)
589     throws InterruptedException, TimeoutException {
590     if (phase < 0)
591     return phase;
592     long s = getReconciledState();
593     int p = phaseOf(s);
594     if (p != phase)
595     return p;
596     if (unarrivedOf(s) == 0 && parent != null)
597     parent.awaitAdvanceInterruptibly(phase, timeout, unit);
598     return timedWait(phase, unit.toNanos(timeout));
599     }
600    
601     /**
602     * Forces this barrier to enter termination state. Counts of
603     * arrived and registered parties are unaffected. If this phaser
604     * has a parent, it too is terminated. This method may be useful
605     * for coordinating recovery after one or more tasks encounter
606     * unexpected exceptions.
607     */
608     public void forceTermination() {
609     for (;;) {
610     long s = getReconciledState();
611     int phase = phaseOf(s);
612     int parties = partiesOf(s);
613     int unarrived = unarrivedOf(s);
614     if (phase < 0 ||
615     casState(s, stateFor(-1, parties, unarrived))) {
616     releaseWaiters(0);
617     releaseWaiters(1);
618     if (parent != null)
619     parent.forceTermination();
620     return;
621     }
622     }
623     }
624    
625     /**
626     * Returns the current phase number. The maximum phase number is
627     * {@code Integer.MAX_VALUE}, after which it restarts at
628     * zero. Upon termination, the phase number is negative.
629     *
630     * @return the phase number, or a negative value if terminated
631     */
632     public final int getPhase() {
633     return phaseOf(getReconciledState());
634     }
635    
636     /**
637     * Returns {@code true} if the current phase number equals the given phase.
638     *
639     * @param phase the phase
640     * @return {@code true} if the current phase number equals the given phase
641     */
642     public final boolean hasPhase(int phase) {
643     return phaseOf(getReconciledState()) == phase;
644     }
645    
646     /**
647     * Returns the number of parties registered at this barrier.
648     *
649     * @return the number of parties
650     */
651     public int getRegisteredParties() {
652     return partiesOf(state);
653     }
654    
655     /**
656     * Returns the number of parties that have arrived at the current
657     * phase of this barrier.
658     *
659     * @return the number of arrived parties
660     */
661     public int getArrivedParties() {
662     return arrivedOf(state);
663     }
664    
665     /**
666     * Returns the number of registered parties that have not yet
667     * arrived at the current phase of this barrier.
668     *
669     * @return the number of unarrived parties
670     */
671     public int getUnarrivedParties() {
672     return unarrivedOf(state);
673     }
674    
675     /**
676     * Returns the parent of this phaser, or null if none.
677     *
678     * @return the parent of this phaser, or null if none
679     */
680     public Phaser getParent() {
681     return parent;
682     }
683    
684     /**
685     * Returns the root ancestor of this phaser, which is the same as
686     * this phaser if it has no parent.
687     *
688     * @return the root ancestor of this phaser
689     */
690     public Phaser getRoot() {
691     return root;
692     }
693    
694     /**
695     * Returns {@code true} if this barrier has been terminated.
696     *
697     * @return {@code true} if this barrier has been terminated
698     */
699     public boolean isTerminated() {
700     return getPhase() < 0;
701     }
702    
703     /**
704     * Overridable method to perform an action upon phase advance, and
705     * to control termination. This method is invoked whenever the
706     * barrier is tripped (and thus all other waiting parties are
707     * dormant). If it returns true, then, rather than advance the
708     * phase number, this barrier will be set to a final termination
709     * state, and subsequent calls to {@code isTerminated} will
710     * return true.
711     *
712     * <p> The default version returns true when the number of
713     * registered parties is zero. Normally, overrides that arrange
714     * termination for other reasons should also preserve this
715     * property.
716     *
717     * <p> You may override this method to perform an action with side
718     * effects visible to participating tasks, but it is in general
719     * only sensible to do so in designs where all parties register
720     * before any arrive, and all {@code awaitAdvance} at each phase.
721     * Otherwise, you cannot ensure lack of interference. In
722     * particular, this method may be invoked more than once per
723     * transition if other parties successfully register while the
724     * invocation of this method is in progress, thus postponing the
725     * transition until those parties also arrive, re-triggering this
726     * method.
727     *
728     * @param phase the phase number on entering the barrier
729     * @param registeredParties the current number of registered parties
730     * @return {@code true} if this barrier should terminate
731     */
732     protected boolean onAdvance(int phase, int registeredParties) {
733     return registeredParties <= 0;
734     }
735    
736     /**
737     * Returns a string identifying this phaser, as well as its
738     * state. The state, in brackets, includes the String {@code
739     * "phase = "} followed by the phase number, {@code "parties = "}
740     * followed by the number of registered parties, and {@code
741     * "arrived = "} followed by the number of arrived parties.
742     *
743     * @return a string identifying this barrier, as well as its state
744     */
745     public String toString() {
746     long s = getReconciledState();
747     return super.toString() +
748     "[phase = " + phaseOf(s) +
749     " parties = " + partiesOf(s) +
750     " arrived = " + arrivedOf(s) + "]";
751     }
752    
753     // methods for waiting
754    
755     /**
756     * Wait nodes for Treiber stack representing wait queue
757     */
758     static final class QNode implements ForkJoinPool.ManagedBlocker {
759     final Phaser phaser;
760     final int phase;
761     final long startTime;
762     final long nanos;
763     final boolean timed;
764     final boolean interruptible;
765     volatile boolean wasInterrupted = false;
766     volatile Thread thread; // nulled to cancel wait
767     QNode next;
768     QNode(Phaser phaser, int phase, boolean interruptible,
769     boolean timed, long startTime, long nanos) {
770     this.phaser = phaser;
771     this.phase = phase;
772     this.timed = timed;
773     this.interruptible = interruptible;
774     this.startTime = startTime;
775     this.nanos = nanos;
776     thread = Thread.currentThread();
777     }
778     public boolean isReleasable() {
779     return (thread == null ||
780     phaser.getPhase() != phase ||
781     (interruptible && wasInterrupted) ||
782     (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
783     }
784     public boolean block() {
785     if (Thread.interrupted()) {
786     wasInterrupted = true;
787     if (interruptible)
788     return true;
789     }
790     if (!timed)
791     LockSupport.park(this);
792     else {
793     long waitTime = nanos - (System.nanoTime() - startTime);
794     if (waitTime <= 0)
795     return true;
796     LockSupport.parkNanos(this, waitTime);
797     }
798     return isReleasable();
799     }
800     void signal() {
801     Thread t = thread;
802     if (t != null) {
803     thread = null;
804     LockSupport.unpark(t);
805     }
806     }
807     boolean doWait() {
808     if (thread != null) {
809     try {
810     ForkJoinPool.managedBlock(this, false);
811     } catch (InterruptedException ie) {
812     }
813     }
814     return wasInterrupted;
815     }
816    
817     }
818    
819     /**
820     * Removes and signals waiting threads from wait queue.
821     */
822     private void releaseWaiters(int phase) {
823     AtomicReference<QNode> head = queueFor(phase);
824     QNode q;
825     while ((q = head.get()) != null) {
826     if (head.compareAndSet(q, q.next))
827     q.signal();
828     }
829     }
830    
831     /**
832     * Tries to enqueue given node in the appropriate wait queue.
833     *
834     * @return true if successful
835     */
836     private boolean tryEnqueue(QNode node) {
837     AtomicReference<QNode> head = queueFor(node.phase);
838     return head.compareAndSet(node.next = head.get(), node);
839     }
840    
841     /**
842     * Enqueues node and waits unless aborted or signalled.
843     *
844     * @return current phase
845     */
846     private int untimedWait(int phase) {
847     QNode node = null;
848     boolean queued = false;
849     boolean interrupted = false;
850     int p;
851     while ((p = getPhase()) == phase) {
852     if (Thread.interrupted())
853     interrupted = true;
854     else if (node == null)
855     node = new QNode(this, phase, false, false, 0, 0);
856     else if (!queued)
857     queued = tryEnqueue(node);
858     else
859     interrupted = node.doWait();
860     }
861     if (node != null)
862     node.thread = null;
863     releaseWaiters(phase);
864     if (interrupted)
865     Thread.currentThread().interrupt();
866     return p;
867     }
868    
869     /**
870     * Interruptible version
871     * @return current phase
872     */
873     private int interruptibleWait(int phase) throws InterruptedException {
874     QNode node = null;
875     boolean queued = false;
876     boolean interrupted = false;
877     int p;
878     while ((p = getPhase()) == phase && !interrupted) {
879     if (Thread.interrupted())
880     interrupted = true;
881     else if (node == null)
882     node = new QNode(this, phase, true, false, 0, 0);
883     else if (!queued)
884     queued = tryEnqueue(node);
885     else
886     interrupted = node.doWait();
887     }
888     if (node != null)
889     node.thread = null;
890     if (p != phase || (p = getPhase()) != phase)
891     releaseWaiters(phase);
892     if (interrupted)
893     throw new InterruptedException();
894     return p;
895     }
896    
897     /**
898     * Timeout version.
899     * @return current phase
900     */
901     private int timedWait(int phase, long nanos)
902     throws InterruptedException, TimeoutException {
903     long startTime = System.nanoTime();
904     QNode node = null;
905     boolean queued = false;
906     boolean interrupted = false;
907     int p;
908     while ((p = getPhase()) == phase && !interrupted) {
909     if (Thread.interrupted())
910     interrupted = true;
911     else if (nanos - (System.nanoTime() - startTime) <= 0)
912     break;
913     else if (node == null)
914     node = new QNode(this, phase, true, true, startTime, nanos);
915     else if (!queued)
916     queued = tryEnqueue(node);
917     else
918     interrupted = node.doWait();
919     }
920     if (node != null)
921     node.thread = null;
922     if (p != phase || (p = getPhase()) != phase)
923     releaseWaiters(phase);
924     if (interrupted)
925     throw new InterruptedException();
926     if (p == phase)
927     throw new TimeoutException();
928     return p;
929     }
930    
931     // Unsafe mechanics
932    
933     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
934 jsr166 1.2 private static final long stateOffset =
935 jsr166 1.3 objectFieldOffset("state", Phaser.class);
936 jsr166 1.1
937 jsr166 1.2 private final boolean casState(long cmp, long val) {
938 jsr166 1.1 return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
939     }
940 jsr166 1.3
941     private static long objectFieldOffset(String field, Class<?> klazz) {
942     try {
943     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
944     } catch (NoSuchFieldException e) {
945     // Convert Exception to corresponding Error
946     NoSuchFieldError error = new NoSuchFieldError(field);
947     error.initCause(e);
948     throw error;
949     }
950     }
951 jsr166 1.1 }