ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Phaser.java
Revision: 1.9
Committed: Thu Aug 20 16:38:43 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +9 -3 lines
Log Message:
sync with jsr166 package

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