ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.13
Committed: Mon Jul 20 22:40:09 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.12: +49 -53 lines
Log Message:
<pre> => <pre> @code

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 jsr166 1.13 * <pre> {@code
97     * void runTasks(List<Runnable> 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 dl 1.4 * }
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 jsr166 1.13 * }}</pre>
117 dl 1.1 *
118 dl 1.4 * <p>One way to cause a set of threads to repeatedly perform actions
119 jsr166 1.7 * for a given number of iterations is to override {@code onAdvance}:
120 dl 1.1 *
121 jsr166 1.13 * <pre> {@code
122     * void startTasks(List<Runnable> list, final int iterations) {
123     * final Phaser phaser = new Phaser() {
124     * public boolean onAdvance(int phase, int registeredParties) {
125     * return phase >= iterations || registeredParties == 0;
126     * }
127     * };
128     * phaser.register();
129     * for (Runnable r : list) {
130     * phaser.register();
131     * new Thread() {
132     * public void run() {
133     * do {
134     * r.run();
135     * phaser.arriveAndAwaitAdvance();
136     * } while(!phaser.isTerminated();
137 dl 1.4 * }
138 jsr166 1.13 * }.start();
139 dl 1.1 * }
140 dl 1.4 * phaser.arriveAndDeregister(); // deregister self, don't wait
141 jsr166 1.13 * }}</pre>
142 dl 1.1 *
143 dl 1.4 * <p> To create a set of tasks using a tree of Phasers,
144     * you could use code of the following form, assuming a
145     * Task class with a constructor accepting a Phaser that
146     * it registers for upon construction:
147 jsr166 1.13 * <pre> {@code
148     * void build(Task[] actions, int lo, int hi, Phaser b) {
149     * int step = (hi - lo) / TASKS_PER_PHASER;
150     * if (step > 1) {
151     * int i = lo;
152     * while (i < hi) {
153     * int r = Math.min(i + step, hi);
154     * build(actions, i, r, new Phaser(b));
155     * i = r;
156     * }
157     * } else {
158     * for (int i = lo; i < hi; ++i)
159     * actions[i] = new Task(b);
160     * // assumes new Task(b) performs b.register()
161     * }
162     * }
163     * // .. initially called, for n tasks via
164     * build(new Task[n], 0, n, new Phaser());}</pre>
165 dl 1.4 *
166 jsr166 1.7 * The best value of {@code TASKS_PER_PHASER} depends mainly on
167 dl 1.4 * expected barrier synchronization rates. A value as low as four may
168     * be appropriate for extremely small per-barrier task bodies (thus
169     * high rates), or up to hundreds for extremely large ones.
170     *
171     * </pre>
172     *
173 dl 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
174 dl 1.4 * maximum number of parties to 65535. Attempts to register additional
175     * parties result in IllegalStateExceptions. However, you can and
176     * should create tiered phasers to accommodate arbitrarily large sets
177     * of participants.
178 dl 1.1 */
179     public class Phaser {
180     /*
181     * This class implements an extension of X10 "clocks". Thanks to
182 dl 1.4 * Vijay Saraswat for the idea, and to Vivek Sarkar for
183     * enhancements to extend functionality.
184 dl 1.1 */
185    
186     /**
187     * Barrier state representation. Conceptually, a barrier contains
188     * four values:
189 jsr166 1.3 *
190 dl 1.1 * * parties -- the number of parties to wait (16 bits)
191     * * unarrived -- the number of parties yet to hit barrier (16 bits)
192     * * phase -- the generation of the barrier (31 bits)
193     * * terminated -- set if barrier is terminated (1 bit)
194     *
195     * However, to efficiently maintain atomicity, these values are
196 dl 1.4 * packed into a single (atomic) long. Termination uses the sign
197     * bit of 32 bit representation of phase, so phase is set to -1 on
198 jsr166 1.8 * termination. Good performance relies on keeping state decoding
199 dl 1.4 * and encoding simple, and keeping race windows short.
200     *
201     * Note: there are some cheats in arrive() that rely on unarrived
202 dl 1.10 * count being lowest 16 bits.
203 dl 1.1 */
204 dl 1.4 private volatile long state;
205 dl 1.1
206     private static final int ushortBits = 16;
207 dl 1.10 private static final int ushortMask = 0xffff;
208     private static final int phaseMask = 0x7fffffff;
209 dl 1.1
210     private static int unarrivedOf(long s) {
211     return (int)(s & ushortMask);
212     }
213    
214     private static int partiesOf(long s) {
215 dl 1.10 return ((int)s) >>> 16;
216 dl 1.1 }
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 dl 1.10 return ((((long)phase) << 32) | (((long)parties) << 16) |
228     (long)unarrived);
229 dl 1.1 }
230    
231 dl 1.4 private static long trippedStateFor(int phase, int parties) {
232 dl 1.10 long lp = (long)parties;
233     return (((long)phase) << 32) | (lp << 16) | lp;
234 dl 1.4 }
235    
236 dl 1.10 /**
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 dl 1.4 }
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 dl 1.10 * Heads of Treiber stacks for waiting threads. To eliminate
259 dl 1.4 * contention while releasing some threads while adding others, we
260     * use two of them, alternating across even and odd phases.
261     */
262     private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
263     private final AtomicReference<QNode> oddQ = new AtomicReference<QNode>();
264    
265     private AtomicReference<QNode> queueFor(int phase) {
266     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 dl 1.1 }
299    
300     /**
301     * Creates a new Phaser without any initially registered parties,
302 dl 1.10 * initial phase number 0, and no parent. Any thread using this
303     * Phaser will need to first register for it.
304 dl 1.1 */
305     public Phaser() {
306 dl 1.4 this(null);
307 dl 1.1 }
308    
309     /**
310     * Creates a new Phaser with the given numbers of registered
311 dl 1.4 * unarrived parties, initial phase number 0, and no parent.
312 dl 1.1 * @param parties the number of parties required to trip barrier.
313     * @throws IllegalArgumentException if parties less than zero
314     * or greater than the maximum number of parties supported.
315     */
316     public Phaser(int parties) {
317 dl 1.4 this(null, parties);
318     }
319    
320     /**
321     * Creates a new Phaser with the given parent, without any
322     * initially registered parties. If parent is non-null this phaser
323     * is registered with the parent and its initial phase number is
324     * the same as that of parent phaser.
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     * Creates a new Phaser with the given parent and numbers of
341     * 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     * @param parent the parent phaser.
345     * @param parties the number of parties required to trip barrier.
346     * @throws IllegalArgumentException if parties less than zero
347     * or greater than the maximum number of parties supported.
348     */
349     public Phaser(Phaser parent, int parties) {
350 dl 1.1 if (parties < 0 || parties > ushortMask)
351     throw new IllegalArgumentException("Illegal number of parties");
352 dl 1.4 int phase = 0;
353     this.parent = parent;
354     if (parent != null) {
355     this.root = parent.root;
356     phase = parent.register();
357     }
358     else
359     this.root = this;
360     this.state = trippedStateFor(phase, parties);
361 dl 1.1 }
362    
363     /**
364     * Adds a new unarrived party to this phaser.
365     * @return the current barrier phase number upon registration
366     * @throws IllegalStateException if attempting to register more
367     * than the maximum supported number of parties.
368     */
369 dl 1.4 public int register() {
370     return doRegister(1);
371     }
372    
373     /**
374     * Adds the given number of new unarrived parties to this phaser.
375     * @param parties the number of parties required to trip barrier.
376     * @return the current barrier phase number upon registration
377     * @throws IllegalStateException if attempting to register more
378     * than the maximum supported number of parties.
379     */
380     public int bulkRegister(int parties) {
381     if (parties < 0)
382     throw new IllegalArgumentException();
383     if (parties == 0)
384     return getPhase();
385     return doRegister(parties);
386     }
387    
388     /**
389     * Shared code for register, bulkRegister
390     */
391     private int doRegister(int registrations) {
392     int phase;
393 dl 1.1 for (;;) {
394 dl 1.4 long s = getReconciledState();
395     phase = phaseOf(s);
396     int unarrived = unarrivedOf(s) + registrations;
397     int parties = partiesOf(s) + registrations;
398 jsr166 1.12 if (phase < 0)
399 dl 1.4 break;
400 dl 1.1 if (parties > ushortMask || unarrived > ushortMask)
401 dl 1.10 throw new IllegalStateException(badBounds(parties, unarrived));
402 dl 1.4 if (phase == phaseOf(root.state) &&
403     casState(s, stateFor(phase, parties, unarrived)))
404     break;
405 dl 1.1 }
406 dl 1.4 return phase;
407 dl 1.1 }
408    
409     /**
410     * Arrives at the barrier, but does not wait for others. (You can
411     * in turn wait for others via {@link #awaitAdvance}).
412     *
413 dl 1.4 * @return the barrier phase number upon entry to this method, or a
414     * negative value if terminated;
415     * @throws IllegalStateException if not terminated and the number
416     * of unarrived parties would become negative.
417 dl 1.1 */
418 dl 1.4 public int arrive() {
419     int phase;
420 dl 1.1 for (;;) {
421 dl 1.4 long s = state;
422     phase = phaseOf(s);
423 dl 1.10 if (phase < 0)
424     break;
425 dl 1.1 int parties = partiesOf(s);
426     int unarrived = unarrivedOf(s) - 1;
427 dl 1.4 if (unarrived > 0) { // Not the last arrival
428     if (casState(s, s - 1)) // s-1 adds one arrival
429     break;
430     }
431     else if (unarrived == 0) { // the last arrival
432     Phaser par = parent;
433     if (par == null) { // directly trip
434     if (casState
435     (s,
436     trippedStateFor(onAdvance(phase, parties)? -1 :
437     ((phase + 1) & phaseMask), parties))) {
438     releaseWaiters(phase);
439     break;
440     }
441     }
442     else { // cascade to parent
443     if (casState(s, s - 1)) { // zeroes unarrived
444     par.arrive();
445     reconcileState();
446     break;
447     }
448     }
449     }
450     else if (phase != phaseOf(root.state)) // or if unreconciled
451     reconcileState();
452     else
453 dl 1.10 throw new IllegalStateException(badBounds(parties, unarrived));
454 dl 1.1 }
455 dl 1.4 return phase;
456 dl 1.1 }
457    
458     /**
459     * Arrives at the barrier, and deregisters from it, without
460 dl 1.4 * waiting for others. Deregistration reduces number of parties
461     * required to trip the barrier in future phases. If this phaser
462     * has a parent, and deregistration causes this phaser to have
463     * zero parties, this phaser is also deregistered from its parent.
464 dl 1.1 *
465     * @return the current barrier phase number upon entry to
466     * this method, or a negative value if terminated;
467 dl 1.4 * @throws IllegalStateException if not terminated and the number
468     * of registered or unarrived parties would become negative.
469 dl 1.1 */
470 dl 1.4 public int arriveAndDeregister() {
471     // similar code to arrive, but too different to merge
472     Phaser par = parent;
473     int phase;
474 dl 1.1 for (;;) {
475 dl 1.4 long s = state;
476     phase = phaseOf(s);
477 dl 1.10 if (phase < 0)
478     break;
479 dl 1.1 int parties = partiesOf(s) - 1;
480     int unarrived = unarrivedOf(s) - 1;
481 dl 1.4 if (parties >= 0) {
482     if (unarrived > 0 || (unarrived == 0 && par != null)) {
483     if (casState
484     (s,
485     stateFor(phase, parties, unarrived))) {
486     if (unarrived == 0) {
487     par.arriveAndDeregister();
488     reconcileState();
489     }
490     break;
491     }
492     continue;
493     }
494     if (unarrived == 0) {
495     if (casState
496     (s,
497     trippedStateFor(onAdvance(phase, parties)? -1 :
498     ((phase + 1) & phaseMask), parties))) {
499     releaseWaiters(phase);
500     break;
501     }
502     continue;
503     }
504     if (par != null && phase != phaseOf(root.state)) {
505     reconcileState();
506     continue;
507     }
508 dl 1.1 }
509 dl 1.10 throw new IllegalStateException(badBounds(parties, unarrived));
510 dl 1.1 }
511 dl 1.4 return phase;
512 dl 1.1 }
513    
514     /**
515 dl 1.4 * Arrives at the barrier and awaits others. Equivalent in effect
516 jsr166 1.7 * to {@code awaitAdvance(arrive())}. If you instead need to
517 dl 1.4 * await with interruption of timeout, and/or deregister upon
518     * arrival, you can arrange them using analogous constructions.
519     * @return the phase on entry to this method
520     * @throws IllegalStateException if not terminated and the number
521     * of unarrived parties would become negative.
522 dl 1.1 */
523     public int arriveAndAwaitAdvance() {
524 dl 1.4 return awaitAdvance(arrive());
525 dl 1.1 }
526    
527     /**
528     * Awaits the phase of the barrier to advance from the given
529 dl 1.4 * value, or returns immediately if argument is negative or this
530     * barrier is terminated.
531 dl 1.1 * @param phase the phase on entry to this method
532     * @return the phase on exit from this method
533     */
534     public int awaitAdvance(int phase) {
535     if (phase < 0)
536     return phase;
537 dl 1.4 long s = getReconciledState();
538     int p = phaseOf(s);
539     if (p != phase)
540     return p;
541 dl 1.10 if (unarrivedOf(s) == 0 && parent != null)
542 dl 1.4 parent.awaitAdvance(phase);
543     // Fall here even if parent waited, to reconcile and help release
544     return untimedWait(phase);
545 dl 1.1 }
546    
547     /**
548     * Awaits the phase of the barrier to advance from the given
549 jsr166 1.8 * value, or returns immediately if argument is negative or this
550 dl 1.4 * barrier is terminated, or throws InterruptedException if
551     * interrupted while waiting.
552 dl 1.1 * @param phase the phase on entry to this method
553     * @return the phase on exit from this method
554     * @throws InterruptedException if thread interrupted while waiting
555     */
556 jsr166 1.12 public int awaitAdvanceInterruptibly(int phase)
557 dl 1.10 throws InterruptedException {
558 dl 1.1 if (phase < 0)
559     return phase;
560 dl 1.4 long s = getReconciledState();
561     int p = phaseOf(s);
562     if (p != phase)
563     return p;
564 dl 1.10 if (unarrivedOf(s) == 0 && parent != null)
565 dl 1.4 parent.awaitAdvanceInterruptibly(phase);
566     return interruptibleWait(phase);
567 dl 1.1 }
568    
569     /**
570     * Awaits the phase of the barrier to advance from the given value
571 dl 1.4 * or the given timeout elapses, or returns immediately if
572     * argument is negative or this barrier is terminated.
573 dl 1.1 * @param phase the phase on entry to this method
574     * @return the phase on exit from this method
575     * @throws InterruptedException if thread interrupted while waiting
576     * @throws TimeoutException if timed out while waiting
577     */
578 jsr166 1.3 public int awaitAdvanceInterruptibly(int phase, long timeout, TimeUnit unit)
579 dl 1.1 throws InterruptedException, TimeoutException {
580     if (phase < 0)
581     return phase;
582 dl 1.4 long s = getReconciledState();
583     int p = phaseOf(s);
584     if (p != phase)
585     return p;
586 dl 1.10 if (unarrivedOf(s) == 0 && parent != null)
587 dl 1.4 parent.awaitAdvanceInterruptibly(phase, timeout, unit);
588     return timedWait(phase, unit.toNanos(timeout));
589 dl 1.1 }
590    
591     /**
592     * Forces this barrier to enter termination state. Counts of
593 dl 1.4 * arrived and registered parties are unaffected. If this phaser
594     * has a parent, it too is terminated. This method may be useful
595     * for coordinating recovery after one or more tasks encounter
596     * unexpected exceptions.
597 dl 1.1 */
598     public void forceTermination() {
599     for (;;) {
600 dl 1.4 long s = getReconciledState();
601 dl 1.1 int phase = phaseOf(s);
602     int parties = partiesOf(s);
603     int unarrived = unarrivedOf(s);
604     if (phase < 0 ||
605 dl 1.4 casState(s, stateFor(-1, parties, unarrived))) {
606     releaseWaiters(0);
607     releaseWaiters(1);
608     if (parent != null)
609     parent.forceTermination();
610 dl 1.1 return;
611     }
612     }
613     }
614    
615     /**
616 dl 1.4 * Returns the current phase number. The maximum phase number is
617 jsr166 1.7 * {@code Integer.MAX_VALUE}, after which it restarts at
618 dl 1.4 * zero. Upon termination, the phase number is negative.
619     * @return the phase number, or a negative value if terminated
620 dl 1.1 */
621 dl 1.4 public final int getPhase() {
622     return phaseOf(getReconciledState());
623 dl 1.1 }
624    
625     /**
626 jsr166 1.9 * Returns {@code true} if the current phase number equals the given phase.
627 dl 1.4 * @param phase the phase
628 jsr166 1.9 * @return {@code true} if the current phase number equals the given phase
629 dl 1.1 */
630 dl 1.4 public final boolean hasPhase(int phase) {
631     return phaseOf(getReconciledState()) == phase;
632 dl 1.1 }
633    
634     /**
635     * Returns the number of parties registered at this barrier.
636     * @return the number of parties
637     */
638     public int getRegisteredParties() {
639 dl 1.4 return partiesOf(state);
640 dl 1.1 }
641    
642     /**
643     * Returns the number of parties that have arrived at the current
644     * phase of this barrier.
645     * @return the number of arrived parties
646     */
647     public int getArrivedParties() {
648 dl 1.4 return arrivedOf(state);
649 dl 1.1 }
650    
651     /**
652     * Returns the number of registered parties that have not yet
653     * arrived at the current phase of this barrier.
654     * @return the number of unarrived parties
655     */
656     public int getUnarrivedParties() {
657 dl 1.4 return unarrivedOf(state);
658     }
659    
660     /**
661     * Returns the parent of this phaser, or null if none.
662 jsr166 1.9 * @return the parent of this phaser, or null if none
663 dl 1.4 */
664     public Phaser getParent() {
665     return parent;
666     }
667    
668     /**
669     * Returns the root ancestor of this phaser, which is the same as
670     * this phaser if it has no parent.
671 jsr166 1.9 * @return the root ancestor of this phaser
672 dl 1.4 */
673     public Phaser getRoot() {
674     return root;
675 dl 1.1 }
676    
677     /**
678 jsr166 1.9 * Returns {@code true} if this barrier has been terminated.
679     * @return {@code true} if this barrier has been terminated
680 dl 1.1 */
681     public boolean isTerminated() {
682 dl 1.4 return getPhase() < 0;
683 dl 1.1 }
684    
685     /**
686     * Overridable method to perform an action upon phase advance, and
687     * to control termination. This method is invoked whenever the
688     * barrier is tripped (and thus all other waiting parties are
689     * dormant). If it returns true, then, rather than advance the
690     * phase number, this barrier will be set to a final termination
691 jsr166 1.7 * state, and subsequent calls to {@code isTerminated} will
692 dl 1.1 * return true.
693 jsr166 1.3 *
694 dl 1.1 * <p> The default version returns true when the number of
695     * registered parties is zero. Normally, overrides that arrange
696     * termination for other reasons should also preserve this
697     * property.
698     *
699 dl 1.4 * <p> You may override this method to perform an action with side
700     * effects visible to participating tasks, but it is in general
701     * only sensible to do so in designs where all parties register
702 jsr166 1.7 * before any arrive, and all {@code awaitAdvance} at each phase.
703 dl 1.4 * Otherwise, you cannot ensure lack of interference. In
704     * particular, this method may be invoked more than once per
705     * transition if other parties successfully register while the
706     * invocation of this method is in progress, thus postponing the
707     * transition until those parties also arrive, re-triggering this
708     * method.
709     *
710 dl 1.1 * @param phase the phase number on entering the barrier
711 jsr166 1.9 * @param registeredParties the current number of registered parties
712     * @return {@code true} if this barrier should terminate
713 dl 1.1 */
714     protected boolean onAdvance(int phase, int registeredParties) {
715     return registeredParties <= 0;
716     }
717    
718     /**
719 dl 1.4 * Returns a string identifying this phaser, as well as its
720 dl 1.1 * state. The state, in brackets, includes the String {@code
721 jsr166 1.9 * "phase = "} followed by the phase number, {@code "parties = "}
722 dl 1.1 * followed by the number of registered parties, and {@code
723 jsr166 1.9 * "arrived = "} followed by the number of arrived parties.
724 dl 1.1 *
725     * @return a string identifying this barrier, as well as its state
726     */
727     public String toString() {
728 dl 1.4 long s = getReconciledState();
729 jsr166 1.9 return super.toString() +
730     "[phase = " + phaseOf(s) +
731     " parties = " + partiesOf(s) +
732     " arrived = " + arrivedOf(s) + "]";
733 dl 1.1 }
734    
735 dl 1.4 // methods for waiting
736 dl 1.1
737     /**
738 dl 1.10 * Wait nodes for Treiber stack representing wait queue
739 dl 1.1 */
740 dl 1.10 static final class QNode implements ForkJoinPool.ManagedBlocker {
741     final Phaser phaser;
742     final int phase;
743     final long startTime;
744     final long nanos;
745     final boolean timed;
746     final boolean interruptible;
747     volatile boolean wasInterrupted = false;
748     volatile Thread thread; // nulled to cancel wait
749 dl 1.4 QNode next;
750 dl 1.10 QNode(Phaser phaser, int phase, boolean interruptible,
751     boolean timed, long startTime, long nanos) {
752     this.phaser = phaser;
753     this.phase = phase;
754     this.timed = timed;
755     this.interruptible = interruptible;
756     this.startTime = startTime;
757     this.nanos = nanos;
758 dl 1.4 thread = Thread.currentThread();
759     }
760 dl 1.10 public boolean isReleasable() {
761     return (thread == null ||
762     phaser.getPhase() != phase ||
763     (interruptible && wasInterrupted) ||
764     (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
765     }
766     public boolean block() {
767     if (Thread.interrupted()) {
768     wasInterrupted = true;
769     if (interruptible)
770     return true;
771     }
772     if (!timed)
773     LockSupport.park(this);
774     else {
775     long waitTime = nanos - (System.nanoTime() - startTime);
776     if (waitTime <= 0)
777     return true;
778     LockSupport.parkNanos(this, waitTime);
779     }
780     return isReleasable();
781     }
782 dl 1.4 void signal() {
783     Thread t = thread;
784     if (t != null) {
785     thread = null;
786     LockSupport.unpark(t);
787     }
788     }
789 dl 1.10 boolean doWait() {
790     if (thread != null) {
791     try {
792     ForkJoinPool.managedBlock(this, false);
793     } catch (InterruptedException ie) {
794 jsr166 1.12 }
795 dl 1.10 }
796     return wasInterrupted;
797     }
798    
799 dl 1.4 }
800    
801     /**
802     * Removes and signals waiting threads from wait queue
803     */
804     private void releaseWaiters(int phase) {
805     AtomicReference<QNode> head = queueFor(phase);
806     QNode q;
807     while ((q = head.get()) != null) {
808     if (head.compareAndSet(q, q.next))
809     q.signal();
810     }
811     }
812    
813     /**
814 dl 1.10 * Tries to enqueue given node in the appropriate wait queue
815     * @return true if successful
816     */
817     private boolean tryEnqueue(QNode node) {
818     AtomicReference<QNode> head = queueFor(node.phase);
819     return head.compareAndSet(node.next = head.get(), node);
820     }
821    
822     /**
823 dl 1.1 * Enqueues node and waits unless aborted or signalled.
824 dl 1.10 * @return current phase
825 dl 1.1 */
826 dl 1.4 private int untimedWait(int phase) {
827 dl 1.1 QNode node = null;
828 dl 1.10 boolean queued = false;
829 dl 1.4 boolean interrupted = false;
830     int p;
831     while ((p = getPhase()) == phase) {
832 dl 1.10 if (Thread.interrupted())
833     interrupted = true;
834     else if (node == null)
835     node = new QNode(this, phase, false, false, 0, 0);
836     else if (!queued)
837     queued = tryEnqueue(node);
838 dl 1.4 else
839 dl 1.10 interrupted = node.doWait();
840 dl 1.4 }
841     if (node != null)
842     node.thread = null;
843 dl 1.10 releaseWaiters(phase);
844 dl 1.4 if (interrupted)
845     Thread.currentThread().interrupt();
846     return p;
847     }
848    
849     /**
850 dl 1.10 * Interruptible version
851     * @return current phase
852 dl 1.4 */
853     private int interruptibleWait(int phase) throws InterruptedException {
854     QNode node = null;
855     boolean queued = false;
856     boolean interrupted = false;
857     int p;
858 dl 1.10 while ((p = getPhase()) == phase && !interrupted) {
859     if (Thread.interrupted())
860     interrupted = true;
861     else if (node == null)
862     node = new QNode(this, phase, true, false, 0, 0);
863     else if (!queued)
864     queued = tryEnqueue(node);
865 dl 1.1 else
866 dl 1.10 interrupted = node.doWait();
867 dl 1.1 }
868     if (node != null)
869     node.thread = null;
870 dl 1.10 if (p != phase || (p = getPhase()) != phase)
871     releaseWaiters(phase);
872 dl 1.4 if (interrupted)
873     throw new InterruptedException();
874     return p;
875 dl 1.1 }
876    
877     /**
878 dl 1.10 * Timeout version.
879     * @return current phase
880 dl 1.1 */
881 dl 1.4 private int timedWait(int phase, long nanos)
882 dl 1.1 throws InterruptedException, TimeoutException {
883 dl 1.10 long startTime = System.nanoTime();
884     QNode node = null;
885     boolean queued = false;
886     boolean interrupted = false;
887 dl 1.4 int p;
888 dl 1.10 while ((p = getPhase()) == phase && !interrupted) {
889     if (Thread.interrupted())
890     interrupted = true;
891     else if (nanos - (System.nanoTime() - startTime) <= 0)
892     break;
893     else if (node == null)
894     node = new QNode(this, phase, true, true, startTime, nanos);
895     else if (!queued)
896     queued = tryEnqueue(node);
897     else
898     interrupted = node.doWait();
899 dl 1.4 }
900 dl 1.10 if (node != null)
901     node.thread = null;
902     if (p != phase || (p = getPhase()) != phase)
903     releaseWaiters(phase);
904     if (interrupted)
905     throw new InterruptedException();
906     if (p == phase)
907     throw new TimeoutException();
908 dl 1.4 return p;
909     }
910    
911     // Temporary Unsafe mechanics for preliminary release
912 jsr166 1.11 private static Unsafe getUnsafe() throws Throwable {
913     try {
914     return Unsafe.getUnsafe();
915     } catch (SecurityException se) {
916     try {
917     return java.security.AccessController.doPrivileged
918     (new java.security.PrivilegedExceptionAction<Unsafe>() {
919     public Unsafe run() throws Exception {
920     return getUnsafePrivileged();
921     }});
922     } catch (java.security.PrivilegedActionException e) {
923     throw e.getCause();
924     }
925     }
926     }
927    
928     private static Unsafe getUnsafePrivileged()
929     throws NoSuchFieldException, IllegalAccessException {
930     Field f = Unsafe.class.getDeclaredField("theUnsafe");
931     f.setAccessible(true);
932 jsr166 1.12 return (Unsafe) f.get(null);
933 jsr166 1.11 }
934    
935     private static long fieldOffset(String fieldName)
936     throws NoSuchFieldException {
937     return _unsafe.objectFieldOffset
938     (Phaser.class.getDeclaredField(fieldName));
939     }
940 dl 1.4
941     static final Unsafe _unsafe;
942     static final long stateOffset;
943    
944     static {
945     try {
946 jsr166 1.11 _unsafe = getUnsafe();
947     stateOffset = fieldOffset("state");
948 jsr166 1.12 } catch (Throwable e) {
949 dl 1.4 throw new RuntimeException("Could not initialize intrinsics", e);
950 dl 1.1 }
951     }
952    
953 dl 1.4 final boolean casState(long cmp, long val) {
954     return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val);
955     }
956 dl 1.1 }