ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.50
Committed: Sat Nov 6 16:12:10 2010 UTC (13 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.49: +95 -77 lines
Log Message:
Performance (and other) improvements

File Contents

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