ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.35
Committed: Sun Aug 23 13:37:08 2009 UTC (14 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.34: +36 -30 lines
Log Message:
Clarify meaning of phase arguments and return values

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