ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.14
Committed: Fri Nov 5 23:01:29 2010 UTC (13 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.13: +98 -125 lines
Log Message:
Suppress register on advance; share root queues; misc touchups

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