ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.46
Committed: Fri Dec 3 22:07:08 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.45: +1 -1 lines
Log Message:
s/MAX_PARTIES/UNARRIVED_MASK/

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8
9 import java.util.concurrent.TimeUnit;
10 import java.util.concurrent.TimeoutException;
11 import java.util.concurrent.atomic.AtomicReference;
12 import java.util.concurrent.locks.LockSupport;
13
14 /**
15 * A reusable synchronization barrier, similar in functionality to
16 * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
17 * {@link java.util.concurrent.CountDownLatch CountDownLatch}
18 * but supporting more flexible usage.
19 *
20 * <p> <b>Registration.</b> Unlike the case for other barriers, the
21 * number of parties <em>registered</em> to synchronize on a phaser
22 * may vary over time. Tasks may be registered at any time (using
23 * methods {@link #register}, {@link #bulkRegister}, or forms of
24 * constructors establishing initial numbers of parties), and
25 * optionally deregistered upon any arrival (using {@link
26 * #arriveAndDeregister}). As is the case with most basic
27 * synchronization constructs, registration and deregistration affect
28 * only internal counts; they do not establish any further internal
29 * bookkeeping, so tasks cannot query whether they are registered.
30 * (However, you can introduce such bookkeeping by subclassing this
31 * class.)
32 *
33 * <p> <b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
34 * Phaser} may be repeatedly awaited. Method {@link
35 * #arriveAndAwaitAdvance} has effect analogous to {@link
36 * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
37 * generation of a phaser has an associated phase number. The phase
38 * number starts at zero, and advances when all parties arrive at the
39 * phaser, wrapping around to zero after reaching {@code
40 * Integer.MAX_VALUE}. The use of phase numbers enables independent
41 * control of actions upon arrival at a phaser and upon awaiting
42 * others, via two kinds of methods that may be invoked by any
43 * registered party:
44 *
45 * <ul>
46 *
47 * <li> <b>Arrival.</b> Methods {@link #arrive} and
48 * {@link #arriveAndDeregister} record arrival. These methods
49 * do not block, but return an associated <em>arrival phase
50 * number</em>; that is, the phase number of the phaser to which
51 * the arrival applied. When the final party for a given phase
52 * arrives, an optional action is performed and the phase
53 * advances. These actions are performed by the party
54 * triggering a phase advance, and are arranged by overriding
55 * method {@link #onAdvance(int, int)}, which also controls
56 * termination. Overriding this method is similar to, but more
57 * flexible than, providing a barrier action to a {@code
58 * CyclicBarrier}.
59 *
60 * <li> <b>Waiting.</b> Method {@link #awaitAdvance} requires an
61 * argument indicating an arrival phase number, and returns when
62 * the phaser advances to (or is already at) a different phase.
63 * Unlike similar constructions using {@code CyclicBarrier},
64 * method {@code awaitAdvance} continues to wait even if the
65 * waiting thread is interrupted. Interruptible and timeout
66 * versions are also available, but exceptions encountered while
67 * tasks wait interruptibly or with timeout do not change the
68 * state of the phaser. If necessary, you can perform any
69 * associated recovery within handlers of those exceptions,
70 * often after invoking {@code forceTermination}. Phasers may
71 * also be used by tasks executing in a {@link ForkJoinPool},
72 * which will ensure sufficient parallelism to execute tasks
73 * when others are blocked waiting for a phase to advance.
74 *
75 * </ul>
76 *
77 * <p> <b>Termination.</b> A phaser may enter a <em>termination</em>
78 * state in which all synchronization methods immediately return
79 * without updating phaser state or waiting for advance, and
80 * indicating (via a negative phase value) that execution is complete.
81 * Termination is triggered when an invocation of {@code onAdvance}
82 * returns {@code true}. The default implementation returns {@code
83 * true} if a deregistration has caused the number of registered
84 * parties to become zero. As illustrated below, when phasers control
85 * actions with a fixed number of iterations, it is often convenient
86 * to override this method to cause termination when the current phase
87 * number reaches a threshold. Method {@link #forceTermination} is
88 * also available to abruptly release waiting threads and allow them
89 * to terminate.
90 *
91 * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
92 * constructed in tree structures) to reduce contention. Phasers with
93 * large numbers of parties that would otherwise experience heavy
94 * synchronization contention costs may instead be set up so that
95 * groups of sub-phasers share a common parent. This may greatly
96 * increase throughput even though it incurs greater per-operation
97 * overhead.
98 *
99 * <p>In a tree of tiered phasers, registration and deregistration of
100 * child phasers with their parent are managed automatically.
101 * Whenever the number of registered parties of a child phaser becomes
102 * non-zero (as established in the {@link #Phaser(Phaser,int)}
103 * constructor, {@link #register}, or {@link #bulkRegister}), this
104 * child phaser is registered with its parent. Whenever the number of
105 * registered parties becomes zero as the result of an invocation of
106 * {@link #arriveAndDeregister}, this child phaser is deregistered
107 * from its parent.
108 *
109 * <p><b>Monitoring.</b> While synchronization methods may be invoked
110 * only by registered parties, the current state of a phaser may be
111 * monitored by any caller. At any given moment there are {@link
112 * #getRegisteredParties} parties in total, of which {@link
113 * #getArrivedParties} have arrived at the current phase ({@link
114 * #getPhase}). When the remaining ({@link #getUnarrivedParties})
115 * parties arrive, the phase advances. The values returned by these
116 * methods may reflect transient states and so are not in general
117 * useful for synchronization control. Method {@link #toString}
118 * returns snapshots of these state queries in a form convenient for
119 * informal monitoring.
120 *
121 * <p><b>Sample usages:</b>
122 *
123 * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
124 * to control a one-shot action serving a variable number of parties.
125 * The typical idiom is for the method setting this up to first
126 * register, then start the actions, then deregister, as in:
127 *
128 * <pre> {@code
129 * void runTasks(List<Runnable> tasks) {
130 * final Phaser phaser = new Phaser(1); // "1" to register self
131 * // create and start threads
132 * for (Runnable task : tasks) {
133 * phaser.register();
134 * new Thread() {
135 * public void run() {
136 * phaser.arriveAndAwaitAdvance(); // await all creation
137 * task.run();
138 * }
139 * }.start();
140 * }
141 *
142 * // allow threads to start and deregister self
143 * phaser.arriveAndDeregister();
144 * }}</pre>
145 *
146 * <p>One way to cause a set of threads to repeatedly perform actions
147 * for a given number of iterations is to override {@code onAdvance}:
148 *
149 * <pre> {@code
150 * void startTasks(List<Runnable> tasks, final int iterations) {
151 * final Phaser phaser = new Phaser() {
152 * protected boolean onAdvance(int phase, int registeredParties) {
153 * return phase >= iterations || registeredParties == 0;
154 * }
155 * };
156 * phaser.register();
157 * for (final Runnable task : tasks) {
158 * phaser.register();
159 * new Thread() {
160 * public void run() {
161 * do {
162 * task.run();
163 * phaser.arriveAndAwaitAdvance();
164 * } while (!phaser.isTerminated());
165 * }
166 * }.start();
167 * }
168 * phaser.arriveAndDeregister(); // deregister self, don't wait
169 * }}</pre>
170 *
171 * If the main task must later await termination, it
172 * may re-register and then execute a similar loop:
173 * <pre> {@code
174 * // ...
175 * phaser.register();
176 * while (!phaser.isTerminated())
177 * phaser.arriveAndAwaitAdvance();}</pre>
178 *
179 * <p>Related constructions may be used to await particular phase numbers
180 * in contexts where you are sure that the phase will never wrap around
181 * {@code Integer.MAX_VALUE}. For example:
182 *
183 * <pre> {@code
184 * void awaitPhase(Phaser phaser, int phase) {
185 * int p = phaser.register(); // assumes caller not already registered
186 * while (p < phase) {
187 * if (phaser.isTerminated())
188 * // ... deal with unexpected termination
189 * else
190 * p = phaser.arriveAndAwaitAdvance();
191 * }
192 * phaser.arriveAndDeregister();
193 * }}</pre>
194 *
195 *
196 * <p>To create a set of {@code n} tasks using a tree of phasers, you
197 * could use code of the following form, assuming a Task class with a
198 * constructor accepting a {@code Phaser} that it registers with upon
199 * construction. After invocation of {@code build(new Task[n], 0, n,
200 * new Phaser())}, these tasks could then be started, for example by
201 * submitting to a pool:
202 *
203 * <pre> {@code
204 * void build(Task[] tasks, int lo, int hi, Phaser ph) {
205 * if (hi - lo > TASKS_PER_PHASER) {
206 * for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
207 * int j = Math.min(i + TASKS_PER_PHASER, hi);
208 * build(tasks, i, j, new Phaser(ph));
209 * }
210 * } else {
211 * for (int i = lo; i < hi; ++i)
212 * tasks[i] = new Task(ph);
213 * // assumes new Task(ph) performs ph.register()
214 * }
215 * }}</pre>
216 *
217 * The best value of {@code TASKS_PER_PHASER} depends mainly on
218 * expected synchronization rates. A value as low as four may
219 * be appropriate for extremely small per-phase task bodies (thus
220 * high rates), or up to hundreds for extremely large ones.
221 *
222 * <p><b>Implementation notes</b>: This implementation restricts the
223 * maximum number of parties to 65535. Attempts to register additional
224 * parties result in {@code IllegalStateException}. However, you can and
225 * should create tiered phasers to accommodate arbitrarily large sets
226 * of participants.
227 *
228 * @since 1.7
229 * @author Doug Lea
230 */
231 public class Phaser {
232 /*
233 * This class implements an extension of X10 "clocks". Thanks to
234 * Vijay Saraswat for the idea, and to Vivek Sarkar for
235 * enhancements to extend functionality.
236 */
237
238 /**
239 * Primary state representation, holding four fields:
240 *
241 * * unarrived -- the number of parties yet to hit barrier (bits 0-15)
242 * * parties -- the number of parties to wait (bits 16-31)
243 * * phase -- the generation of the barrier (bits 32-62)
244 * * terminated -- set if barrier is terminated (bit 63 / sign)
245 *
246 * Except that a phaser with no registered parties is
247 * distinguished with the otherwise illegal state of having zero
248 * parties and one unarrived parties (encoded as EMPTY below).
249 *
250 * To efficiently maintain atomicity, these values are packed into
251 * a single (atomic) long. Good performance relies on keeping
252 * state decoding and encoding simple, and keeping race windows
253 * short.
254 *
255 * All state updates are performed via CAS except initial
256 * registration of a sub-phaser (i.e., one with a non-null
257 * parent). In this (relatively rare) case, we use built-in
258 * synchronization to lock while first registering with its
259 * parent.
260 *
261 * The phase of a subphaser is allowed to lag that of its
262 * ancestors until it is actually accessed. Method reconcileState
263 * is usually attempted only only when the number of unarrived
264 * parties appears to be zero, which indicates a potential lag in
265 * updating phase after the root advanced.
266 */
267 private volatile long state;
268
269 private static final int MAX_PARTIES = 0xffff;
270 private static final int MAX_PHASE = 0x7fffffff;
271 private static final int PARTIES_SHIFT = 16;
272 private static final int PHASE_SHIFT = 32;
273 private static final int UNARRIVED_MASK = 0xffff; // to mask ints
274 private static final long PARTIES_MASK = 0xffff0000L; // to mask longs
275 private static final long TERMINATION_BIT = 1L << 63;
276
277 // some special values
278 private static final int ONE_ARRIVAL = 1;
279 private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
280 private static final int EMPTY = 1;
281
282 // The following unpacking methods are usually manually inlined
283
284 private static int unarrivedOf(long s) {
285 int counts = (int)s;
286 return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK;
287 }
288
289 private static int partiesOf(long s) {
290 return (int)s >>> PARTIES_SHIFT;
291 }
292
293 private static int phaseOf(long s) {
294 return (int) (s >>> PHASE_SHIFT);
295 }
296
297 private static int arrivedOf(long s) {
298 int counts = (int)s;
299 return (counts == EMPTY) ? 0 :
300 (counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
301 }
302
303 /**
304 * The parent of this phaser, or null if none
305 */
306 private final Phaser parent;
307
308 /**
309 * The root of phaser tree. Equals this if not in a tree.
310 */
311 private final Phaser root;
312
313 /**
314 * Heads of Treiber stacks for waiting threads. To eliminate
315 * contention when releasing some threads while adding others, we
316 * use two of them, alternating across even and odd phases.
317 * Subphasers share queues with root to speed up releases.
318 */
319 private final AtomicReference<QNode> evenQ;
320 private final AtomicReference<QNode> oddQ;
321
322 private AtomicReference<QNode> queueFor(int phase) {
323 return ((phase & 1) == 0) ? evenQ : oddQ;
324 }
325
326 /**
327 * Returns message string for bounds exceptions on arrival.
328 */
329 private String badArrive(long s) {
330 return "Attempted arrival of unregistered party for " +
331 stateToString(s);
332 }
333
334 /**
335 * Returns message string for bounds exceptions on registration.
336 */
337 private String badRegister(long s) {
338 return "Attempt to register more than " +
339 MAX_PARTIES + " parties for " + stateToString(s);
340 }
341
342 /**
343 * Main implementation for methods arrive and arriveAndDeregister.
344 * Manually tuned to speed up and minimize race windows for the
345 * common case of just decrementing unarrived field.
346 *
347 * @param deregister false for arrive, true for arriveAndDeregister
348 */
349 private int doArrive(boolean deregister) {
350 int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
351 long s;
352 int phase;
353 while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0) {
354 int counts = (int)s;
355 int unarrived = counts & UNARRIVED_MASK;
356 if (counts == EMPTY || unarrived == 0) {
357 if (reconcileState() == s)
358 throw new IllegalStateException(badArrive(s));
359 }
360 else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
361 if (unarrived == 1) {
362 long n = s & PARTIES_MASK; // unshifted parties field
363 int u = ((int)n) >>> PARTIES_SHIFT;
364 Phaser par = parent;
365 if (par != null) {
366 par.doArrive(u == 0);
367 reconcileState();
368 }
369 else {
370 n |= (((long)((phase+1) & MAX_PHASE)) << PHASE_SHIFT);
371 if (onAdvance(phase, u))
372 n |= TERMINATION_BIT;
373 else if (u == 0)
374 n |= EMPTY; // reset to unregistered
375 else
376 n |= (long)u; // reset unarr to parties
377 // assert state == s || isTerminated();
378 UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
379 releaseWaiters(phase);
380 }
381 }
382 break;
383 }
384 }
385 return phase;
386 }
387
388 /**
389 * Implementation of register, bulkRegister
390 *
391 * @param registrations number to add to both parties and
392 * unarrived fields. Must be greater than zero.
393 */
394 private int doRegister(int registrations) {
395 // adjustment to state
396 long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
397 Phaser par = parent;
398 int phase;
399 for (;;) {
400 long s = state;
401 int counts = (int)s;
402 int parties = counts >>> PARTIES_SHIFT;
403 int unarrived = counts & UNARRIVED_MASK;
404 if (registrations > MAX_PARTIES - parties)
405 throw new IllegalStateException(badRegister(s));
406 else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
407 break;
408 else if (counts != EMPTY) { // not 1st registration
409 if (par == null || reconcileState() == s) {
410 if (unarrived == 0) // wait out advance
411 root.internalAwaitAdvance(phase, null);
412 else if (UNSAFE.compareAndSwapLong(this, stateOffset,
413 s, s + adj))
414 break;
415 }
416 }
417 else if (par == null) { // 1st root registration
418 long next = (((long) phase) << PHASE_SHIFT) | adj;
419 if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
420 break;
421 }
422 else {
423 synchronized (this) { // 1st sub registration
424 if (state == s) { // recheck under lock
425 par.doRegister(1);
426 do { // force current phase
427 phase = (int)(root.state >>> PHASE_SHIFT);
428 // assert phase < 0 || (int)state == EMPTY;
429 } while (!UNSAFE.compareAndSwapLong
430 (this, stateOffset, state,
431 (((long) phase) << PHASE_SHIFT) | adj));
432 break;
433 }
434 }
435 }
436 }
437 return phase;
438 }
439
440 /**
441 * Resolves lagged phase propagation from root if necessary.
442 */
443 private long reconcileState() {
444 Phaser rt = root;
445 long s = state;
446 if (rt != this) {
447 int phase;
448 while ((phase = (int)(rt.state >>> PHASE_SHIFT)) !=
449 (int)(s >>> PHASE_SHIFT)) {
450 // assert phase < 0 || unarrivedOf(s) == 0
451 long t; // to reread s
452 long p = s & PARTIES_MASK; // unshifted parties field
453 long n = (((long) phase) << PHASE_SHIFT) | p;
454 if (phase >= 0) {
455 if (p == 0L)
456 n |= EMPTY; // reset to empty
457 else
458 n |= p >>> PARTIES_SHIFT; // set unarr to parties
459 }
460 if ((t = state) == s &&
461 UNSAFE.compareAndSwapLong(this, stateOffset, s, s = n))
462 break;
463 s = t;
464 }
465 }
466 return s;
467 }
468
469 /**
470 * Creates a new phaser with no initially registered parties, no
471 * parent, and initial phase number 0. Any thread using this
472 * phaser will need to first register for it.
473 */
474 public Phaser() {
475 this(null, 0);
476 }
477
478 /**
479 * Creates a new phaser with the given number of registered
480 * unarrived parties, no parent, and initial phase number 0.
481 *
482 * @param parties the number of parties required to advance to the
483 * next phase
484 * @throws IllegalArgumentException if parties less than zero
485 * or greater than the maximum number of parties supported
486 */
487 public Phaser(int parties) {
488 this(null, parties);
489 }
490
491 /**
492 * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
493 *
494 * @param parent the parent phaser
495 */
496 public Phaser(Phaser parent) {
497 this(parent, 0);
498 }
499
500 /**
501 * Creates a new phaser with the given parent and number of
502 * registered unarrived parties. If the given parent is non-null
503 * and the given number of parties is greater than zero, this
504 * child phaser is registered with its parent.
505 *
506 * @param parent the parent phaser
507 * @param parties the number of parties required to advance to the
508 * next phase
509 * @throws IllegalArgumentException if parties less than zero
510 * or greater than the maximum number of parties supported
511 */
512 public Phaser(Phaser parent, int parties) {
513 if (parties >>> PARTIES_SHIFT != 0)
514 throw new IllegalArgumentException("Illegal number of parties");
515 int phase = 0;
516 this.parent = parent;
517 if (parent != null) {
518 final Phaser root = parent.root;
519 this.root = root;
520 this.evenQ = root.evenQ;
521 this.oddQ = root.oddQ;
522 if (parties != 0)
523 phase = parent.doRegister(1);
524 }
525 else {
526 this.root = this;
527 this.evenQ = new AtomicReference<QNode>();
528 this.oddQ = new AtomicReference<QNode>();
529 }
530 this.state = (parties == 0) ? (long) EMPTY :
531 ((((long) phase) << PHASE_SHIFT) |
532 (((long) parties) << PARTIES_SHIFT) |
533 ((long) parties));
534 }
535
536 /**
537 * Adds a new unarrived party to this phaser. If an ongoing
538 * invocation of {@link #onAdvance} is in progress, this method
539 * may await its completion before returning. If this phaser has
540 * a parent, and this phaser previously had no registered parties,
541 * this child phaser is also registered with its parent.
542 *
543 * @return the arrival phase number to which this registration applied
544 * @throws IllegalStateException if attempting to register more
545 * than the maximum supported number of parties
546 */
547 public int register() {
548 return doRegister(1);
549 }
550
551 /**
552 * Adds the given number of new unarrived parties to this phaser.
553 * If an ongoing invocation of {@link #onAdvance} is in progress,
554 * this method may await its completion before returning. If this
555 * phaser has a parent, and the given number of parties is
556 * greater than zero, and this phaser previously had no registered
557 * parties, this child phaser is also registered with its parent.
558 *
559 * @param parties the number of additional parties required to
560 * advance to the next phase
561 * @return the arrival phase number to which this registration applied
562 * @throws IllegalStateException if attempting to register more
563 * than the maximum supported number of parties
564 * @throws IllegalArgumentException if {@code parties < 0}
565 */
566 public int bulkRegister(int parties) {
567 if (parties < 0)
568 throw new IllegalArgumentException();
569 if (parties == 0)
570 return getPhase();
571 return doRegister(parties);
572 }
573
574 /**
575 * Arrives at this phaser, without waiting for others to arrive.
576 *
577 * <p>It is a usage error for an unregistered party to invoke this
578 * method. However, this error may result in an {@code
579 * IllegalStateException} only upon some subsequent operation on
580 * this phaser, if ever.
581 *
582 * @return the arrival phase number, or a negative value if terminated
583 * @throws IllegalStateException if not terminated and the number
584 * of unarrived parties would become negative
585 */
586 public int arrive() {
587 return doArrive(false);
588 }
589
590 /**
591 * Arrives at this phaser and deregisters from it without waiting
592 * for others to arrive. Deregistration reduces the number of
593 * parties required to advance in future phases. If this phaser
594 * has a parent, and deregistration causes this phaser to have
595 * zero parties, this phaser is also deregistered from its parent.
596 *
597 * <p>It is a usage error for an unregistered party to invoke this
598 * method. However, this error may result in an {@code
599 * IllegalStateException} only upon some subsequent operation on
600 * this phaser, if ever.
601 *
602 * @return the arrival phase number, or a negative value if terminated
603 * @throws IllegalStateException if not terminated and the number
604 * of registered or unarrived parties would become negative
605 */
606 public int arriveAndDeregister() {
607 return doArrive(true);
608 }
609
610 /**
611 * Arrives at this phaser and awaits others. Equivalent in effect
612 * to {@code awaitAdvance(arrive())}. If you need to await with
613 * interruption or timeout, you can arrange this with an analogous
614 * construction using one of the other forms of the {@code
615 * awaitAdvance} method. If instead you need to deregister upon
616 * arrival, use {@code awaitAdvance(arriveAndDeregister())}.
617 *
618 * <p>It is a usage error for an unregistered party to invoke this
619 * method. However, this error may result in an {@code
620 * IllegalStateException} only upon some subsequent operation on
621 * this phaser, if ever.
622 *
623 * @return the arrival phase number, or a negative number if terminated
624 * @throws IllegalStateException if not terminated and the number
625 * of unarrived parties would become negative
626 */
627 public int arriveAndAwaitAdvance() {
628 return awaitAdvance(doArrive(false));
629 }
630
631 /**
632 * Awaits the phase of this phaser to advance from the given phase
633 * value, returning immediately if the current phase is not equal
634 * to the given phase value or this phaser is terminated.
635 *
636 * @param phase an arrival phase number, or negative value if
637 * terminated; this argument is normally the value returned by a
638 * previous call to {@code arrive} or {@code arriveAndDeregister}.
639 * @return the next arrival phase number, or a negative value
640 * if terminated or argument is negative
641 */
642 public int awaitAdvance(int phase) {
643 Phaser rt;
644 int p = (int)(state >>> PHASE_SHIFT);
645 if (phase < 0)
646 return phase;
647 if (p == phase) {
648 if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase)
649 return rt.internalAwaitAdvance(phase, null);
650 reconcileState();
651 }
652 return p;
653 }
654
655 /**
656 * Awaits the phase of this phaser to advance from the given phase
657 * value, throwing {@code InterruptedException} if interrupted
658 * while waiting, or returning immediately if the current phase is
659 * not equal to the given phase value or this phaser is
660 * terminated.
661 *
662 * @param phase an arrival phase number, or negative value if
663 * terminated; this argument is normally the value returned by a
664 * previous call to {@code arrive} or {@code arriveAndDeregister}.
665 * @return the next arrival phase number, or a negative value
666 * if terminated or argument is negative
667 * @throws InterruptedException if thread interrupted while waiting
668 */
669 public int awaitAdvanceInterruptibly(int phase)
670 throws InterruptedException {
671 Phaser rt;
672 int p = (int)(state >>> PHASE_SHIFT);
673 if (phase < 0)
674 return phase;
675 if (p == phase) {
676 if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
677 QNode node = new QNode(this, phase, true, false, 0L);
678 p = rt.internalAwaitAdvance(phase, node);
679 if (node.wasInterrupted)
680 throw new InterruptedException();
681 }
682 else
683 reconcileState();
684 }
685 return p;
686 }
687
688 /**
689 * Awaits the phase of this phaser to advance from the given phase
690 * value or the given timeout to elapse, throwing {@code
691 * InterruptedException} if interrupted while waiting, or
692 * returning immediately if the current phase is not equal to the
693 * given phase value or this phaser is terminated.
694 *
695 * @param phase an arrival phase number, or negative value if
696 * terminated; this argument is normally the value returned by a
697 * previous call to {@code arrive} or {@code arriveAndDeregister}.
698 * @param timeout how long to wait before giving up, in units of
699 * {@code unit}
700 * @param unit a {@code TimeUnit} determining how to interpret the
701 * {@code timeout} parameter
702 * @return the next arrival phase number, or a negative value
703 * if terminated or argument is negative
704 * @throws InterruptedException if thread interrupted while waiting
705 * @throws TimeoutException if timed out while waiting
706 */
707 public int awaitAdvanceInterruptibly(int phase,
708 long timeout, TimeUnit unit)
709 throws InterruptedException, TimeoutException {
710 long nanos = unit.toNanos(timeout);
711 Phaser rt;
712 int p = (int)(state >>> PHASE_SHIFT);
713 if (phase < 0)
714 return phase;
715 if (p == phase) {
716 if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
717 QNode node = new QNode(this, phase, true, true, nanos);
718 p = rt.internalAwaitAdvance(phase, node);
719 if (node.wasInterrupted)
720 throw new InterruptedException();
721 else if (p == phase)
722 throw new TimeoutException();
723 }
724 else
725 reconcileState();
726 }
727 return p;
728 }
729
730 /**
731 * Forces this phaser to enter termination state. Counts of
732 * registered parties are unaffected. If this phaser is a member
733 * of a tiered set of phasers, then all of the phasers in the set
734 * are terminated. If this phaser is already terminated, this
735 * method has no effect. This method may be useful for
736 * coordinating recovery after one or more tasks encounter
737 * unexpected exceptions.
738 */
739 public void forceTermination() {
740 // Only need to change root state
741 final Phaser root = this.root;
742 long s;
743 while ((s = root.state) >= 0) {
744 long next = (s & ~((long)UNARRIVED_MASK)) | TERMINATION_BIT;
745 if (UNSAFE.compareAndSwapLong(root, stateOffset, s, next)) {
746 // signal all threads
747 releaseWaiters(0);
748 releaseWaiters(1);
749 return;
750 }
751 }
752 }
753
754 /**
755 * Returns the current phase number. The maximum phase number is
756 * {@code Integer.MAX_VALUE}, after which it restarts at
757 * zero. Upon termination, the phase number is negative,
758 * in which case the prevailing phase prior to termination
759 * may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
760 *
761 * @return the phase number, or a negative value if terminated
762 */
763 public final int getPhase() {
764 return (int)(root.state >>> PHASE_SHIFT);
765 }
766
767 /**
768 * Returns the number of parties registered at this phaser.
769 *
770 * @return the number of parties
771 */
772 public int getRegisteredParties() {
773 return partiesOf(state);
774 }
775
776 /**
777 * Returns the number of registered parties that have arrived at
778 * the current phase of this phaser.
779 *
780 * @return the number of arrived parties
781 */
782 public int getArrivedParties() {
783 return arrivedOf(reconcileState());
784 }
785
786 /**
787 * Returns the number of registered parties that have not yet
788 * arrived at the current phase of this phaser.
789 *
790 * @return the number of unarrived parties
791 */
792 public int getUnarrivedParties() {
793 return unarrivedOf(reconcileState());
794 }
795
796 /**
797 * Returns the parent of this phaser, or {@code null} if none.
798 *
799 * @return the parent of this phaser, or {@code null} if none
800 */
801 public Phaser getParent() {
802 return parent;
803 }
804
805 /**
806 * Returns the root ancestor of this phaser, which is the same as
807 * this phaser if it has no parent.
808 *
809 * @return the root ancestor of this phaser
810 */
811 public Phaser getRoot() {
812 return root;
813 }
814
815 /**
816 * Returns {@code true} if this phaser has been terminated.
817 *
818 * @return {@code true} if this phaser has been terminated
819 */
820 public boolean isTerminated() {
821 return root.state < 0L;
822 }
823
824 /**
825 * Overridable method to perform an action upon impending phase
826 * advance, and to control termination. This method is invoked
827 * upon arrival of the party advancing this phaser (when all other
828 * waiting parties are dormant). If this method returns {@code
829 * true}, this phaser will be set to a final termination state
830 * upon advance, and subsequent calls to {@link #isTerminated}
831 * will return true. Any (unchecked) Exception or Error thrown by
832 * an invocation of this method is propagated to the party
833 * attempting to advance this phaser, in which case no advance
834 * occurs.
835 *
836 * <p>The arguments to this method provide the state of the phaser
837 * prevailing for the current transition. The effects of invoking
838 * arrival, registration, and waiting methods on this phaser from
839 * within {@code onAdvance} are unspecified and should not be
840 * relied on.
841 *
842 * <p>If this phaser is a member of a tiered set of phasers, then
843 * {@code onAdvance} is invoked only for its root phaser on each
844 * advance.
845 *
846 * <p>To support the most common use cases, the default
847 * implementation of this method returns {@code true} when the
848 * number of registered parties has become zero as the result of a
849 * party invoking {@code arriveAndDeregister}. You can disable
850 * this behavior, thus enabling continuation upon future
851 * registrations, by overriding this method to always return
852 * {@code false}:
853 *
854 * <pre> {@code
855 * Phaser phaser = new Phaser() {
856 * protected boolean onAdvance(int phase, int parties) { return false; }
857 * }}</pre>
858 *
859 * @param phase the current phase number on entry to this method,
860 * before this phaser is advanced
861 * @param registeredParties the current number of registered parties
862 * @return {@code true} if this phaser should terminate
863 */
864 protected boolean onAdvance(int phase, int registeredParties) {
865 return registeredParties == 0;
866 }
867
868 /**
869 * Returns a string identifying this phaser, as well as its
870 * state. The state, in brackets, includes the String {@code
871 * "phase = "} followed by the phase number, {@code "parties = "}
872 * followed by the number of registered parties, and {@code
873 * "arrived = "} followed by the number of arrived parties.
874 *
875 * @return a string identifying this phaser, as well as its state
876 */
877 public String toString() {
878 return stateToString(reconcileState());
879 }
880
881 /**
882 * Implementation of toString and string-based error messages
883 */
884 private String stateToString(long s) {
885 return super.toString() +
886 "[phase = " + phaseOf(s) +
887 " parties = " + partiesOf(s) +
888 " arrived = " + arrivedOf(s) + "]";
889 }
890
891 // Waiting mechanics
892
893 /**
894 * Removes and signals threads from queue for phase.
895 */
896 private void releaseWaiters(int phase) {
897 QNode q; // first element of queue
898 int p; // its phase
899 Thread t; // its thread
900 // assert phase != phaseOf(root.state);
901 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
902 while ((q = head.get()) != null &&
903 q.phase != (int)(root.state >>> PHASE_SHIFT)) {
904 if (head.compareAndSet(q, q.next) &&
905 (t = q.thread) != null) {
906 q.thread = null;
907 LockSupport.unpark(t);
908 }
909 }
910 }
911
912 /** The number of CPUs, for spin control */
913 private static final int NCPU = Runtime.getRuntime().availableProcessors();
914
915 /**
916 * The number of times to spin before blocking while waiting for
917 * advance, per arrival while waiting. On multiprocessors, fully
918 * blocking and waking up a large number of threads all at once is
919 * usually a very slow process, so we use rechargeable spins to
920 * avoid it when threads regularly arrive: When a thread in
921 * internalAwaitAdvance notices another arrival before blocking,
922 * and there appear to be enough CPUs available, it spins
923 * SPINS_PER_ARRIVAL more times before blocking. The value trades
924 * off good-citizenship vs big unnecessary slowdowns.
925 */
926 static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
927
928 /**
929 * Possibly blocks and waits for phase to advance unless aborted.
930 * Call only from root node.
931 *
932 * @param phase current phase
933 * @param node if non-null, the wait node to track interrupt and timeout;
934 * if null, denotes noninterruptible wait
935 * @return current phase
936 */
937 private int internalAwaitAdvance(int phase, QNode node) {
938 releaseWaiters(phase-1); // ensure old queue clean
939 boolean queued = false; // true when node is enqueued
940 int lastUnarrived = 0; // to increase spins upon change
941 int spins = SPINS_PER_ARRIVAL;
942 long s;
943 int p;
944 while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
945 if (node == null) { // spinning in noninterruptible mode
946 int unarrived = (int)s & UNARRIVED_MASK;
947 if (unarrived != lastUnarrived &&
948 (lastUnarrived = unarrived) < NCPU)
949 spins += SPINS_PER_ARRIVAL;
950 boolean interrupted = Thread.interrupted();
951 if (interrupted || --spins < 0) { // need node to record intr
952 node = new QNode(this, phase, false, false, 0L);
953 node.wasInterrupted = interrupted;
954 }
955 }
956 else if (node.isReleasable()) // done or aborted
957 break;
958 else if (!queued) { // push onto queue
959 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
960 QNode q = node.next = head.get();
961 if ((q == null || q.phase == phase) &&
962 (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
963 queued = head.compareAndSet(q, node);
964 }
965 else {
966 try {
967 ForkJoinPool.managedBlock(node);
968 } catch (InterruptedException ie) {
969 node.wasInterrupted = true;
970 }
971 }
972 }
973
974 if (node != null) {
975 if (node.thread != null)
976 node.thread = null; // avoid need for unpark()
977 if (node.wasInterrupted && !node.interruptible)
978 Thread.currentThread().interrupt();
979 if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
980 return p; // recheck abort
981 }
982 releaseWaiters(phase);
983 return p;
984 }
985
986 /**
987 * Wait nodes for Treiber stack representing wait queue
988 */
989 static final class QNode implements ForkJoinPool.ManagedBlocker {
990 final Phaser phaser;
991 final int phase;
992 final boolean interruptible;
993 final boolean timed;
994 boolean wasInterrupted;
995 long nanos;
996 long lastTime;
997 volatile Thread thread; // nulled to cancel wait
998 QNode next;
999
1000 QNode(Phaser phaser, int phase, boolean interruptible,
1001 boolean timed, long nanos) {
1002 this.phaser = phaser;
1003 this.phase = phase;
1004 this.interruptible = interruptible;
1005 this.nanos = nanos;
1006 this.timed = timed;
1007 this.lastTime = timed ? System.nanoTime() : 0L;
1008 thread = Thread.currentThread();
1009 }
1010
1011 public boolean isReleasable() {
1012 if (thread == null)
1013 return true;
1014 if (phaser.getPhase() != phase) {
1015 thread = null;
1016 return true;
1017 }
1018 if (Thread.interrupted())
1019 wasInterrupted = true;
1020 if (wasInterrupted && interruptible) {
1021 thread = null;
1022 return true;
1023 }
1024 if (timed) {
1025 if (nanos > 0L) {
1026 long now = System.nanoTime();
1027 nanos -= now - lastTime;
1028 lastTime = now;
1029 }
1030 if (nanos <= 0L) {
1031 thread = null;
1032 return true;
1033 }
1034 }
1035 return false;
1036 }
1037
1038 public boolean block() {
1039 if (isReleasable())
1040 return true;
1041 else if (!timed)
1042 LockSupport.park(this);
1043 else if (nanos > 0)
1044 LockSupport.parkNanos(this, nanos);
1045 return isReleasable();
1046 }
1047 }
1048
1049 // Unsafe mechanics
1050
1051 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1052 private static final long stateOffset =
1053 objectFieldOffset("state", Phaser.class);
1054
1055 private static long objectFieldOffset(String field, Class<?> klazz) {
1056 try {
1057 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1058 } catch (NoSuchFieldException e) {
1059 // Convert Exception to corresponding Error
1060 NoSuchFieldError error = new NoSuchFieldError(field);
1061 error.initCause(e);
1062 throw error;
1063 }
1064 }
1065 }