ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.94
Committed: Sun Mar 11 18:00:06 2018 UTC (6 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.93: +1 -1 lines
Log Message:
prefer throwing ExceptionInInitializerError from <clinit> to throwing Error

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 jsr166 1.60 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.1 */
6    
7     package java.util.concurrent;
8    
9 dl 1.87 import java.lang.invoke.MethodHandles;
10     import java.lang.invoke.VarHandle;
11 jsr166 1.1 import java.util.concurrent.atomic.AtomicReference;
12     import java.util.concurrent.locks.LockSupport;
13    
14     /**
15 jsr166 1.10 * A reusable synchronization barrier, similar in functionality to
16 jsr166 1.93 * {@link CyclicBarrier} and {@link CountDownLatch} but supporting
17     * more flexible usage.
18 jsr166 1.1 *
19 jsr166 1.73 * <p><b>Registration.</b> Unlike the case for other barriers, the
20 dl 1.37 * number of parties <em>registered</em> to synchronize on a phaser
21 jsr166 1.10 * 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 jsr166 1.73 * <p><b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
33 jsr166 1.10 * Phaser} may be repeatedly awaited. Method {@link
34     * #arriveAndAwaitAdvance} has effect analogous to {@link
35     * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
36 dl 1.37 * 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 jsr166 1.10 * Integer.MAX_VALUE}. The use of phase numbers enables independent
40 dl 1.37 * control of actions upon arrival at a phaser and upon awaiting
41 jsr166 1.10 * others, via two kinds of methods that may be invoked by any
42     * registered party:
43     *
44 jsr166 1.1 * <ul>
45     *
46 jsr166 1.82 * <li><b>Arrival.</b> Methods {@link #arrive} and
47 dl 1.37 * {@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 jsr166 1.10 *
59 jsr166 1.82 * <li><b>Waiting.</b> Method {@link #awaitAdvance} requires an
60 jsr166 1.10 * argument indicating an arrival phase number, and returns when
61 dl 1.37 * the phaser advances to (or is already at) a different phase.
62 jsr166 1.10 * 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 dl 1.37 * state of the phaser. If necessary, you can perform any
68 jsr166 1.10 * associated recovery within handlers of those exceptions,
69     * often after invoking {@code forceTermination}. Phasers may
70 dl 1.81 * also be used by tasks executing in a {@link ForkJoinPool}.
71     * Progress is ensured if the pool's parallelismLevel can
72     * accommodate the maximum number of simultaneously blocked
73     * parties.
74 jsr166 1.1 *
75     * </ul>
76     *
77 jsr166 1.73 * <p><b>Termination.</b> A phaser may enter a <em>termination</em>
78 dl 1.50 * state, that may be checked using method {@link #isTerminated}. Upon
79     * termination, all synchronization methods immediately return without
80 jsr166 1.51 * 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 jsr166 1.1 *
92 jsr166 1.73 * <p><b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
93 dl 1.32 * constructed in tree structures) to reduce contention. Phasers with
94     * large numbers of parties that would otherwise experience heavy
95 jsr166 1.10 * 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 jsr166 1.44 * <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 dl 1.50 * constructor, {@link #register}, or {@link #bulkRegister}), the
105 jsr166 1.44 * child phaser is registered with its parent. Whenever the number of
106     * registered parties becomes zero as the result of an invocation of
107 dl 1.50 * {@link #arriveAndDeregister}, the child phaser is deregistered
108 jsr166 1.44 * from its parent.
109     *
110 jsr166 1.10 * <p><b>Monitoring.</b> While synchronization methods may be invoked
111 dl 1.37 * only by registered parties, the current state of a phaser may be
112 jsr166 1.10 * 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 jsr166 1.1 *
122     * <p><b>Sample usages:</b>
123     *
124 jsr166 1.4 * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
125 jsr166 1.12 * 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 jsr166 1.91 * register, then start all the actions, then deregister, as in:
128 jsr166 1.1 *
129 jsr166 1.79 * <pre> {@code
130 jsr166 1.8 * void runTasks(List<Runnable> tasks) {
131 jsr166 1.91 * Phaser startingGate = new Phaser(1); // "1" to register self
132 jsr166 1.7 * // create and start threads
133 jsr166 1.91 * for (Runnable task : tasks) {
134     * startingGate.register();
135     * new Thread(() -> {
136     * startingGate.arriveAndAwaitAdvance();
137     * task.run();
138     * }).start();
139 jsr166 1.1 * }
140     *
141 jsr166 1.91 * // deregister self to allow threads to proceed
142     * startingGate.arriveAndDeregister();
143 jsr166 1.1 * }}</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 jsr166 1.79 * <pre> {@code
149 jsr166 1.91 * void startTasks(List<Runnable> tasks, int iterations) {
150     * Phaser phaser = new Phaser() {
151 jsr166 1.10 * protected boolean onAdvance(int phase, int registeredParties) {
152 dl 1.92 * return phase >= iterations - 1 || registeredParties == 0;
153 jsr166 1.1 * }
154     * };
155     * phaser.register();
156 jsr166 1.91 * for (Runnable task : tasks) {
157 jsr166 1.1 * phaser.register();
158 jsr166 1.91 * new Thread(() -> {
159     * do {
160     * task.run();
161     * phaser.arriveAndAwaitAdvance();
162     * } while (!phaser.isTerminated());
163     * }).start();
164 jsr166 1.1 * }
165 jsr166 1.91 * // allow threads to proceed; don't wait for them
166     * phaser.arriveAndDeregister();
167 jsr166 1.1 * }}</pre>
168     *
169 jsr166 1.10 * If the main task must later await termination, it
170     * may re-register and then execute a similar loop:
171 jsr166 1.79 * <pre> {@code
172 jsr166 1.10 * // ...
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 jsr166 1.79 * <pre> {@code
182 jsr166 1.10 * 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 dl 1.39 * <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 jsr166 1.10 *
200 jsr166 1.79 * <pre> {@code
201 dl 1.39 * void build(Task[] tasks, int lo, int hi, Phaser ph) {
202 jsr166 1.10 * 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 dl 1.39 * build(tasks, i, j, new Phaser(ph));
206 jsr166 1.1 * }
207     * } else {
208     * for (int i = lo; i < hi; ++i)
209 dl 1.39 * tasks[i] = new Task(ph);
210 jsr166 1.10 * // assumes new Task(ph) performs ph.register()
211 jsr166 1.1 * }
212 dl 1.39 * }}</pre>
213 jsr166 1.1 *
214     * The best value of {@code TASKS_PER_PHASER} depends mainly on
215 dl 1.37 * expected synchronization rates. A value as low as four may
216     * be appropriate for extremely small per-phase task bodies (thus
217 jsr166 1.1 * 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 jsr166 1.8 * parties result in {@code IllegalStateException}. However, you can and
222 dl 1.37 * should create tiered phasers to accommodate arbitrarily large sets
223 jsr166 1.1 * 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 jsr166 1.55 * Primary state representation, holding four bit-fields:
237 jsr166 1.1 *
238 jsr166 1.55 * 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 jsr166 1.1 *
243 dl 1.39 * Except that a phaser with no registered parties is
244 jsr166 1.55 * distinguished by the otherwise illegal state of having zero
245 dl 1.39 * 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 dl 1.53 * ancestors until it is actually accessed -- see method
260     * reconcileState.
261 jsr166 1.1 */
262     private volatile long state;
263    
264 dl 1.33 private static final int MAX_PARTIES = 0xffff;
265 jsr166 1.56 private static final int MAX_PHASE = Integer.MAX_VALUE;
266 dl 1.33 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 jsr166 1.71 private static final long COUNTS_MASK = 0xffffffffL;
271 dl 1.33 private static final long TERMINATION_BIT = 1L << 63;
272 dl 1.17
273 dl 1.39 // some special values
274     private static final int ONE_ARRIVAL = 1;
275     private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
276 jsr166 1.66 private static final int ONE_DEREGISTER = ONE_ARRIVAL|ONE_PARTY;
277 dl 1.39 private static final int EMPTY = 1;
278    
279 dl 1.17 // The following unpacking methods are usually manually inlined
280 jsr166 1.1
281     private static int unarrivedOf(long s) {
282 dl 1.39 int counts = (int)s;
283 jsr166 1.64 return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
284 jsr166 1.1 }
285    
286     private static int partiesOf(long s) {
287 jsr166 1.41 return (int)s >>> PARTIES_SHIFT;
288 jsr166 1.1 }
289    
290     private static int phaseOf(long s) {
291 jsr166 1.54 return (int)(s >>> PHASE_SHIFT);
292 jsr166 1.1 }
293    
294     private static int arrivedOf(long s) {
295 dl 1.39 int counts = (int)s;
296 jsr166 1.40 return (counts == EMPTY) ? 0 :
297 dl 1.39 (counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
298 jsr166 1.1 }
299    
300     /**
301 jsr166 1.83 * The parent of this phaser, or null if none.
302 jsr166 1.1 */
303     private final Phaser parent;
304    
305     /**
306 dl 1.39 * The root of phaser tree. Equals this if not in a tree.
307 jsr166 1.1 */
308     private final Phaser root;
309    
310     /**
311     * Heads of Treiber stacks for waiting threads. To eliminate
312 dl 1.14 * contention when releasing some threads while adding others, we
313 jsr166 1.1 * use two of them, alternating across even and odd phases.
314 dl 1.14 * Subphasers share queues with root to speed up releases.
315 jsr166 1.1 */
316 dl 1.15 private final AtomicReference<QNode> evenQ;
317     private final AtomicReference<QNode> oddQ;
318 jsr166 1.1
319     /**
320 dl 1.33 * 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 dl 1.17 * 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 jsr166 1.66 * @param adjust value to subtract from state;
341     * ONE_ARRIVAL for arrive,
342     * ONE_DEREGISTER for arriveAndDeregister
343 dl 1.17 */
344 jsr166 1.66 private int doArrive(int adjust) {
345 dl 1.50 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 jsr166 1.64 int counts = (int)s;
352     int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
353     if (unarrived <= 0)
354     throw new IllegalStateException(badArrive(s));
355 dl 1.87 if (STATE.compareAndSet(this, s, s-=adjust)) {
356 jsr166 1.64 if (unarrived == 1) {
357 jsr166 1.65 long n = s & PARTIES_MASK; // base of next state
358     int nextUnarrived = (int)n >>> PARTIES_SHIFT;
359 dl 1.63 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 jsr166 1.64 int nextPhase = (phase + 1) & MAX_PHASE;
367     n |= (long)nextPhase << PHASE_SHIFT;
368 dl 1.87 STATE.compareAndSet(this, s, n);
369 jsr166 1.68 releaseWaiters(phase);
370 dl 1.63 }
371     else if (nextUnarrived == 0) { // propagate deregistration
372 jsr166 1.66 phase = parent.doArrive(ONE_DEREGISTER);
373 dl 1.87 STATE.compareAndSet(this, s, s | EMPTY);
374 dl 1.63 }
375 dl 1.50 else
376 jsr166 1.66 phase = parent.doArrive(ONE_ARRIVAL);
377 dl 1.17 }
378 dl 1.50 return phase;
379 dl 1.17 }
380     }
381     }
382    
383     /**
384 jsr166 1.83 * Implementation of register, bulkRegister.
385 dl 1.17 *
386 dl 1.32 * @param registrations number to add to both parties and
387     * unarrived fields. Must be greater than zero.
388 jsr166 1.1 */
389 dl 1.17 private int doRegister(int registrations) {
390 jsr166 1.26 // adjustment to state
391 jsr166 1.66 long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
392 jsr166 1.57 final Phaser parent = this.parent;
393 dl 1.39 int phase;
394 dl 1.21 for (;;) {
395 dl 1.63 long s = (parent == null) ? state : reconcileState();
396 dl 1.39 int counts = (int)s;
397     int parties = counts >>> PARTIES_SHIFT;
398     int unarrived = counts & UNARRIVED_MASK;
399     if (registrations > MAX_PARTIES - parties)
400 dl 1.21 throw new IllegalStateException(badRegister(s));
401 jsr166 1.69 phase = (int)(s >>> PHASE_SHIFT);
402     if (phase < 0)
403 dl 1.39 break;
404 jsr166 1.69 if (counts != EMPTY) { // not 1st registration
405 jsr166 1.57 if (parent == null || reconcileState() == s) {
406 dl 1.39 if (unarrived == 0) // wait out advance
407     root.internalAwaitAdvance(phase, null);
408 dl 1.87 else if (STATE.compareAndSet(this, s, s + adjust))
409 dl 1.39 break;
410     }
411     }
412 jsr166 1.57 else if (parent == null) { // 1st root registration
413 jsr166 1.66 long next = ((long)phase << PHASE_SHIFT) | adjust;
414 dl 1.87 if (STATE.compareAndSet(this, s, next))
415 dl 1.39 break;
416     }
417     else {
418 jsr166 1.40 synchronized (this) { // 1st sub registration
419 dl 1.39 if (state == s) { // recheck under lock
420 jsr166 1.70 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 jsr166 1.90 while (!STATE.weakCompareAndSet
427 dl 1.87 (this, s,
428 jsr166 1.70 ((long)phase << PHASE_SHIFT) | adjust)) {
429     s = state;
430 dl 1.39 phase = (int)(root.state >>> PHASE_SHIFT);
431 jsr166 1.70 // assert (int)s == EMPTY;
432     }
433 dl 1.39 break;
434 dl 1.33 }
435     }
436     }
437 dl 1.17 }
438 dl 1.39 return phase;
439 dl 1.17 }
440    
441     /**
442 dl 1.39 * Resolves lagged phase propagation from root if necessary.
443 dl 1.53 * 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 jsr166 1.1 */
450     private long reconcileState() {
451 jsr166 1.52 final Phaser root = this.root;
452 dl 1.31 long s = state;
453 jsr166 1.52 if (root != this) {
454 jsr166 1.71 int phase, p;
455     // CAS to root phase with current parties, tripping unarrived
456 dl 1.53 while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
457     (int)(s >>> PHASE_SHIFT) &&
458 jsr166 1.90 !STATE.weakCompareAndSet
459 dl 1.87 (this, s,
460 jsr166 1.54 s = (((long)phase << PHASE_SHIFT) |
461 jsr166 1.71 ((phase < 0) ? (s & COUNTS_MASK) :
462     (((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
463     ((s & PARTIES_MASK) | p))))))
464 dl 1.53 s = state;
465 jsr166 1.1 }
466 dl 1.31 return s;
467 jsr166 1.1 }
468    
469     /**
470 dl 1.37 * 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 jsr166 1.1 */
474     public Phaser() {
475 dl 1.15 this(null, 0);
476 jsr166 1.1 }
477    
478     /**
479 dl 1.37 * Creates a new phaser with the given number of registered
480     * unarrived parties, no parent, and initial phase number 0.
481 jsr166 1.1 *
482 dl 1.37 * @param parties the number of parties required to advance to the
483     * next phase
484 jsr166 1.1 * @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 dl 1.32 * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
493 jsr166 1.1 *
494 dl 1.37 * @param parent the parent phaser
495 jsr166 1.1 */
496     public Phaser(Phaser parent) {
497 dl 1.15 this(parent, 0);
498 jsr166 1.1 }
499    
500     /**
501 dl 1.37 * Creates a new phaser with the given parent and number of
502 dl 1.50 * registered unarrived parties. When the given parent is non-null
503 jsr166 1.44 * and the given number of parties is greater than zero, this
504     * child phaser is registered with its parent.
505 jsr166 1.1 *
506 dl 1.37 * @param parent the parent phaser
507     * @param parties the number of parties required to advance to the
508     * next phase
509 jsr166 1.1 * @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 dl 1.24 if (parties >>> PARTIES_SHIFT != 0)
514 jsr166 1.1 throw new IllegalArgumentException("Illegal number of parties");
515 dl 1.39 int phase = 0;
516 jsr166 1.1 this.parent = parent;
517     if (parent != null) {
518 jsr166 1.42 final Phaser root = parent.root;
519     this.root = root;
520     this.evenQ = root.evenQ;
521     this.oddQ = root.oddQ;
522 dl 1.34 if (parties != 0)
523 dl 1.39 phase = parent.doRegister(1);
524 jsr166 1.1 }
525 dl 1.15 else {
526 jsr166 1.1 this.root = this;
527 dl 1.15 this.evenQ = new AtomicReference<QNode>();
528     this.oddQ = new AtomicReference<QNode>();
529     }
530 jsr166 1.54 this.state = (parties == 0) ? (long)EMPTY :
531     ((long)phase << PHASE_SHIFT) |
532     ((long)parties << PARTIES_SHIFT) |
533     ((long)parties);
534 jsr166 1.1 }
535    
536     /**
537 dl 1.37 * Adds a new unarrived party to this phaser. If an ongoing
538 dl 1.33 * invocation of {@link #onAdvance} is in progress, this method
539 dl 1.37 * may await its completion before returning. If this phaser has
540     * a parent, and this phaser previously had no registered parties,
541 dl 1.50 * 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 jsr166 1.51 * terminated, in which case registration has no effect.
548 jsr166 1.1 * @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 dl 1.37 * Adds the given number of new unarrived parties to this phaser.
557 dl 1.14 * If an ongoing invocation of {@link #onAdvance} is in progress,
558 dl 1.34 * this method may await its completion before returning. If this
559 dl 1.50 * phaser has a parent, and the given number of parties is greater
560     * than zero, and this phaser previously had no registered
561 jsr166 1.44 * parties, this child phaser is also registered with its parent.
562 dl 1.50 * If this phaser is terminated, the attempt to register has no
563     * effect, and a negative value is returned.
564 jsr166 1.1 *
565 dl 1.37 * @param parties the number of additional parties required to
566     * advance to the next phase
567 dl 1.50 * @return the arrival phase number to which this registration
568     * applied. If this value is negative, then this phaser has
569 jsr166 1.51 * terminated, in which case registration has no effect.
570 jsr166 1.1 * @throws IllegalStateException if attempting to register more
571     * than the maximum supported number of parties
572 dl 1.13 * @throws IllegalArgumentException if {@code parties < 0}
573 jsr166 1.1 */
574     public int bulkRegister(int parties) {
575     if (parties < 0)
576     throw new IllegalArgumentException();
577 dl 1.34 if (parties == 0)
578 jsr166 1.1 return getPhase();
579     return doRegister(parties);
580     }
581    
582     /**
583 dl 1.37 * Arrives at this phaser, without waiting for others to arrive.
584 dl 1.34 *
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 dl 1.37 * this phaser, if ever.
589 jsr166 1.1 *
590 jsr166 1.10 * @return the arrival phase number, or a negative value if terminated
591 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
592     * of unarrived parties would become negative
593     */
594     public int arrive() {
595 jsr166 1.66 return doArrive(ONE_ARRIVAL);
596 jsr166 1.1 }
597    
598     /**
599 dl 1.37 * Arrives at this phaser and deregisters from it without waiting
600 dl 1.34 * for others to arrive. Deregistration reduces the number of
601 dl 1.37 * 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 dl 1.34 *
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 dl 1.37 * this phaser, if ever.
609 jsr166 1.1 *
610 jsr166 1.10 * @return the arrival phase number, or a negative value if terminated
611 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
612     * of registered or unarrived parties would become negative
613     */
614     public int arriveAndDeregister() {
615 jsr166 1.66 return doArrive(ONE_DEREGISTER);
616 jsr166 1.1 }
617    
618     /**
619 dl 1.37 * Arrives at this phaser and awaits others. Equivalent in effect
620 jsr166 1.7 * to {@code awaitAdvance(arrive())}. If you need to await with
621     * interruption or timeout, you can arrange this with an analogous
622 jsr166 1.12 * construction using one of the other forms of the {@code
623     * awaitAdvance} method. If instead you need to deregister upon
624 dl 1.34 * 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 dl 1.37 * this phaser, if ever.
630 jsr166 1.1 *
631 jsr166 1.49 * @return the arrival phase number, or the (negative)
632     * {@linkplain #getPhase() current phase} if terminated
633 jsr166 1.1 * @throws IllegalStateException if not terminated and the number
634     * of unarrived parties would become negative
635     */
636     public int arriveAndAwaitAdvance() {
637 dl 1.50 // 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 jsr166 1.64 int counts = (int)s;
645     int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
646     if (unarrived <= 0)
647     throw new IllegalStateException(badArrive(s));
648 dl 1.87 if (STATE.compareAndSet(this, s, s -= ONE_ARRIVAL)) {
649 jsr166 1.64 if (unarrived > 1)
650 dl 1.50 return root.internalAwaitAdvance(phase, null);
651     if (root != this)
652     return parent.arriveAndAwaitAdvance();
653     long n = s & PARTIES_MASK; // base of next state
654 jsr166 1.54 int nextUnarrived = (int)n >>> PARTIES_SHIFT;
655 dl 1.50 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 dl 1.87 if (!STATE.compareAndSet(this, s, n))
664 dl 1.50 return (int)(state >>> PHASE_SHIFT); // terminated
665     releaseWaiters(phase);
666     return nextPhase;
667     }
668     }
669 jsr166 1.1 }
670    
671     /**
672 dl 1.37 * 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 jsr166 1.1 *
676 jsr166 1.10 * @param phase an arrival phase number, or negative value if
677     * terminated; this argument is normally the value returned by a
678 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
679 jsr166 1.48 * @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 jsr166 1.1 */
683     public int awaitAdvance(int phase) {
684 dl 1.50 final Phaser root = this.root;
685 jsr166 1.51 long s = (root == this) ? state : reconcileState();
686     int p = (int)(s >>> PHASE_SHIFT);
687 jsr166 1.1 if (phase < 0)
688     return phase;
689 dl 1.50 if (p == phase)
690     return root.internalAwaitAdvance(phase, null);
691 dl 1.34 return p;
692 jsr166 1.1 }
693    
694     /**
695 dl 1.37 * Awaits the phase of this phaser to advance from the given phase
696 jsr166 1.10 * value, throwing {@code InterruptedException} if interrupted
697 dl 1.37 * 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 jsr166 1.10 *
701     * @param phase an arrival phase number, or negative value if
702     * terminated; this argument is normally the value returned by a
703 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
704 jsr166 1.48 * @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 jsr166 1.1 * @throws InterruptedException if thread interrupted while waiting
708     */
709     public int awaitAdvanceInterruptibly(int phase)
710     throws InterruptedException {
711 dl 1.50 final Phaser root = this.root;
712 jsr166 1.51 long s = (root == this) ? state : reconcileState();
713     int p = (int)(s >>> PHASE_SHIFT);
714 jsr166 1.1 if (phase < 0)
715     return phase;
716 dl 1.39 if (p == phase) {
717 dl 1.50 QNode node = new QNode(this, phase, true, false, 0L);
718     p = root.internalAwaitAdvance(phase, node);
719     if (node.wasInterrupted)
720     throw new InterruptedException();
721 dl 1.24 }
722     return p;
723 jsr166 1.1 }
724    
725     /**
726 dl 1.37 * Awaits the phase of this phaser to advance from the given phase
727 jsr166 1.10 * value or the given timeout to elapse, throwing {@code
728     * InterruptedException} if interrupted while waiting, or
729 dl 1.37 * returning immediately if the current phase is not equal to the
730     * given phase value or this phaser is terminated.
731 jsr166 1.10 *
732     * @param phase an arrival phase number, or negative value if
733     * terminated; this argument is normally the value returned by a
734 dl 1.37 * previous call to {@code arrive} or {@code arriveAndDeregister}.
735 jsr166 1.8 * @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 jsr166 1.48 * @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 jsr166 1.1 * @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 dl 1.50 long nanos = unit.toNanos(timeout);
749     final Phaser root = this.root;
750 jsr166 1.51 long s = (root == this) ? state : reconcileState();
751     int p = (int)(s >>> PHASE_SHIFT);
752 jsr166 1.47 if (phase < 0)
753     return phase;
754 dl 1.39 if (p == phase) {
755 dl 1.50 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 dl 1.24 }
762     return p;
763 jsr166 1.1 }
764    
765     /**
766 dl 1.37 * Forces this phaser to enter termination state. Counts of
767 dl 1.39 * 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 jsr166 1.1 */
774     public void forceTermination() {
775 jsr166 1.23 // Only need to change root state
776     final Phaser root = this.root;
777 dl 1.14 long s;
778 jsr166 1.23 while ((s = root.state) >= 0) {
779 dl 1.87 if (STATE.compareAndSet(root, s, s | TERMINATION_BIT)) {
780 jsr166 1.45 // signal all threads
781 jsr166 1.67 releaseWaiters(0); // Waiters on evenQ
782     releaseWaiters(1); // Waiters on oddQ
783 jsr166 1.23 return;
784     }
785     }
786 jsr166 1.1 }
787    
788     /**
789     * Returns the current phase number. The maximum phase number is
790     * {@code Integer.MAX_VALUE}, after which it restarts at
791 dl 1.37 * 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 jsr166 1.1 *
795     * @return the phase number, or a negative value if terminated
796     */
797     public final int getPhase() {
798 dl 1.31 return (int)(root.state >>> PHASE_SHIFT);
799 jsr166 1.1 }
800    
801     /**
802 dl 1.37 * Returns the number of parties registered at this phaser.
803 jsr166 1.1 *
804     * @return the number of parties
805     */
806     public int getRegisteredParties() {
807 dl 1.31 return partiesOf(state);
808 jsr166 1.1 }
809    
810     /**
811 jsr166 1.10 * Returns the number of registered parties that have arrived at
812 dl 1.53 * the current phase of this phaser. If this phaser has terminated,
813     * the returned value is meaningless and arbitrary.
814 jsr166 1.1 *
815     * @return the number of arrived parties
816     */
817     public int getArrivedParties() {
818 dl 1.39 return arrivedOf(reconcileState());
819 jsr166 1.1 }
820    
821     /**
822     * Returns the number of registered parties that have not yet
823 dl 1.53 * arrived at the current phase of this phaser. If this phaser has
824     * terminated, the returned value is meaningless and arbitrary.
825 jsr166 1.1 *
826     * @return the number of unarrived parties
827     */
828     public int getUnarrivedParties() {
829 dl 1.39 return unarrivedOf(reconcileState());
830 jsr166 1.1 }
831    
832     /**
833 dl 1.37 * Returns the parent of this phaser, or {@code null} if none.
834 jsr166 1.1 *
835 dl 1.37 * @return the parent of this phaser, or {@code null} if none
836 jsr166 1.1 */
837     public Phaser getParent() {
838     return parent;
839     }
840    
841     /**
842 dl 1.37 * Returns the root ancestor of this phaser, which is the same as
843     * this phaser if it has no parent.
844 jsr166 1.1 *
845 dl 1.37 * @return the root ancestor of this phaser
846 jsr166 1.1 */
847     public Phaser getRoot() {
848     return root;
849     }
850    
851     /**
852 dl 1.37 * Returns {@code true} if this phaser has been terminated.
853 jsr166 1.1 *
854 dl 1.37 * @return {@code true} if this phaser has been terminated
855 jsr166 1.1 */
856     public boolean isTerminated() {
857 dl 1.31 return root.state < 0L;
858 jsr166 1.1 }
859    
860     /**
861 jsr166 1.10 * Overridable method to perform an action upon impending phase
862     * advance, and to control termination. This method is invoked
863 dl 1.37 * upon arrival of the party advancing this phaser (when all other
864 jsr166 1.10 * waiting parties are dormant). If this method returns {@code
865 dl 1.39 * 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 jsr166 1.10 *
872 dl 1.37 * <p>The arguments to this method provide the state of the phaser
873 dl 1.17 * prevailing for the current transition. The effects of invoking
874 dl 1.37 * arrival, registration, and waiting methods on this phaser from
875 dl 1.15 * within {@code onAdvance} are unspecified and should not be
876 dl 1.17 * relied on.
877     *
878 dl 1.37 * <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 dl 1.17 * advance.
881 jsr166 1.1 *
882 dl 1.33 * <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 jsr166 1.1 *
895 dl 1.37 * @param phase the current phase number on entry to this method,
896     * before this phaser is advanced
897 jsr166 1.1 * @param registeredParties the current number of registered parties
898 dl 1.37 * @return {@code true} if this phaser should terminate
899 jsr166 1.1 */
900     protected boolean onAdvance(int phase, int registeredParties) {
901 dl 1.36 return registeredParties == 0;
902 jsr166 1.1 }
903    
904     /**
905 dl 1.37 * Returns a string identifying this phaser, as well as its
906 dl 1.21 * 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 jsr166 1.1 *
911 dl 1.37 * @return a string identifying this phaser, as well as its state
912 jsr166 1.1 */
913     public String toString() {
914 dl 1.21 return stateToString(reconcileState());
915     }
916    
917     /**
918 jsr166 1.83 * Implementation of toString and string-based error messages.
919 dl 1.21 */
920     private String stateToString(long s) {
921 jsr166 1.1 return super.toString() +
922     "[phase = " + phaseOf(s) +
923     " parties = " + partiesOf(s) +
924     " arrived = " + arrivedOf(s) + "]";
925     }
926    
927 dl 1.21 // Waiting mechanics
928    
929 jsr166 1.1 /**
930 jsr166 1.30 * Removes and signals threads from queue for phase.
931 jsr166 1.1 */
932     private void releaseWaiters(int phase) {
933 dl 1.37 QNode q; // first element of queue
934     Thread t; // its thread
935 dl 1.36 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
936 dl 1.17 while ((q = head.get()) != null &&
937 dl 1.39 q.phase != (int)(root.state >>> PHASE_SHIFT)) {
938 dl 1.37 if (head.compareAndSet(q, q.next) &&
939     (t = q.thread) != null) {
940     q.thread = null;
941     LockSupport.unpark(t);
942     }
943 jsr166 1.1 }
944     }
945    
946 dl 1.50 /**
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 dl 1.17 /** The number of CPUs, for spin control */
971     private static final int NCPU = Runtime.getRuntime().availableProcessors();
972    
973 jsr166 1.1 /**
974 dl 1.17 * 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 dl 1.36 * SPINS_PER_ARRIVAL more times before blocking. The value trades
982     * off good-citizenship vs big unnecessary slowdowns.
983 dl 1.15 */
984 jsr166 1.22 static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
985 dl 1.15
986     /**
987 dl 1.17 * Possibly blocks and waits for phase to advance unless aborted.
988 jsr166 1.64 * Call only on root phaser.
989 jsr166 1.1 *
990 dl 1.17 * @param phase current phase
991 jsr166 1.22 * @param node if non-null, the wait node to track interrupt and timeout;
992 dl 1.17 * if null, denotes noninterruptible wait
993 jsr166 1.1 * @return current phase
994     */
995 dl 1.17 private int internalAwaitAdvance(int phase, QNode node) {
996 jsr166 1.64 // assert root == this;
997 dl 1.37 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 dl 1.17 int spins = SPINS_PER_ARRIVAL;
1001 dl 1.31 long s;
1002     int p;
1003 dl 1.34 while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
1004 dl 1.37 if (node == null) { // spinning in noninterruptible mode
1005     int unarrived = (int)s & UNARRIVED_MASK;
1006     if (unarrived != lastUnarrived &&
1007     (lastUnarrived = unarrived) < NCPU)
1008 dl 1.31 spins += SPINS_PER_ARRIVAL;
1009 dl 1.37 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 dl 1.87 else
1015     Thread.onSpinWait();
1016 dl 1.21 }
1017 dl 1.37 else if (node.isReleasable()) // done or aborted
1018     break;
1019     else if (!queued) { // push onto queue
1020 dl 1.36 AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
1021 dl 1.37 QNode q = node.next = head.get();
1022     if ((q == null || q.phase == phase) &&
1023     (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
1024 dl 1.36 queued = head.compareAndSet(q, node);
1025 dl 1.31 }
1026 dl 1.17 else {
1027     try {
1028     ForkJoinPool.managedBlock(node);
1029 jsr166 1.74 } catch (InterruptedException cantHappen) {
1030 dl 1.17 node.wasInterrupted = true;
1031     }
1032     }
1033     }
1034 dl 1.34
1035     if (node != null) {
1036     if (node.thread != null)
1037 dl 1.37 node.thread = null; // avoid need for unpark()
1038 dl 1.36 if (node.wasInterrupted && !node.interruptible)
1039 dl 1.34 Thread.currentThread().interrupt();
1040 dl 1.39 if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
1041 dl 1.50 return abortWait(phase); // possibly clean up on abort
1042 dl 1.34 }
1043 dl 1.37 releaseWaiters(phase);
1044 dl 1.31 return p;
1045 jsr166 1.1 }
1046    
1047     /**
1048 jsr166 1.83 * Wait nodes for Treiber stack representing wait queue.
1049 jsr166 1.1 */
1050 dl 1.17 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 jsr166 1.72 final long deadline;
1058 dl 1.17 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 jsr166 1.72 this.deadline = timed ? System.nanoTime() + nanos : 0L;
1069 dl 1.17 thread = Thread.currentThread();
1070     }
1071    
1072     public boolean isReleasable() {
1073 dl 1.37 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 jsr166 1.84 if (timed &&
1086     (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
1087     thread = null;
1088     return true;
1089 dl 1.15 }
1090 dl 1.37 return false;
1091 dl 1.17 }
1092    
1093     public boolean block() {
1094 jsr166 1.74 while (!isReleasable()) {
1095 jsr166 1.75 if (timed)
1096     LockSupport.parkNanos(this, nanos);
1097     else
1098 jsr166 1.74 LockSupport.park(this);
1099     }
1100     return true;
1101 dl 1.17 }
1102 jsr166 1.1 }
1103    
1104 dl 1.87 // VarHandle mechanics
1105     private static final VarHandle STATE;
1106 dl 1.59 static {
1107 jsr166 1.3 try {
1108 dl 1.87 MethodHandles.Lookup l = MethodHandles.lookup();
1109     STATE = l.findVarHandle(Phaser.class, "state", long.class);
1110 jsr166 1.77 } catch (ReflectiveOperationException e) {
1111 jsr166 1.94 throw new ExceptionInInitializerError(e);
1112 jsr166 1.3 }
1113 jsr166 1.80
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 jsr166 1.3 }
1118 jsr166 1.1 }