ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/Phaser.java
Revision: 1.19
Committed: Fri Jul 24 23:47:01 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.18: +23 -26 lines
Log Message:
Unsafe mechanics

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 import java.util.concurrent.atomic.*;
11 import java.util.concurrent.locks.LockSupport;
12
13 /**
14 * A reusable synchronization barrier, similar in functionality to a
15 * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
16 * {@link java.util.concurrent.CountDownLatch CountDownLatch}
17 * but supporting more flexible usage.
18 *
19 * <ul>
20 *
21 * <li> The number of parties synchronizing on a phaser may vary over
22 * time. A task may register to be a party at any time, and may
23 * deregister upon arriving at the barrier. As is the case with most
24 * basic synchronization constructs, registration and deregistration
25 * affect only internal counts; they do not establish any further
26 * internal bookkeeping, so tasks cannot query whether they are
27 * registered. (However, you can introduce such bookkeeping by
28 * subclassing this class.)
29 *
30 * <li> Each generation has an associated phase value, starting at
31 * zero, and advancing when all parties reach the barrier (wrapping
32 * around to zero after reaching {@code Integer.MAX_VALUE}).
33 *
34 * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
35 * Method {@code arriveAndAwaitAdvance} has effect analogous to
36 * {@code CyclicBarrier.await}. However, Phasers separate two
37 * aspects of coordination, that may also be invoked independently:
38 *
39 * <ul>
40 *
41 * <li> Arriving at a barrier. Methods {@code arrive} and
42 * {@code arriveAndDeregister} do not block, but return
43 * the phase value current upon entry to the method.
44 *
45 * <li> Awaiting others. Method {@code 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 while others may be waiting, are arranged by overriding
53 * method {@code onAdvance}, that also controls termination.
54 * Overriding this method may be used to similar but more flexible
55 * effect as providing a barrier action to a 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 by executing the
61 * overridable {@code onAdvance} method that is invoked each time the
62 * barrier is about to be tripped. When a Phaser is controlling an
63 * action with a fixed number of iterations, it is often convenient to
64 * override this method to cause termination when the current phase
65 * number reaches a threshold. Method {@code forceTermination} is also
66 * available to abruptly release waiting threads and allow them to
67 * terminate.
68 *
69 * <li> Phasers may be tiered to reduce contention. Phasers with large
70 * numbers of parties that would otherwise experience heavy
71 * synchronization contention costs may instead be arranged in trees.
72 * This will typically greatly increase throughput even though it
73 * incurs somewhat greater per-operation overhead.
74 *
75 * <li> By default, {@code awaitAdvance} continues to wait even if
76 * the waiting thread is interrupted. And unlike the case in
77 * CyclicBarriers, exceptions encountered while tasks wait
78 * interruptibly or with timeout do not change the state of the
79 * barrier. If necessary, you can perform any associated recovery
80 * within handlers of those exceptions, often after invoking
81 * {@code forceTermination}.
82 *
83 * <li>Phasers ensure lack of starvation when used by ForkJoinTasks.
84 *
85 * </ul>
86 *
87 * <p><b>Sample usages:</b>
88 *
89 * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
90 * a one-shot action serving a variable number of parties. The typical
91 * idiom is for the method setting this up to first register, then
92 * start the actions, then deregister, as in:
93 *
94 * <pre> {@code
95 * void runTasks(List<Runnable> list) {
96 * final Phaser phaser = new Phaser(1); // "1" to register self
97 * for (Runnable r : list) {
98 * phaser.register();
99 * new Thread() {
100 * public void run() {
101 * phaser.arriveAndAwaitAdvance(); // await all creation
102 * r.run();
103 * phaser.arriveAndDeregister(); // signal completion
104 * }
105 * }.start();
106 * }
107 *
108 * doSomethingOnBehalfOfWorkers();
109 * phaser.arrive(); // allow threads to start
110 * int p = phaser.arriveAndDeregister(); // deregister self ...
111 * p = phaser.awaitAdvance(p); // ... and await arrival
112 * otherActions(); // do other things while tasks execute
113 * phaser.awaitAdvance(p); // await final completion
114 * }}</pre>
115 *
116 * <p>One way to cause a set of threads to repeatedly perform actions
117 * for a given number of iterations is to override {@code onAdvance}:
118 *
119 * <pre> {@code
120 * void startTasks(List<Runnable> list, final int iterations) {
121 * final Phaser phaser = new Phaser() {
122 * public boolean onAdvance(int phase, int registeredParties) {
123 * return phase >= iterations || registeredParties == 0;
124 * }
125 * };
126 * phaser.register();
127 * for (Runnable r : list) {
128 * phaser.register();
129 * new Thread() {
130 * public void run() {
131 * do {
132 * r.run();
133 * phaser.arriveAndAwaitAdvance();
134 * } while(!phaser.isTerminated();
135 * }
136 * }.start();
137 * }
138 * phaser.arriveAndDeregister(); // deregister self, don't wait
139 * }}</pre>
140 *
141 * <p> To create a set of tasks using a tree of Phasers,
142 * you could use code of the following form, assuming a
143 * Task class with a constructor accepting a Phaser that
144 * it registers for upon construction:
145 * <pre> {@code
146 * void build(Task[] actions, int lo, int hi, Phaser b) {
147 * int step = (hi - lo) / TASKS_PER_PHASER;
148 * if (step > 1) {
149 * int i = lo;
150 * while (i < hi) {
151 * int r = Math.min(i + step, hi);
152 * build(actions, i, r, new Phaser(b));
153 * i = r;
154 * }
155 * } else {
156 * for (int i = lo; i < hi; ++i)
157 * actions[i] = new Task(b);
158 * // assumes new Task(b) performs b.register()
159 * }
160 * }
161 * // .. initially called, for n tasks via
162 * build(new Task[n], 0, n, new Phaser());}</pre>
163 *
164 * The best value of {@code TASKS_PER_PHASER} depends mainly on
165 * expected barrier synchronization rates. A value as low as four may
166 * be appropriate for extremely small per-barrier task bodies (thus
167 * high rates), or up to hundreds for extremely large ones.
168 *
169 * </pre>
170 *
171 * <p><b>Implementation notes</b>: This implementation restricts the
172 * maximum number of parties to 65535. Attempts to register additional
173 * parties result in IllegalStateExceptions. However, you can and
174 * should create tiered phasers to accommodate arbitrarily large sets
175 * of participants.
176 *
177 * @since 1.7
178 * @author Doug Lea
179 */
180 public class Phaser {
181 /*
182 * This class implements an extension of X10 "clocks". Thanks to
183 * Vijay Saraswat for the idea, and to Vivek Sarkar for
184 * enhancements to extend functionality.
185 */
186
187 /**
188 * Barrier state representation. Conceptually, a barrier contains
189 * four values:
190 *
191 * * parties -- the number of parties to wait (16 bits)
192 * * unarrived -- the number of parties yet to hit barrier (16 bits)
193 * * phase -- the generation of the barrier (31 bits)
194 * * terminated -- set if barrier is terminated (1 bit)
195 *
196 * However, to efficiently maintain atomicity, these values are
197 * packed into a single (atomic) long. Termination uses the sign
198 * bit of 32 bit representation of phase, so phase is set to -1 on
199 * termination. Good performance relies on keeping state decoding
200 * and encoding simple, and keeping race windows short.
201 *
202 * Note: there are some cheats in arrive() that rely on unarrived
203 * count being lowest 16 bits.
204 */
205 private volatile long state;
206
207 private static final int ushortBits = 16;
208 private static final int ushortMask = 0xffff;
209 private static final int phaseMask = 0x7fffffff;
210
211 private static int unarrivedOf(long s) {
212 return (int) (s & ushortMask);
213 }
214
215 private static int partiesOf(long s) {
216 return ((int) s) >>> 16;
217 }
218
219 private static int phaseOf(long s) {
220 return (int) (s >>> 32);
221 }
222
223 private static int arrivedOf(long s) {
224 return partiesOf(s) - unarrivedOf(s);
225 }
226
227 private static long stateFor(int phase, int parties, int unarrived) {
228 return ((((long) phase) << 32) | (((long) parties) << 16) |
229 (long) unarrived);
230 }
231
232 private static long trippedStateFor(int phase, int parties) {
233 long lp = (long) parties;
234 return (((long) phase) << 32) | (lp << 16) | lp;
235 }
236
237 /**
238 * Returns message string for bad bounds exceptions.
239 */
240 private static String badBounds(int parties, int unarrived) {
241 return ("Attempt to set " + unarrived +
242 " unarrived of " + parties + " parties");
243 }
244
245 /**
246 * The parent of this phaser, or null if none
247 */
248 private final Phaser parent;
249
250 /**
251 * The root of Phaser tree. Equals this if not in a tree. Used to
252 * support faster state push-down.
253 */
254 private final Phaser root;
255
256 // Wait queues
257
258 /**
259 * Heads of Treiber stacks for waiting threads. To eliminate
260 * contention while releasing some threads while adding others, we
261 * use two of them, alternating across even and odd phases.
262 */
263 private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
264 private final AtomicReference<QNode> oddQ = new AtomicReference<QNode>();
265
266 private AtomicReference<QNode> queueFor(int phase) {
267 return ((phase & 1) == 0) ? evenQ : oddQ;
268 }
269
270 /**
271 * Returns current state, first resolving lagged propagation from
272 * root if necessary.
273 */
274 private long getReconciledState() {
275 return (parent == null) ? state : reconcileState();
276 }
277
278 /**
279 * Recursively resolves state.
280 */
281 private long reconcileState() {
282 Phaser p = parent;
283 long s = state;
284 if (p != null) {
285 while (unarrivedOf(s) == 0 && phaseOf(s) != phaseOf(root.state)) {
286 long parentState = p.getReconciledState();
287 int parentPhase = phaseOf(parentState);
288 int phase = phaseOf(s = state);
289 if (phase != parentPhase) {
290 long next = trippedStateFor(parentPhase, partiesOf(s));
291 if (casState(s, next)) {
292 releaseWaiters(phase);
293 s = next;
294 }
295 }
296 }
297 }
298 return s;
299 }
300
301 /**
302 * Creates a new Phaser without any initially registered parties,
303 * initial phase number 0, and no parent. Any thread using this
304 * Phaser will need to first register for it.
305 */
306 public Phaser() {
307 this(null);
308 }
309
310 /**
311 * Creates a new Phaser with the given numbers of registered
312 * unarrived parties, initial phase number 0, and no parent.
313 *
314 * @param parties the number of parties required to trip barrier
315 * @throws IllegalArgumentException if parties less than zero
316 * or greater than the maximum number of parties supported
317 */
318 public Phaser(int parties) {
319 this(null, parties);
320 }
321
322 /**
323 * Creates a new Phaser with the given parent, without any
324 * initially registered parties. If parent is non-null this phaser
325 * is registered with the parent and its initial phase number is
326 * the same as that of parent phaser.
327 *
328 * @param parent the parent phaser
329 */
330 public Phaser(Phaser parent) {
331 int phase = 0;
332 this.parent = parent;
333 if (parent != null) {
334 this.root = parent.root;
335 phase = parent.register();
336 }
337 else
338 this.root = this;
339 this.state = trippedStateFor(phase, 0);
340 }
341
342 /**
343 * Creates a new Phaser with the given parent and numbers of
344 * registered unarrived parties. If parent is non-null, this phaser
345 * is registered with the parent and its initial phase number is
346 * the same as that of parent phaser.
347 *
348 * @param parent the parent phaser
349 * @param parties the number of parties required to trip barrier
350 * @throws IllegalArgumentException if parties less than zero
351 * or greater than the maximum number of parties supported
352 */
353 public Phaser(Phaser parent, int parties) {
354 if (parties < 0 || parties > ushortMask)
355 throw new IllegalArgumentException("Illegal number of parties");
356 int phase = 0;
357 this.parent = parent;
358 if (parent != null) {
359 this.root = parent.root;
360 phase = parent.register();
361 }
362 else
363 this.root = this;
364 this.state = trippedStateFor(phase, parties);
365 }
366
367 /**
368 * Adds a new unarrived party to this phaser.
369 *
370 * @return the current barrier phase number upon registration
371 * @throws IllegalStateException if attempting to register more
372 * than the maximum supported number of parties
373 */
374 public int register() {
375 return doRegister(1);
376 }
377
378 /**
379 * Adds the given number of new unarrived parties to this phaser.
380 *
381 * @param parties the number of parties required to trip barrier
382 * @return the current barrier phase number upon registration
383 * @throws IllegalStateException if attempting to register more
384 * than the maximum supported number of parties
385 */
386 public int bulkRegister(int parties) {
387 if (parties < 0)
388 throw new IllegalArgumentException();
389 if (parties == 0)
390 return getPhase();
391 return doRegister(parties);
392 }
393
394 /**
395 * Shared code for register, bulkRegister
396 */
397 private int doRegister(int registrations) {
398 int phase;
399 for (;;) {
400 long s = getReconciledState();
401 phase = phaseOf(s);
402 int unarrived = unarrivedOf(s) + registrations;
403 int parties = partiesOf(s) + registrations;
404 if (phase < 0)
405 break;
406 if (parties > ushortMask || unarrived > ushortMask)
407 throw new IllegalStateException(badBounds(parties, unarrived));
408 if (phase == phaseOf(root.state) &&
409 casState(s, stateFor(phase, parties, unarrived)))
410 break;
411 }
412 return phase;
413 }
414
415 /**
416 * Arrives at the barrier, but does not wait for others. (You can
417 * in turn wait for others via {@link #awaitAdvance}).
418 *
419 * @return the barrier phase number upon entry to this method, or a
420 * negative value if terminated
421 * @throws IllegalStateException if not terminated and the number
422 * of unarrived parties would become negative
423 */
424 public int arrive() {
425 int phase;
426 for (;;) {
427 long s = state;
428 phase = phaseOf(s);
429 if (phase < 0)
430 break;
431 int parties = partiesOf(s);
432 int unarrived = unarrivedOf(s) - 1;
433 if (unarrived > 0) { // Not the last arrival
434 if (casState(s, s - 1)) // s-1 adds one arrival
435 break;
436 }
437 else if (unarrived == 0) { // the last arrival
438 Phaser par = parent;
439 if (par == null) { // directly trip
440 if (casState
441 (s,
442 trippedStateFor(onAdvance(phase, parties) ? -1 :
443 ((phase + 1) & phaseMask), parties))) {
444 releaseWaiters(phase);
445 break;
446 }
447 }
448 else { // cascade to parent
449 if (casState(s, s - 1)) { // zeroes unarrived
450 par.arrive();
451 reconcileState();
452 break;
453 }
454 }
455 }
456 else if (phase != phaseOf(root.state)) // or if unreconciled
457 reconcileState();
458 else
459 throw new IllegalStateException(badBounds(parties, unarrived));
460 }
461 return phase;
462 }
463
464 /**
465 * Arrives at the barrier, and deregisters from it, without
466 * waiting for others. Deregistration reduces number of parties
467 * required to trip the barrier in future phases. If this phaser
468 * has a parent, and deregistration causes this phaser to have
469 * zero parties, this phaser is also deregistered from its parent.
470 *
471 * @return the current barrier phase number upon entry to
472 * this method, or a negative value if terminated
473 * @throws IllegalStateException if not terminated and the number
474 * of registered or unarrived parties would become negative
475 */
476 public int arriveAndDeregister() {
477 // similar code to arrive, but too different to merge
478 Phaser par = parent;
479 int phase;
480 for (;;) {
481 long s = state;
482 phase = phaseOf(s);
483 if (phase < 0)
484 break;
485 int parties = partiesOf(s) - 1;
486 int unarrived = unarrivedOf(s) - 1;
487 if (parties >= 0) {
488 if (unarrived > 0 || (unarrived == 0 && par != null)) {
489 if (casState
490 (s,
491 stateFor(phase, parties, unarrived))) {
492 if (unarrived == 0) {
493 par.arriveAndDeregister();
494 reconcileState();
495 }
496 break;
497 }
498 continue;
499 }
500 if (unarrived == 0) {
501 if (casState
502 (s,
503 trippedStateFor(onAdvance(phase, parties) ? -1 :
504 ((phase + 1) & phaseMask), parties))) {
505 releaseWaiters(phase);
506 break;
507 }
508 continue;
509 }
510 if (par != null && phase != phaseOf(root.state)) {
511 reconcileState();
512 continue;
513 }
514 }
515 throw new IllegalStateException(badBounds(parties, unarrived));
516 }
517 return phase;
518 }
519
520 /**
521 * Arrives at the barrier and awaits others. Equivalent in effect
522 * to {@code awaitAdvance(arrive())}. If you instead need to
523 * await with interruption of timeout, and/or deregister upon
524 * arrival, you can arrange them using analogous constructions.
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
536 * value, or returns immediately if argument is negative or this
537 * barrier is terminated.
538 *
539 * @param phase the phase on entry to this method
540 * @return the phase on exit from this method
541 */
542 public int awaitAdvance(int phase) {
543 if (phase < 0)
544 return phase;
545 long s = getReconciledState();
546 int p = phaseOf(s);
547 if (p != phase)
548 return p;
549 if (unarrivedOf(s) == 0 && parent != null)
550 parent.awaitAdvance(phase);
551 // Fall here even if parent waited, to reconcile and help release
552 return untimedWait(phase);
553 }
554
555 /**
556 * Awaits the phase of the barrier to advance from the given
557 * value, or returns immediately if argument is negative or this
558 * barrier is terminated, or throws InterruptedException if
559 * interrupted while waiting.
560 *
561 * @param phase the phase on entry to this method
562 * @return the phase on exit from this method
563 * @throws InterruptedException if thread interrupted while waiting
564 */
565 public int awaitAdvanceInterruptibly(int phase)
566 throws InterruptedException {
567 if (phase < 0)
568 return phase;
569 long s = getReconciledState();
570 int p = phaseOf(s);
571 if (p != phase)
572 return p;
573 if (unarrivedOf(s) == 0 && parent != null)
574 parent.awaitAdvanceInterruptibly(phase);
575 return interruptibleWait(phase);
576 }
577
578 /**
579 * Awaits the phase of the barrier to advance from the given value
580 * or the given timeout elapses, or returns immediately if
581 * argument is negative or this barrier is terminated.
582 *
583 * @param phase the phase on entry to this method
584 * @return the phase on exit from this method
585 * @throws InterruptedException if thread interrupted while waiting
586 * @throws TimeoutException if timed out while waiting
587 */
588 public int awaitAdvanceInterruptibly(int phase,
589 long timeout, TimeUnit unit)
590 throws InterruptedException, TimeoutException {
591 if (phase < 0)
592 return phase;
593 long s = getReconciledState();
594 int p = phaseOf(s);
595 if (p != phase)
596 return p;
597 if (unarrivedOf(s) == 0 && parent != null)
598 parent.awaitAdvanceInterruptibly(phase, timeout, unit);
599 return timedWait(phase, unit.toNanos(timeout));
600 }
601
602 /**
603 * Forces this barrier to enter termination state. Counts of
604 * arrived and registered parties are unaffected. If this phaser
605 * has a parent, it too is terminated. This method may be useful
606 * for coordinating recovery after one or more tasks encounter
607 * unexpected exceptions.
608 */
609 public void forceTermination() {
610 for (;;) {
611 long s = getReconciledState();
612 int phase = phaseOf(s);
613 int parties = partiesOf(s);
614 int unarrived = unarrivedOf(s);
615 if (phase < 0 ||
616 casState(s, stateFor(-1, parties, unarrived))) {
617 releaseWaiters(0);
618 releaseWaiters(1);
619 if (parent != null)
620 parent.forceTermination();
621 return;
622 }
623 }
624 }
625
626 /**
627 * Returns the current phase number. The maximum phase number is
628 * {@code Integer.MAX_VALUE}, after which it restarts at
629 * zero. Upon termination, the phase number is negative.
630 *
631 * @return the phase number, or a negative value if terminated
632 */
633 public final int getPhase() {
634 return phaseOf(getReconciledState());
635 }
636
637 /**
638 * Returns {@code true} if the current phase number equals the given phase.
639 *
640 * @param phase the phase
641 * @return {@code true} if the current phase number equals the given phase
642 */
643 public final boolean hasPhase(int phase) {
644 return phaseOf(getReconciledState()) == phase;
645 }
646
647 /**
648 * Returns the number of parties registered at this barrier.
649 *
650 * @return the number of parties
651 */
652 public int getRegisteredParties() {
653 return partiesOf(state);
654 }
655
656 /**
657 * Returns the number of parties that have arrived at the current
658 * phase of this barrier.
659 *
660 * @return the number of arrived parties
661 */
662 public int getArrivedParties() {
663 return arrivedOf(state);
664 }
665
666 /**
667 * Returns the number of registered parties that have not yet
668 * arrived at the current phase of this barrier.
669 *
670 * @return the number of unarrived parties
671 */
672 public int getUnarrivedParties() {
673 return unarrivedOf(state);
674 }
675
676 /**
677 * Returns the parent of this phaser, or null if none.
678 *
679 * @return the parent of this phaser, or null if none
680 */
681 public Phaser getParent() {
682 return parent;
683 }
684
685 /**
686 * Returns the root ancestor of this phaser, which is the same as
687 * this phaser if it has no parent.
688 *
689 * @return the root ancestor of this phaser
690 */
691 public Phaser getRoot() {
692 return root;
693 }
694
695 /**
696 * Returns {@code true} if this barrier has been terminated.
697 *
698 * @return {@code true} if this barrier has been terminated
699 */
700 public boolean isTerminated() {
701 return getPhase() < 0;
702 }
703
704 /**
705 * Overridable method to perform an action upon phase advance, and
706 * to control termination. This method is invoked whenever the
707 * barrier is tripped (and thus all other waiting parties are
708 * dormant). If it returns true, then, rather than advance the
709 * phase number, this barrier will be set to a final termination
710 * state, and subsequent calls to {@code isTerminated} will
711 * return true.
712 *
713 * <p> The default version returns true when the number of
714 * registered parties is zero. Normally, overrides that arrange
715 * termination for other reasons should also preserve this
716 * property.
717 *
718 * <p> You may override this method to perform an action with side
719 * effects visible to participating tasks, but it is in general
720 * only sensible to do so in designs where all parties register
721 * before any arrive, and all {@code awaitAdvance} at each phase.
722 * Otherwise, you cannot ensure lack of interference. In
723 * particular, this method may be invoked more than once per
724 * transition if other parties successfully register while the
725 * invocation of this method is in progress, thus postponing the
726 * transition until those parties also arrive, re-triggering this
727 * 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 for jsr166y 3rd party package.
933 private static sun.misc.Unsafe getUnsafe() {
934 try {
935 return sun.misc.Unsafe.getUnsafe();
936 } catch (SecurityException se) {
937 try {
938 return java.security.AccessController.doPrivileged
939 (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
940 public sun.misc.Unsafe run() throws Exception {
941 return getUnsafeByReflection();
942 }});
943 } catch (java.security.PrivilegedActionException e) {
944 throw new RuntimeException("Could not initialize intrinsics",
945 e.getCause());
946 }
947 }
948 }
949
950 private static sun.misc.Unsafe getUnsafeByReflection()
951 throws NoSuchFieldException, IllegalAccessException {
952 java.lang.reflect.Field f =
953 sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
954 f.setAccessible(true);
955 return (sun.misc.Unsafe) f.get(null);
956 }
957
958 private static long fieldOffset(String fieldName, Class<?> klazz) {
959 try {
960 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
961 } catch (NoSuchFieldException e) {
962 // Convert Exception to Error
963 NoSuchFieldError error = new NoSuchFieldError(fieldName);
964 error.initCause(e);
965 throw error;
966 }
967 }
968
969 private static final sun.misc.Unsafe UNSAFE = getUnsafe();
970 static final long stateOffset =
971 fieldOffset("state", Phaser.class);
972
973 final boolean casState(long cmp, long val) {
974 return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val);
975 }
976 }