ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.16
Committed: Sun Nov 7 19:01:42 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.15: +10 -8 lines
Log Message:
better test for parties over/underflow

File Contents

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