ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.13
Committed: Sun Oct 24 21:45:16 2010 UTC (13 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.12: +8 -7 lines
Log Message:
Don't overwrite record of interrupt

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 ushortMask = 0xffff;
245 private static final int phaseMask = 0x7fffffff;
246
247 private static int unarrivedOf(long s) {
248 return (int) (s & ushortMask);
249 }
250
251 private static int partiesOf(long s) {
252 return ((int) s) >>> 16;
253 }
254
255 private static int phaseOf(long s) {
256 return (int) (s >>> 32);
257 }
258
259 private static int arrivedOf(long s) {
260 return partiesOf(s) - unarrivedOf(s);
261 }
262
263 private static long stateFor(int phase, int parties, int unarrived) {
264 return ((((long) phase) << 32) | (((long) parties) << 16) |
265 (long) unarrived);
266 }
267
268 private static long trippedStateFor(int phase, int parties) {
269 long lp = (long) parties;
270 return (((long) phase) << 32) | (lp << 16) | lp;
271 }
272
273 /**
274 * Returns message string for bad bounds exceptions.
275 */
276 private static String badBounds(int parties, int unarrived) {
277 return ("Attempt to set " + unarrived +
278 " unarrived of " + parties + " parties");
279 }
280
281 /**
282 * The parent of this phaser, or null if none
283 */
284 private final Phaser parent;
285
286 /**
287 * The root of phaser tree. Equals this if not in a tree. Used to
288 * support faster state push-down.
289 */
290 private final Phaser root;
291
292 // Wait queues
293
294 /**
295 * Heads of Treiber stacks for waiting threads. To eliminate
296 * contention while releasing some threads while adding others, we
297 * use two of them, alternating across even and odd phases.
298 */
299 private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
300 private final AtomicReference<QNode> oddQ = new AtomicReference<QNode>();
301
302 private AtomicReference<QNode> queueFor(int phase) {
303 return ((phase & 1) == 0) ? evenQ : oddQ;
304 }
305
306 /**
307 * Returns current state, first resolving lagged propagation from
308 * root if necessary.
309 */
310 private long getReconciledState() {
311 return (parent == null) ? state : reconcileState();
312 }
313
314 /**
315 * Recursively resolves state.
316 */
317 private long reconcileState() {
318 Phaser p = parent;
319 long s = state;
320 if (p != null) {
321 while (unarrivedOf(s) == 0 && phaseOf(s) != phaseOf(root.state)) {
322 long parentState = p.getReconciledState();
323 int parentPhase = phaseOf(parentState);
324 int phase = phaseOf(s = state);
325 if (phase != parentPhase) {
326 long next = trippedStateFor(parentPhase, partiesOf(s));
327 if (casState(s, next)) {
328 releaseWaiters(phase);
329 s = next;
330 }
331 }
332 }
333 }
334 return s;
335 }
336
337 /**
338 * Creates a new phaser without any initially registered parties,
339 * initial phase number 0, and no parent. Any thread using this
340 * phaser will need to first register for it.
341 */
342 public Phaser() {
343 this(null);
344 }
345
346 /**
347 * Creates a new phaser with the given number of registered
348 * unarrived parties, initial phase number 0, and no parent.
349 *
350 * @param parties the number of parties required to trip barrier
351 * @throws IllegalArgumentException if parties less than zero
352 * or greater than the maximum number of parties supported
353 */
354 public Phaser(int parties) {
355 this(null, parties);
356 }
357
358 /**
359 * Creates a new phaser with the given parent, without any
360 * initially registered parties. If parent is non-null this phaser
361 * is registered with the parent and its initial phase number is
362 * the same as that of parent phaser.
363 *
364 * @param parent the parent phaser
365 */
366 public Phaser(Phaser parent) {
367 int phase = 0;
368 this.parent = parent;
369 if (parent != null) {
370 this.root = parent.root;
371 phase = parent.register();
372 }
373 else
374 this.root = this;
375 this.state = trippedStateFor(phase, 0);
376 }
377
378 /**
379 * Creates a new phaser with the given parent and number of
380 * registered unarrived parties. If parent is non-null, this phaser
381 * is registered with the parent and its initial phase number is
382 * the same as that of parent phaser.
383 *
384 * @param parent the parent phaser
385 * @param parties the number of parties required to trip barrier
386 * @throws IllegalArgumentException if parties less than zero
387 * or greater than the maximum number of parties supported
388 */
389 public Phaser(Phaser parent, int parties) {
390 if (parties < 0 || parties > ushortMask)
391 throw new IllegalArgumentException("Illegal number of parties");
392 int phase = 0;
393 this.parent = parent;
394 if (parent != null) {
395 this.root = parent.root;
396 phase = parent.register();
397 }
398 else
399 this.root = this;
400 this.state = trippedStateFor(phase, parties);
401 }
402
403 /**
404 * Adds a new unarrived party to this phaser.
405 *
406 * @return the arrival phase number to which this registration applied
407 * @throws IllegalStateException if attempting to register more
408 * than the maximum supported number of parties
409 */
410 public int register() {
411 return doRegister(1);
412 }
413
414 /**
415 * Adds the given number of new unarrived parties to this phaser.
416 *
417 * @param parties the number of additional parties required to trip barrier
418 * @return the arrival phase number to which this registration applied
419 * @throws IllegalStateException if attempting to register more
420 * than the maximum supported number of parties
421 * @throws IllegalArgumentException if {@code parties < 0}
422 */
423 public int bulkRegister(int parties) {
424 if (parties < 0)
425 throw new IllegalArgumentException();
426 if (parties == 0)
427 return getPhase();
428 return doRegister(parties);
429 }
430
431 /**
432 * Shared code for register, bulkRegister
433 */
434 private int doRegister(int registrations) {
435 int phase;
436 for (;;) {
437 long s = getReconciledState();
438 phase = phaseOf(s);
439 int unarrived = unarrivedOf(s) + registrations;
440 int parties = partiesOf(s) + registrations;
441 if (phase < 0)
442 break;
443 if (parties > ushortMask || unarrived > ushortMask)
444 throw new IllegalStateException(badBounds(parties, unarrived));
445 if (phase == phaseOf(root.state) &&
446 casState(s, stateFor(phase, parties, unarrived)))
447 break;
448 }
449 return phase;
450 }
451
452 /**
453 * Arrives at the barrier, but does not wait for others. (You can
454 * in turn wait for others via {@link #awaitAdvance}). It is an
455 * unenforced usage error for an unregistered party to invoke this
456 * method.
457 *
458 * @return the arrival phase number, or a negative value if terminated
459 * @throws IllegalStateException if not terminated and the number
460 * of unarrived parties would become negative
461 */
462 public int arrive() {
463 int phase;
464 for (;;) {
465 long s = state;
466 phase = phaseOf(s);
467 if (phase < 0)
468 break;
469 int parties = partiesOf(s);
470 int unarrived = unarrivedOf(s) - 1;
471 if (unarrived > 0) { // Not the last arrival
472 if (casState(s, s - 1)) // s-1 adds one arrival
473 break;
474 }
475 else if (unarrived == 0) { // the last arrival
476 Phaser par = parent;
477 if (par == null) { // directly trip
478 if (casState
479 (s,
480 trippedStateFor(onAdvance(phase, parties) ? -1 :
481 ((phase + 1) & phaseMask), parties))) {
482 releaseWaiters(phase);
483 break;
484 }
485 }
486 else { // cascade to parent
487 if (casState(s, s - 1)) { // zeroes unarrived
488 par.arrive();
489 reconcileState();
490 break;
491 }
492 }
493 }
494 else if (phase != phaseOf(root.state)) // or if unreconciled
495 reconcileState();
496 else
497 throw new IllegalStateException(badBounds(parties, unarrived));
498 }
499 return phase;
500 }
501
502 /**
503 * Arrives at the barrier and deregisters from it without waiting
504 * for others. Deregistration reduces the number of parties
505 * required to trip the barrier in future phases. If this phaser
506 * has a parent, and deregistration causes this phaser to have
507 * zero parties, this phaser also arrives at and is deregistered
508 * from its parent. It is an unenforced usage error for an
509 * unregistered party to invoke this method.
510 *
511 * @return the arrival phase number, or a negative value if terminated
512 * @throws IllegalStateException if not terminated and the number
513 * of registered or unarrived parties would become negative
514 */
515 public int arriveAndDeregister() {
516 // similar code to arrive, but too different to merge
517 Phaser par = parent;
518 int phase;
519 for (;;) {
520 long s = state;
521 phase = phaseOf(s);
522 if (phase < 0)
523 break;
524 int parties = partiesOf(s) - 1;
525 int unarrived = unarrivedOf(s) - 1;
526 if (parties >= 0) {
527 if (unarrived > 0 || (unarrived == 0 && par != null)) {
528 if (casState
529 (s,
530 stateFor(phase, parties, unarrived))) {
531 if (unarrived == 0) {
532 par.arriveAndDeregister();
533 reconcileState();
534 }
535 break;
536 }
537 continue;
538 }
539 if (unarrived == 0) {
540 if (casState
541 (s,
542 trippedStateFor(onAdvance(phase, parties) ? -1 :
543 ((phase + 1) & phaseMask), parties))) {
544 releaseWaiters(phase);
545 break;
546 }
547 continue;
548 }
549 if (par != null && phase != phaseOf(root.state)) {
550 reconcileState();
551 continue;
552 }
553 }
554 throw new IllegalStateException(badBounds(parties, unarrived));
555 }
556 return phase;
557 }
558
559 /**
560 * Arrives at the barrier and awaits others. Equivalent in effect
561 * to {@code awaitAdvance(arrive())}. If you need to await with
562 * interruption or timeout, you can arrange this with an analogous
563 * construction using one of the other forms of the {@code
564 * awaitAdvance} method. If instead you need to deregister upon
565 * arrival, use {@link #arriveAndDeregister}. It is an unenforced
566 * usage error for an unregistered party to invoke this method.
567 *
568 * @return the arrival phase number, or a negative number if terminated
569 * @throws IllegalStateException if not terminated and the number
570 * of unarrived parties would become negative
571 */
572 public int arriveAndAwaitAdvance() {
573 return awaitAdvance(arrive());
574 }
575
576 /**
577 * Awaits the phase of the barrier to advance from the given phase
578 * value, returning immediately if the current phase of the
579 * barrier is not equal to the given phase value or this barrier
580 * is terminated. It is an unenforced usage error for an
581 * unregistered party to invoke this method.
582 *
583 * @param phase an arrival phase number, or negative value if
584 * terminated; this argument is normally the value returned by a
585 * previous call to {@code arrive} or its variants
586 * @return the next arrival phase number, or a negative value
587 * if terminated or argument is negative
588 */
589 public int awaitAdvance(int phase) {
590 if (phase < 0)
591 return phase;
592 long s = getReconciledState();
593 int p = phaseOf(s);
594 if (p != phase)
595 return p;
596 if (unarrivedOf(s) == 0 && parent != null)
597 parent.awaitAdvance(phase);
598 // Fall here even if parent waited, to reconcile and help release
599 return untimedWait(phase);
600 }
601
602 /**
603 * Awaits the phase of the barrier to advance from the given phase
604 * value, throwing {@code InterruptedException} if interrupted
605 * while waiting, or returning immediately if the current phase of
606 * the barrier is not equal to the given phase value or this
607 * barrier is terminated. It is an unenforced usage error for an
608 * unregistered party to invoke this method.
609 *
610 * @param phase an arrival phase number, or negative value if
611 * terminated; this argument is normally the value returned by a
612 * previous call to {@code arrive} or its variants
613 * @return the next arrival phase number, or a negative value
614 * if terminated or argument is negative
615 * @throws InterruptedException if thread interrupted while waiting
616 */
617 public int awaitAdvanceInterruptibly(int phase)
618 throws InterruptedException {
619 if (phase < 0)
620 return phase;
621 long s = getReconciledState();
622 int p = phaseOf(s);
623 if (p != phase)
624 return p;
625 if (unarrivedOf(s) == 0 && parent != null)
626 parent.awaitAdvanceInterruptibly(phase);
627 return interruptibleWait(phase);
628 }
629
630 /**
631 * Awaits the phase of the barrier to advance from the given phase
632 * value or the given timeout to elapse, throwing {@code
633 * InterruptedException} if interrupted while waiting, or
634 * returning immediately if the current phase of the barrier is
635 * not equal to the given phase value or this barrier is
636 * terminated. It is an unenforced usage error for an
637 * unregistered party to invoke this method.
638 *
639 * @param phase an arrival phase number, or negative value if
640 * terminated; this argument is normally the value returned by a
641 * previous call to {@code arrive} or its variants
642 * @param timeout how long to wait before giving up, in units of
643 * {@code unit}
644 * @param unit a {@code TimeUnit} determining how to interpret the
645 * {@code timeout} parameter
646 * @return the next arrival phase number, or a negative value
647 * if terminated or argument is negative
648 * @throws InterruptedException if thread interrupted while waiting
649 * @throws TimeoutException if timed out while waiting
650 */
651 public int awaitAdvanceInterruptibly(int phase,
652 long timeout, TimeUnit unit)
653 throws InterruptedException, TimeoutException {
654 if (phase < 0)
655 return phase;
656 long s = getReconciledState();
657 int p = phaseOf(s);
658 if (p != phase)
659 return p;
660 if (unarrivedOf(s) == 0 && parent != null)
661 parent.awaitAdvanceInterruptibly(phase, timeout, unit);
662 return timedWait(phase, unit.toNanos(timeout));
663 }
664
665 /**
666 * Forces this barrier to enter termination state. Counts of
667 * arrived and registered parties are unaffected. If this phaser
668 * has a parent, it too is terminated. This method may be useful
669 * for coordinating recovery after one or more tasks encounter
670 * unexpected exceptions.
671 */
672 public void forceTermination() {
673 for (;;) {
674 long s = getReconciledState();
675 int phase = phaseOf(s);
676 int parties = partiesOf(s);
677 int unarrived = unarrivedOf(s);
678 if (phase < 0 ||
679 casState(s, stateFor(-1, parties, unarrived))) {
680 releaseWaiters(0);
681 releaseWaiters(1);
682 if (parent != null)
683 parent.forceTermination();
684 return;
685 }
686 }
687 }
688
689 /**
690 * Returns the current phase number. The maximum phase number is
691 * {@code Integer.MAX_VALUE}, after which it restarts at
692 * zero. Upon termination, the phase number is negative.
693 *
694 * @return the phase number, or a negative value if terminated
695 */
696 public final int getPhase() {
697 return phaseOf(getReconciledState());
698 }
699
700 /**
701 * Returns the number of parties registered at this barrier.
702 *
703 * @return the number of parties
704 */
705 public int getRegisteredParties() {
706 return partiesOf(state);
707 }
708
709 /**
710 * Returns the number of registered parties that have arrived at
711 * the current phase of this barrier.
712 *
713 * @return the number of arrived parties
714 */
715 public int getArrivedParties() {
716 return arrivedOf(state);
717 }
718
719 /**
720 * Returns the number of registered parties that have not yet
721 * arrived at the current phase of this barrier.
722 *
723 * @return the number of unarrived parties
724 */
725 public int getUnarrivedParties() {
726 return unarrivedOf(state);
727 }
728
729 /**
730 * Returns the parent of this phaser, or {@code null} if none.
731 *
732 * @return the parent of this phaser, or {@code null} if none
733 */
734 public Phaser getParent() {
735 return parent;
736 }
737
738 /**
739 * Returns the root ancestor of this phaser, which is the same as
740 * this phaser if it has no parent.
741 *
742 * @return the root ancestor of this phaser
743 */
744 public Phaser getRoot() {
745 return root;
746 }
747
748 /**
749 * Returns {@code true} if this barrier has been terminated.
750 *
751 * @return {@code true} if this barrier has been terminated
752 */
753 public boolean isTerminated() {
754 return getPhase() < 0;
755 }
756
757 /**
758 * Overridable method to perform an action upon impending phase
759 * advance, and to control termination. This method is invoked
760 * upon arrival of the party tripping the barrier (when all other
761 * waiting parties are dormant). If this method returns {@code
762 * true}, then, rather than advance the phase number, this barrier
763 * will be set to a final termination state, and subsequent calls
764 * to {@link #isTerminated} will return true. Any (unchecked)
765 * Exception or Error thrown by an invocation of this method is
766 * propagated to the party attempting to trip the barrier, in
767 * which case no advance occurs.
768 *
769 * <p>The arguments to this method provide the state of the phaser
770 * prevailing for the current transition. (When called from within
771 * an implementation of {@code onAdvance} the values returned by
772 * methods such as {@code getPhase} may or may not reliably
773 * indicate the state to which this transition applies.)
774 *
775 * <p>The default version returns {@code true} when the number of
776 * registered parties is zero. Normally, overrides that arrange
777 * termination for other reasons should also preserve this
778 * property.
779 *
780 * <p>You may override this method to perform an action with side
781 * effects visible to participating tasks, but it is only sensible
782 * to do so in designs where all parties register before any
783 * arrive, and all {@link #awaitAdvance} at each phase.
784 * Otherwise, you cannot ensure lack of interference from other
785 * parties during the invocation of this method. Additionally,
786 * method {@code onAdvance} may be invoked more than once per
787 * transition if registrations are intermixed with arrivals.
788 *
789 * @param phase the phase number on entering the barrier
790 * @param registeredParties the current number of registered parties
791 * @return {@code true} if this barrier should terminate
792 */
793 protected boolean onAdvance(int phase, int registeredParties) {
794 return registeredParties <= 0;
795 }
796
797 /**
798 * Returns a string identifying this phaser, as well as its
799 * state. The state, in brackets, includes the String {@code
800 * "phase = "} followed by the phase number, {@code "parties = "}
801 * followed by the number of registered parties, and {@code
802 * "arrived = "} followed by the number of arrived parties.
803 *
804 * @return a string identifying this barrier, as well as its state
805 */
806 public String toString() {
807 long s = getReconciledState();
808 return super.toString() +
809 "[phase = " + phaseOf(s) +
810 " parties = " + partiesOf(s) +
811 " arrived = " + arrivedOf(s) + "]";
812 }
813
814 // methods for waiting
815
816 /**
817 * Wait nodes for Treiber stack representing wait queue
818 */
819 static final class QNode implements ForkJoinPool.ManagedBlocker {
820 final Phaser phaser;
821 final int phase;
822 final long startTime;
823 final long nanos;
824 final boolean timed;
825 final boolean interruptible;
826 volatile boolean wasInterrupted = false;
827 volatile Thread thread; // nulled to cancel wait
828 QNode next;
829
830 QNode(Phaser phaser, int phase, boolean interruptible,
831 boolean timed, long startTime, long nanos) {
832 this.phaser = phaser;
833 this.phase = phase;
834 this.timed = timed;
835 this.interruptible = interruptible;
836 this.startTime = startTime;
837 this.nanos = nanos;
838 thread = Thread.currentThread();
839 }
840
841 public boolean isReleasable() {
842 return (thread == null ||
843 phaser.getPhase() != phase ||
844 (interruptible && wasInterrupted) ||
845 (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
846 }
847
848 public boolean block() {
849 if (Thread.interrupted()) {
850 wasInterrupted = true;
851 if (interruptible)
852 return true;
853 }
854 if (!timed)
855 LockSupport.park(this);
856 else {
857 long waitTime = nanos - (System.nanoTime() - startTime);
858 if (waitTime <= 0)
859 return true;
860 LockSupport.parkNanos(this, waitTime);
861 }
862 return isReleasable();
863 }
864
865 void signal() {
866 Thread t = thread;
867 if (t != null) {
868 thread = null;
869 LockSupport.unpark(t);
870 }
871 }
872
873 boolean doWait() {
874 if (thread != null) {
875 try {
876 ForkJoinPool.managedBlock(this);
877 } catch (InterruptedException ie) {
878 wasInterrupted = true; // can't currently happen
879 }
880 }
881 return wasInterrupted;
882 }
883 }
884
885 /**
886 * Removes and signals waiting threads from wait queue.
887 */
888 private void releaseWaiters(int phase) {
889 AtomicReference<QNode> head = queueFor(phase);
890 QNode q;
891 while ((q = head.get()) != null) {
892 if (head.compareAndSet(q, q.next))
893 q.signal();
894 }
895 }
896
897 /**
898 * Tries to enqueue given node in the appropriate wait queue.
899 *
900 * @return true if successful
901 */
902 private boolean tryEnqueue(QNode node) {
903 AtomicReference<QNode> head = queueFor(node.phase);
904 return head.compareAndSet(node.next = head.get(), node);
905 }
906
907 /**
908 * Enqueues node and waits unless aborted or signalled.
909 *
910 * @return current phase
911 */
912 private int untimedWait(int phase) {
913 QNode node = null;
914 boolean queued = false;
915 boolean interrupted = false;
916 int p;
917 while ((p = getPhase()) == phase) {
918 if (Thread.interrupted())
919 interrupted = true;
920 else if (node == null)
921 node = new QNode(this, phase, false, false, 0, 0);
922 else if (!queued)
923 queued = tryEnqueue(node);
924 else if (node.doWait())
925 interrupted = true;
926 }
927 if (node != null)
928 node.thread = null;
929 releaseWaiters(phase);
930 if (interrupted)
931 Thread.currentThread().interrupt();
932 return p;
933 }
934
935 /**
936 * Interruptible version
937 * @return current phase
938 */
939 private int interruptibleWait(int phase) throws InterruptedException {
940 QNode node = null;
941 boolean queued = false;
942 boolean interrupted = false;
943 int p;
944 while ((p = getPhase()) == phase && !interrupted) {
945 if (Thread.interrupted())
946 interrupted = true;
947 else if (node == null)
948 node = new QNode(this, phase, true, false, 0, 0);
949 else if (!queued)
950 queued = tryEnqueue(node);
951 else if (node.doWait())
952 interrupted = true;
953 }
954 if (node != null)
955 node.thread = null;
956 if (p != phase || (p = getPhase()) != phase)
957 releaseWaiters(phase);
958 if (interrupted)
959 throw new InterruptedException();
960 return p;
961 }
962
963 /**
964 * Timeout version.
965 * @return current phase
966 */
967 private int timedWait(int phase, long nanos)
968 throws InterruptedException, TimeoutException {
969 long startTime = System.nanoTime();
970 QNode node = null;
971 boolean queued = false;
972 boolean interrupted = false;
973 int p;
974 while ((p = getPhase()) == phase && !interrupted) {
975 if (Thread.interrupted())
976 interrupted = true;
977 else if (nanos - (System.nanoTime() - startTime) <= 0)
978 break;
979 else if (node == null)
980 node = new QNode(this, phase, true, true, startTime, nanos);
981 else if (!queued)
982 queued = tryEnqueue(node);
983 else if (node.doWait())
984 interrupted = true;
985 }
986 if (node != null)
987 node.thread = null;
988 if (p != phase || (p = getPhase()) != phase)
989 releaseWaiters(phase);
990 if (interrupted)
991 throw new InterruptedException();
992 if (p == phase)
993 throw new TimeoutException();
994 return p;
995 }
996
997 // Unsafe mechanics
998
999 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1000 private static final long stateOffset =
1001 objectFieldOffset("state", Phaser.class);
1002
1003 private final boolean casState(long cmp, long val) {
1004 return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
1005 }
1006
1007 private static long objectFieldOffset(String field, Class<?> klazz) {
1008 try {
1009 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1010 } catch (NoSuchFieldException e) {
1011 // Convert Exception to corresponding Error
1012 NoSuchFieldError error = new NoSuchFieldError(field);
1013 error.initCause(e);
1014 throw error;
1015 }
1016 }
1017 }