ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/Phaser.java
Revision: 1.3
Committed: Fri Jul 8 20:02:54 2016 UTC (7 years, 10 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.2: +0 -1 lines
Log Message:
whitespace

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