ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.10
Committed: Tue Jan 6 14:30:31 2009 UTC (15 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.9: +148 -128 lines
Log Message:
Refactored and repackaged ForkJoin classes

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