ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/Phaser.java
Revision: 1.2
Committed: Wed Apr 27 18:26:57 2016 UTC (8 years ago) by jsr166
Branch: MAIN
Changes since 1.1: +0 -4 lines
Log Message:
delete no-longer-used method queueFor(int phase)

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/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     *
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 bit-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 by 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 -- see method
263     * reconcileState.
264     */
265     private volatile long state;
266    
267     private static final int MAX_PARTIES = 0xffff;
268     private static final int MAX_PHASE = Integer.MAX_VALUE;
269     private static final int PARTIES_SHIFT = 16;
270     private static final int PHASE_SHIFT = 32;
271     private static final int UNARRIVED_MASK = 0xffff; // to mask ints
272     private static final long PARTIES_MASK = 0xffff0000L; // to mask longs
273     private static final long COUNTS_MASK = 0xffffffffL;
274     private static final long TERMINATION_BIT = 1L << 63;
275    
276     // some special values
277     private static final int ONE_ARRIVAL = 1;
278     private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
279     private static final int ONE_DEREGISTER = ONE_ARRIVAL|ONE_PARTY;
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     /**
323     * Returns message string for bounds exceptions on arrival.
324     */
325     private String badArrive(long s) {
326     return "Attempted arrival of unregistered party for " +
327     stateToString(s);
328     }
329    
330     /**
331     * Returns message string for bounds exceptions on registration.
332     */
333     private String badRegister(long s) {
334     return "Attempt to register more than " +
335     MAX_PARTIES + " parties for " + stateToString(s);
336     }
337    
338     /**
339     * Main implementation for methods arrive and arriveAndDeregister.
340     * Manually tuned to speed up and minimize race windows for the
341     * common case of just decrementing unarrived field.
342     *
343     * @param adjust value to subtract from state;
344     * ONE_ARRIVAL for arrive,
345     * ONE_DEREGISTER for arriveAndDeregister
346     */
347     private int doArrive(int adjust) {
348     final Phaser root = this.root;
349     for (;;) {
350     long s = (root == this) ? state : reconcileState();
351     int phase = (int)(s >>> PHASE_SHIFT);
352     if (phase < 0)
353     return phase;
354     int counts = (int)s;
355     int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
356     if (unarrived <= 0)
357     throw new IllegalStateException(badArrive(s));
358     if (U.compareAndSwapLong(this, STATE, s, s-=adjust)) {
359     if (unarrived == 1) {
360     long n = s & PARTIES_MASK; // base of next state
361     int nextUnarrived = (int)n >>> PARTIES_SHIFT;
362     if (root == this) {
363     if (onAdvance(phase, nextUnarrived))
364     n |= TERMINATION_BIT;
365     else if (nextUnarrived == 0)
366     n |= EMPTY;
367     else
368     n |= nextUnarrived;
369     int nextPhase = (phase + 1) & MAX_PHASE;
370     n |= (long)nextPhase << PHASE_SHIFT;
371     U.compareAndSwapLong(this, STATE, s, n);
372     releaseWaiters(phase);
373     }
374     else if (nextUnarrived == 0) { // propagate deregistration
375     phase = parent.doArrive(ONE_DEREGISTER);
376     U.compareAndSwapLong(this, STATE, s, s | EMPTY);
377     }
378     else
379     phase = parent.doArrive(ONE_ARRIVAL);
380     }
381     return phase;
382     }
383     }
384     }
385    
386     /**
387     * Implementation of register, bulkRegister.
388     *
389     * @param registrations number to add to both parties and
390     * unarrived fields. Must be greater than zero.
391     */
392     private int doRegister(int registrations) {
393     // adjustment to state
394     long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
395     final Phaser parent = this.parent;
396     int phase;
397     for (;;) {
398     long s = (parent == null) ? state : reconcileState();
399     int counts = (int)s;
400     int parties = counts >>> PARTIES_SHIFT;
401     int unarrived = counts & UNARRIVED_MASK;
402     if (registrations > MAX_PARTIES - parties)
403     throw new IllegalStateException(badRegister(s));
404     phase = (int)(s >>> PHASE_SHIFT);
405     if (phase < 0)
406     break;
407     if (counts != EMPTY) { // not 1st registration
408     if (parent == null || reconcileState() == s) {
409     if (unarrived == 0) // wait out advance
410     root.internalAwaitAdvance(phase, null);
411     else if (U.compareAndSwapLong(this, STATE, s, s + adjust))
412     break;
413     }
414     }
415     else if (parent == null) { // 1st root registration
416     long next = ((long)phase << PHASE_SHIFT) | adjust;
417     if (U.compareAndSwapLong(this, STATE, s, next))
418     break;
419     }
420     else {
421     synchronized (this) { // 1st sub registration
422     if (state == s) { // recheck under lock
423     phase = parent.doRegister(1);
424     if (phase < 0)
425     break;
426     // finish registration whenever parent registration
427     // succeeded, even when racing with termination,
428     // since these are part of the same "transaction".
429     while (!U.compareAndSwapLong
430     (this, STATE, s,
431     ((long)phase << PHASE_SHIFT) | adjust)) {
432     s = state;
433     phase = (int)(root.state >>> PHASE_SHIFT);
434     // assert (int)s == EMPTY;
435     }
436     break;
437     }
438     }
439     }
440     }
441     return phase;
442     }
443    
444     /**
445     * Resolves lagged phase propagation from root if necessary.
446     * Reconciliation normally occurs when root has advanced but
447     * subphasers have not yet done so, in which case they must finish
448     * their own advance by setting unarrived to parties (or if
449     * parties is zero, resetting to unregistered EMPTY state).
450     *
451     * @return reconciled state
452     */
453     private long reconcileState() {
454     final Phaser root = this.root;
455     long s = state;
456     if (root != this) {
457     int phase, p;
458     // CAS to root phase with current parties, tripping unarrived
459     while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
460     (int)(s >>> PHASE_SHIFT) &&
461     !U.compareAndSwapLong
462     (this, STATE, s,
463     s = (((long)phase << PHASE_SHIFT) |
464     ((phase < 0) ? (s & COUNTS_MASK) :
465     (((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
466     ((s & PARTIES_MASK) | p))))))
467     s = state;
468     }
469     return s;
470     }
471    
472     /**
473     * Creates a new phaser with no initially registered parties, no
474     * parent, and initial phase number 0. Any thread using this
475     * phaser will need to first register for it.
476     */
477     public Phaser() {
478     this(null, 0);
479     }
480    
481     /**
482     * Creates a new phaser with the given number of registered
483     * unarrived parties, no parent, and initial phase number 0.
484     *
485     * @param parties the number of parties required to advance to the
486     * next phase
487     * @throws IllegalArgumentException if parties less than zero
488     * or greater than the maximum number of parties supported
489     */
490     public Phaser(int parties) {
491     this(null, parties);
492     }
493    
494     /**
495     * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
496     *
497     * @param parent the parent phaser
498     */
499     public Phaser(Phaser parent) {
500     this(parent, 0);
501     }
502    
503     /**
504     * Creates a new phaser with the given parent and number of
505     * registered unarrived parties. When the given parent is non-null
506     * and the given number of parties is greater than zero, this
507     * child phaser is registered with its parent.
508     *
509     * @param parent the parent phaser
510     * @param parties the number of parties required to advance to the
511     * next phase
512     * @throws IllegalArgumentException if parties less than zero
513     * or greater than the maximum number of parties supported
514     */
515     public Phaser(Phaser parent, int parties) {
516     if (parties >>> PARTIES_SHIFT != 0)
517     throw new IllegalArgumentException("Illegal number of parties");
518     int phase = 0;
519     this.parent = parent;
520     if (parent != null) {
521     final Phaser root = parent.root;
522     this.root = root;
523     this.evenQ = root.evenQ;
524     this.oddQ = root.oddQ;
525     if (parties != 0)
526     phase = parent.doRegister(1);
527     }
528     else {
529     this.root = this;
530     this.evenQ = new AtomicReference<QNode>();
531     this.oddQ = new AtomicReference<QNode>();
532     }
533     this.state = (parties == 0) ? (long)EMPTY :
534     ((long)phase << PHASE_SHIFT) |
535     ((long)parties << PARTIES_SHIFT) |
536     ((long)parties);
537     }
538    
539     /**
540     * Adds a new unarrived party to this phaser. If an ongoing
541     * invocation of {@link #onAdvance} is in progress, this method
542     * may await its completion before returning. If this phaser has
543     * a parent, and this phaser previously had no registered parties,
544     * this child phaser is also registered with its parent. If
545     * this phaser is terminated, the attempt to register has
546     * no effect, and a negative value is returned.
547     *
548     * @return the arrival phase number to which this registration
549     * applied. If this value is negative, then this phaser has
550     * terminated, in which case registration has no effect.
551     * @throws IllegalStateException if attempting to register more
552     * than the maximum supported number of parties
553     */
554     public int register() {
555     return doRegister(1);
556     }
557    
558     /**
559     * Adds the given number of new unarrived parties to this phaser.
560     * If an ongoing invocation of {@link #onAdvance} is in progress,
561     * this method may await its completion before returning. If this
562     * phaser has a parent, and the given number of parties is greater
563     * than zero, and this phaser previously had no registered
564     * parties, this child phaser is also registered with its parent.
565     * If this phaser is terminated, the attempt to register has no
566     * effect, and a negative value is returned.
567     *
568     * @param parties the number of additional parties required to
569     * advance to the next phase
570     * @return the arrival phase number to which this registration
571     * applied. If this value is negative, then this phaser has
572     * terminated, in which case registration has no effect.
573     * @throws IllegalStateException if attempting to register more
574     * than the maximum supported number of parties
575     * @throws IllegalArgumentException if {@code parties < 0}
576     */
577     public int bulkRegister(int parties) {
578     if (parties < 0)
579     throw new IllegalArgumentException();
580     if (parties == 0)
581     return getPhase();
582     return doRegister(parties);
583     }
584    
585     /**
586     * Arrives at this phaser, without waiting for others to arrive.
587     *
588     * <p>It is a usage error for an unregistered party to invoke this
589     * method. However, this error may result in an {@code
590     * IllegalStateException} only upon some subsequent operation on
591     * this phaser, if ever.
592     *
593     * @return the arrival phase number, or a negative value if terminated
594     * @throws IllegalStateException if not terminated and the number
595     * of unarrived parties would become negative
596     */
597     public int arrive() {
598     return doArrive(ONE_ARRIVAL);
599     }
600    
601     /**
602     * Arrives at this phaser and deregisters from it without waiting
603     * for others to arrive. Deregistration reduces the number of
604     * parties required to advance in future phases. If this phaser
605     * has a parent, and deregistration causes this phaser to have
606     * zero parties, this phaser is also deregistered from its parent.
607     *
608     * <p>It is a usage error for an unregistered party to invoke this
609     * method. However, this error may result in an {@code
610     * IllegalStateException} only upon some subsequent operation on
611     * this phaser, if ever.
612     *
613     * @return the arrival phase number, or a negative value if terminated
614     * @throws IllegalStateException if not terminated and the number
615     * of registered or unarrived parties would become negative
616     */
617     public int arriveAndDeregister() {
618     return doArrive(ONE_DEREGISTER);
619     }
620    
621     /**
622     * Arrives at this phaser and awaits others. Equivalent in effect
623     * to {@code awaitAdvance(arrive())}. If you need to await with
624     * interruption or timeout, you can arrange this with an analogous
625     * construction using one of the other forms of the {@code
626     * awaitAdvance} method. If instead you need to deregister upon
627     * arrival, use {@code awaitAdvance(arriveAndDeregister())}.
628     *
629     * <p>It is a usage error for an unregistered party to invoke this
630     * method. However, this error may result in an {@code
631     * IllegalStateException} only upon some subsequent operation on
632     * this phaser, if ever.
633     *
634     * @return the arrival phase number, or the (negative)
635     * {@linkplain #getPhase() current phase} if terminated
636     * @throws IllegalStateException if not terminated and the number
637     * of unarrived parties would become negative
638     */
639     public int arriveAndAwaitAdvance() {
640     // Specialization of doArrive+awaitAdvance eliminating some reads/paths
641     final Phaser root = this.root;
642     for (;;) {
643     long s = (root == this) ? state : reconcileState();
644     int phase = (int)(s >>> PHASE_SHIFT);
645     if (phase < 0)
646     return phase;
647     int counts = (int)s;
648     int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
649     if (unarrived <= 0)
650     throw new IllegalStateException(badArrive(s));
651     if (U.compareAndSwapLong(this, STATE, s, s -= ONE_ARRIVAL)) {
652     if (unarrived > 1)
653     return root.internalAwaitAdvance(phase, null);
654     if (root != this)
655     return parent.arriveAndAwaitAdvance();
656     long n = s & PARTIES_MASK; // base of next state
657     int nextUnarrived = (int)n >>> PARTIES_SHIFT;
658     if (onAdvance(phase, nextUnarrived))
659     n |= TERMINATION_BIT;
660     else if (nextUnarrived == 0)
661     n |= EMPTY;
662     else
663     n |= nextUnarrived;
664     int nextPhase = (phase + 1) & MAX_PHASE;
665     n |= (long)nextPhase << PHASE_SHIFT;
666     if (!U.compareAndSwapLong(this, STATE, s, n))
667     return (int)(state >>> PHASE_SHIFT); // terminated
668     releaseWaiters(phase);
669     return nextPhase;
670     }
671     }
672     }
673    
674     /**
675     * Awaits the phase of this phaser to advance from the given phase
676     * value, returning immediately if the current phase is not equal
677     * to the given phase value or this phaser is terminated.
678     *
679     * @param phase an arrival phase number, or negative value if
680     * terminated; this argument is normally the value returned by a
681     * previous call to {@code arrive} or {@code arriveAndDeregister}.
682     * @return the next arrival phase number, or the argument if it is
683     * negative, or the (negative) {@linkplain #getPhase() current phase}
684     * if terminated
685     */
686     public int awaitAdvance(int phase) {
687     final Phaser root = this.root;
688     long s = (root == this) ? state : reconcileState();
689     int p = (int)(s >>> PHASE_SHIFT);
690     if (phase < 0)
691     return phase;
692     if (p == phase)
693     return root.internalAwaitAdvance(phase, null);
694     return p;
695     }
696    
697     /**
698     * Awaits the phase of this phaser to advance from the given phase
699     * value, throwing {@code InterruptedException} if interrupted
700     * while waiting, or returning immediately if the current phase is
701     * not equal to the given phase value or this phaser is
702     * terminated.
703     *
704     * @param phase an arrival phase number, or negative value if
705     * terminated; this argument is normally the value returned by a
706     * previous call to {@code arrive} or {@code arriveAndDeregister}.
707     * @return the next arrival phase number, or the argument if it is
708     * negative, or the (negative) {@linkplain #getPhase() current phase}
709     * if terminated
710     * @throws InterruptedException if thread interrupted while waiting
711     */
712     public int awaitAdvanceInterruptibly(int phase)
713     throws InterruptedException {
714     final Phaser root = this.root;
715     long s = (root == this) ? state : reconcileState();
716     int p = (int)(s >>> PHASE_SHIFT);
717     if (phase < 0)
718     return phase;
719     if (p == phase) {
720     QNode node = new QNode(this, phase, true, false, 0L);
721     p = root.internalAwaitAdvance(phase, node);
722     if (node.wasInterrupted)
723     throw new InterruptedException();
724     }
725     return p;
726     }
727    
728     /**
729     * Awaits the phase of this phaser to advance from the given phase
730     * value or the given timeout to elapse, throwing {@code
731     * InterruptedException} if interrupted while waiting, or
732     * returning immediately if the current phase is not equal to the
733     * given phase value or this phaser is terminated.
734     *
735     * @param phase an arrival phase number, or negative value if
736     * terminated; this argument is normally the value returned by a
737     * previous call to {@code arrive} or {@code arriveAndDeregister}.
738     * @param timeout how long to wait before giving up, in units of
739     * {@code unit}
740     * @param unit a {@code TimeUnit} determining how to interpret the
741     * {@code timeout} parameter
742     * @return the next arrival phase number, or the argument if it is
743     * negative, or the (negative) {@linkplain #getPhase() current phase}
744     * if terminated
745     * @throws InterruptedException if thread interrupted while waiting
746     * @throws TimeoutException if timed out while waiting
747     */
748     public int awaitAdvanceInterruptibly(int phase,
749     long timeout, TimeUnit unit)
750     throws InterruptedException, TimeoutException {
751     long nanos = unit.toNanos(timeout);
752     final Phaser root = this.root;
753     long s = (root == this) ? state : reconcileState();
754     int p = (int)(s >>> PHASE_SHIFT);
755     if (phase < 0)
756     return phase;
757     if (p == phase) {
758     QNode node = new QNode(this, phase, true, true, nanos);
759     p = root.internalAwaitAdvance(phase, node);
760     if (node.wasInterrupted)
761     throw new InterruptedException();
762     else if (p == phase)
763     throw new TimeoutException();
764     }
765     return p;
766     }
767    
768     /**
769     * Forces this phaser to enter termination state. Counts of
770     * registered parties are unaffected. If this phaser is a member
771     * of a tiered set of phasers, then all of the phasers in the set
772     * are terminated. If this phaser is already terminated, this
773     * method has no effect. This method may be useful for
774     * coordinating recovery after one or more tasks encounter
775     * unexpected exceptions.
776     */
777     public void forceTermination() {
778     // Only need to change root state
779     final Phaser root = this.root;
780     long s;
781     while ((s = root.state) >= 0) {
782     if (U.compareAndSwapLong(root, STATE, s, s | TERMINATION_BIT)) {
783     // signal all threads
784     releaseWaiters(0); // Waiters on evenQ
785     releaseWaiters(1); // Waiters on oddQ
786     return;
787     }
788     }
789     }
790    
791     /**
792     * Returns the current phase number. The maximum phase number is
793     * {@code Integer.MAX_VALUE}, after which it restarts at
794     * zero. Upon termination, the phase number is negative,
795     * in which case the prevailing phase prior to termination
796     * may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
797     *
798     * @return the phase number, or a negative value if terminated
799     */
800     public final int getPhase() {
801     return (int)(root.state >>> PHASE_SHIFT);
802     }
803    
804     /**
805     * Returns the number of parties registered at this phaser.
806     *
807     * @return the number of parties
808     */
809     public int getRegisteredParties() {
810     return partiesOf(state);
811     }
812    
813     /**
814     * Returns the number of registered parties that have arrived at
815     * the current phase of this phaser. If this phaser has terminated,
816     * the returned value is meaningless and arbitrary.
817     *
818     * @return the number of arrived parties
819     */
820     public int getArrivedParties() {
821     return arrivedOf(reconcileState());
822     }
823    
824     /**
825     * Returns the number of registered parties that have not yet
826     * arrived at the current phase of this phaser. If this phaser has
827     * terminated, the returned value is meaningless and arbitrary.
828     *
829     * @return the number of unarrived parties
830     */
831     public int getUnarrivedParties() {
832     return unarrivedOf(reconcileState());
833     }
834    
835     /**
836     * Returns the parent of this phaser, or {@code null} if none.
837     *
838     * @return the parent of this phaser, or {@code null} if none
839     */
840     public Phaser getParent() {
841     return parent;
842     }
843    
844     /**
845     * Returns the root ancestor of this phaser, which is the same as
846     * this phaser if it has no parent.
847     *
848     * @return the root ancestor of this phaser
849     */
850     public Phaser getRoot() {
851     return root;
852     }
853    
854     /**
855     * Returns {@code true} if this phaser has been terminated.
856     *
857     * @return {@code true} if this phaser has been terminated
858     */
859     public boolean isTerminated() {
860     return root.state < 0L;
861     }
862    
863     /**
864     * Overridable method to perform an action upon impending phase
865     * advance, and to control termination. This method is invoked
866     * upon arrival of the party advancing this phaser (when all other
867     * waiting parties are dormant). If this method returns {@code
868     * true}, this phaser will be set to a final termination state
869     * upon advance, and subsequent calls to {@link #isTerminated}
870     * will return true. Any (unchecked) Exception or Error thrown by
871     * an invocation of this method is propagated to the party
872     * attempting to advance this phaser, in which case no advance
873     * occurs.
874     *
875     * <p>The arguments to this method provide the state of the phaser
876     * prevailing for the current transition. The effects of invoking
877     * arrival, registration, and waiting methods on this phaser from
878     * within {@code onAdvance} are unspecified and should not be
879     * relied on.
880     *
881     * <p>If this phaser is a member of a tiered set of phasers, then
882     * {@code onAdvance} is invoked only for its root phaser on each
883     * advance.
884     *
885     * <p>To support the most common use cases, the default
886     * implementation of this method returns {@code true} when the
887     * number of registered parties has become zero as the result of a
888     * party invoking {@code arriveAndDeregister}. You can disable
889     * this behavior, thus enabling continuation upon future
890     * registrations, by overriding this method to always return
891     * {@code false}:
892     *
893     * <pre> {@code
894     * Phaser phaser = new Phaser() {
895     * protected boolean onAdvance(int phase, int parties) { return false; }
896     * }}</pre>
897     *
898     * @param phase the current phase number on entry to this method,
899     * before this phaser is advanced
900     * @param registeredParties the current number of registered parties
901     * @return {@code true} if this phaser should terminate
902     */
903     protected boolean onAdvance(int phase, int registeredParties) {
904     return registeredParties == 0;
905     }
906    
907     /**
908     * Returns a string identifying this phaser, as well as its
909     * state. The state, in brackets, includes the String {@code
910     * "phase = "} followed by the phase number, {@code "parties = "}
911     * followed by the number of registered parties, and {@code
912     * "arrived = "} followed by the number of arrived parties.
913     *
914     * @return a string identifying this phaser, as well as its state
915     */
916     public String toString() {
917     return stateToString(reconcileState());
918     }
919    
920     /**
921     * Implementation of toString and string-based error messages.
922     */
923     private String stateToString(long s) {
924     return super.toString() +
925     "[phase = " + phaseOf(s) +
926     " parties = " + partiesOf(s) +
927     " arrived = " + arrivedOf(s) + "]";
928     }
929    
930     // Waiting mechanics
931    
932     /**
933     * Removes and signals threads from queue for phase.
934     */
935     private void releaseWaiters(int phase) {
936     QNode q; // first element of queue
937     Thread t; // its thread
938     AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
939     while ((q = head.get()) != null &&
940     q.phase != (int)(root.state >>> PHASE_SHIFT)) {
941     if (head.compareAndSet(q, q.next) &&
942     (t = q.thread) != null) {
943     q.thread = null;
944     LockSupport.unpark(t);
945     }
946     }
947     }
948    
949     /**
950     * Variant of releaseWaiters that additionally tries to remove any
951     * nodes no longer waiting for advance due to timeout or
952     * interrupt. Currently, nodes are removed only if they are at
953     * head of queue, which suffices to reduce memory footprint in
954     * most usages.
955     *
956     * @return current phase on exit
957     */
958     private int abortWait(int phase) {
959     AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
960     for (;;) {
961     Thread t;
962     QNode q = head.get();
963     int p = (int)(root.state >>> PHASE_SHIFT);
964     if (q == null || ((t = q.thread) != null && q.phase == p))
965     return p;
966     if (head.compareAndSet(q, q.next) && t != null) {
967     q.thread = null;
968     LockSupport.unpark(t);
969     }
970     }
971     }
972    
973     /** The number of CPUs, for spin control */
974     private static final int NCPU = Runtime.getRuntime().availableProcessors();
975    
976     /**
977     * The number of times to spin before blocking while waiting for
978     * advance, per arrival while waiting. On multiprocessors, fully
979     * blocking and waking up a large number of threads all at once is
980     * usually a very slow process, so we use rechargeable spins to
981     * avoid it when threads regularly arrive: When a thread in
982     * internalAwaitAdvance notices another arrival before blocking,
983     * and there appear to be enough CPUs available, it spins
984     * SPINS_PER_ARRIVAL more times before blocking. The value trades
985     * off good-citizenship vs big unnecessary slowdowns.
986     */
987     static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
988    
989     /**
990     * Possibly blocks and waits for phase to advance unless aborted.
991     * Call only on root phaser.
992     *
993     * @param phase current phase
994     * @param node if non-null, the wait node to track interrupt and timeout;
995     * if null, denotes noninterruptible wait
996     * @return current phase
997     */
998     private int internalAwaitAdvance(int phase, QNode node) {
999     // assert root == this;
1000     releaseWaiters(phase-1); // ensure old queue clean
1001     boolean queued = false; // true when node is enqueued
1002     int lastUnarrived = 0; // to increase spins upon change
1003     int spins = SPINS_PER_ARRIVAL;
1004     long s;
1005     int p;
1006     while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
1007     if (node == null) { // spinning in noninterruptible mode
1008     int unarrived = (int)s & UNARRIVED_MASK;
1009     if (unarrived != lastUnarrived &&
1010     (lastUnarrived = unarrived) < NCPU)
1011     spins += SPINS_PER_ARRIVAL;
1012     boolean interrupted = Thread.interrupted();
1013     if (interrupted || --spins < 0) { // need node to record intr
1014     node = new QNode(this, phase, false, false, 0L);
1015     node.wasInterrupted = interrupted;
1016     }
1017     }
1018     else if (node.isReleasable()) // done or aborted
1019     break;
1020     else if (!queued) { // push onto queue
1021     AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
1022     QNode q = node.next = head.get();
1023     if ((q == null || q.phase == phase) &&
1024     (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
1025     queued = head.compareAndSet(q, node);
1026     }
1027     else {
1028     try {
1029     ForkJoinPool.managedBlock(node);
1030     } catch (InterruptedException cantHappen) {
1031     node.wasInterrupted = true;
1032     }
1033     }
1034     }
1035    
1036     if (node != null) {
1037     if (node.thread != null)
1038     node.thread = null; // avoid need for unpark()
1039     if (node.wasInterrupted && !node.interruptible)
1040     Thread.currentThread().interrupt();
1041     if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
1042     return abortWait(phase); // possibly clean up on abort
1043     }
1044     releaseWaiters(phase);
1045     return p;
1046     }
1047    
1048     /**
1049     * Wait nodes for Treiber stack representing wait queue.
1050     */
1051     static final class QNode implements ForkJoinPool.ManagedBlocker {
1052     final Phaser phaser;
1053     final int phase;
1054     final boolean interruptible;
1055     final boolean timed;
1056     boolean wasInterrupted;
1057     long nanos;
1058     final long deadline;
1059     volatile Thread thread; // nulled to cancel wait
1060     QNode next;
1061    
1062     QNode(Phaser phaser, int phase, boolean interruptible,
1063     boolean timed, long nanos) {
1064     this.phaser = phaser;
1065     this.phase = phase;
1066     this.interruptible = interruptible;
1067     this.nanos = nanos;
1068     this.timed = timed;
1069     this.deadline = timed ? System.nanoTime() + nanos : 0L;
1070     thread = Thread.currentThread();
1071     }
1072    
1073     public boolean isReleasable() {
1074     if (thread == null)
1075     return true;
1076     if (phaser.getPhase() != phase) {
1077     thread = null;
1078     return true;
1079     }
1080     if (Thread.interrupted())
1081     wasInterrupted = true;
1082     if (wasInterrupted && interruptible) {
1083     thread = null;
1084     return true;
1085     }
1086     if (timed &&
1087     (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
1088     thread = null;
1089     return true;
1090     }
1091     return false;
1092     }
1093    
1094     public boolean block() {
1095     while (!isReleasable()) {
1096     if (timed)
1097     LockSupport.parkNanos(this, nanos);
1098     else
1099     LockSupport.park(this);
1100     }
1101     return true;
1102     }
1103     }
1104    
1105     // Unsafe mechanics
1106    
1107     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1108     private static final long STATE;
1109     static {
1110     try {
1111     STATE = U.objectFieldOffset
1112     (Phaser.class.getDeclaredField("state"));
1113     } catch (ReflectiveOperationException e) {
1114     throw new Error(e);
1115     }
1116    
1117     // Reduce the risk of rare disastrous classloading in first call to
1118     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
1119     Class<?> ensureLoaded = LockSupport.class;
1120     }
1121     }