ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.95
Committed: Mon Aug 12 22:05:32 2019 UTC (4 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.94: +1 -1 lines
Log Message:
s/parallelismLevel/parallelism level/ as suggested by Pavel Rappo

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