ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.17
Committed: Thu Jul 23 19:25:45 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.16: +6 -6 lines
Log Message:
j.u.c. coding standards

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