ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.19
Committed: Fri Jul 24 23:47:01 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.18: +23 -26 lines
Log Message:
Unsafe mechanics

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