5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
+ |
|
9 |
|
import java.util.concurrent.*; |
10 |
|
import java.util.concurrent.atomic.*; |
11 |
|
import java.util.concurrent.locks.LockSupport; |
14 |
|
|
15 |
|
/** |
16 |
|
* A reusable synchronization barrier, similar in functionality to a |
17 |
< |
* {@link java.util.concurrent.CyclicBarrier} and {@link |
18 |
< |
* java.util.concurrent.CountDownLatch} but supporting more flexible |
19 |
< |
* usage. |
17 |
> |
* {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and |
18 |
> |
* {@link java.util.concurrent.CountDownLatch CountDownLatch} |
19 |
> |
* but supporting more flexible usage. |
20 |
|
* |
21 |
|
* <ul> |
22 |
|
* |
26 |
|
* basic synchronization constructs, registration and deregistration |
27 |
|
* affect only internal counts; they do not establish any further |
28 |
|
* internal bookkeeping, so tasks cannot query whether they are |
29 |
< |
* registered. (However, you can introduce such bookkeeping in by |
29 |
> |
* registered. (However, you can introduce such bookkeeping by |
30 |
|
* subclassing this class.) |
31 |
|
* |
32 |
|
* <li> Each generation has an associated phase value, starting at |
57 |
|
* effect as providing a barrier action to a CyclicBarrier. |
58 |
|
* |
59 |
|
* <li> Phasers may enter a <em>termination</em> state in which all |
60 |
< |
* await actions immediately return, indicating (via a negative phase |
61 |
< |
* value) that execution is complete. Termination is triggered by |
62 |
< |
* executing the overridable {@code onAdvance} method that is invoked |
63 |
< |
* each time the barrier is about to be tripped. When a Phaser is |
64 |
< |
* controlling an action with a fixed number of iterations, it is |
65 |
< |
* often convenient to override this method to cause termination when |
66 |
< |
* the current phase number reaches a threshold. Method |
67 |
< |
* {@code forceTermination} is also available to abruptly release |
68 |
< |
* waiting threads and allow them to terminate. |
60 |
> |
* actions immediately return without updating phaser state or waiting |
61 |
> |
* for advance, and indicating (via a negative phase value) that |
62 |
> |
* execution is complete. Termination is triggered by executing the |
63 |
> |
* overridable {@code onAdvance} method that is invoked each time the |
64 |
> |
* barrier is about to be tripped. When a Phaser is controlling an |
65 |
> |
* action with a fixed number of iterations, it is often convenient to |
66 |
> |
* override this method to cause termination when the current phase |
67 |
> |
* number reaches a threshold. Method {@code forceTermination} is also |
68 |
> |
* available to abruptly release waiting threads and allow them to |
69 |
> |
* terminate. |
70 |
|
* |
71 |
|
* <li> Phasers may be tiered to reduce contention. Phasers with large |
72 |
|
* numbers of parties that would otherwise experience heavy |
82 |
|
* within handlers of those exceptions, often after invoking |
83 |
|
* {@code forceTermination}. |
84 |
|
* |
85 |
+ |
* <li>Phasers ensure lack of starvation when used by ForkJoinTasks. |
86 |
+ |
* |
87 |
|
* </ul> |
88 |
|
* |
89 |
|
* <p><b>Sample usages:</b> |
93 |
|
* idiom is for the method setting this up to first register, then |
94 |
|
* start the actions, then deregister, as in: |
95 |
|
* |
96 |
< |
* <pre> |
97 |
< |
* void runTasks(List<Runnable> list) { |
98 |
< |
* final Phaser phaser = new Phaser(1); // "1" to register self |
99 |
< |
* for (Runnable r : list) { |
100 |
< |
* phaser.register(); |
101 |
< |
* new Thread() { |
102 |
< |
* public void run() { |
103 |
< |
* phaser.arriveAndAwaitAdvance(); // await all creation |
104 |
< |
* r.run(); |
105 |
< |
* phaser.arriveAndDeregister(); // signal completion |
106 |
< |
* } |
107 |
< |
* }.start(); |
96 |
> |
* <pre> {@code |
97 |
> |
* void runTasks(List<Runnable> list) { |
98 |
> |
* final Phaser phaser = new Phaser(1); // "1" to register self |
99 |
> |
* for (Runnable r : list) { |
100 |
> |
* phaser.register(); |
101 |
> |
* new Thread() { |
102 |
> |
* public void run() { |
103 |
> |
* phaser.arriveAndAwaitAdvance(); // await all creation |
104 |
> |
* r.run(); |
105 |
> |
* phaser.arriveAndDeregister(); // signal completion |
106 |
> |
* } |
107 |
> |
* }.start(); |
108 |
|
* } |
109 |
|
* |
110 |
|
* doSomethingOnBehalfOfWorkers(); |
113 |
|
* p = phaser.awaitAdvance(p); // ... and await arrival |
114 |
|
* otherActions(); // do other things while tasks execute |
115 |
|
* phaser.awaitAdvance(p); // await final completion |
116 |
< |
* } |
113 |
< |
* </pre> |
116 |
> |
* }}</pre> |
117 |
|
* |
118 |
|
* <p>One way to cause a set of threads to repeatedly perform actions |
119 |
|
* for a given number of iterations is to override {@code onAdvance}: |
120 |
|
* |
121 |
< |
* <pre> |
122 |
< |
* void startTasks(List<Runnable> list, final int iterations) { |
123 |
< |
* final Phaser phaser = new Phaser() { |
124 |
< |
* public boolean onAdvance(int phase, int registeredParties) { |
125 |
< |
* return phase >= iterations || registeredParties == 0; |
121 |
> |
* <pre> {@code |
122 |
> |
* void startTasks(List<Runnable> list, final int iterations) { |
123 |
> |
* final Phaser phaser = new Phaser() { |
124 |
> |
* public boolean onAdvance(int phase, int registeredParties) { |
125 |
> |
* return phase >= iterations || registeredParties == 0; |
126 |
> |
* } |
127 |
> |
* }; |
128 |
> |
* phaser.register(); |
129 |
> |
* for (Runnable r : list) { |
130 |
> |
* phaser.register(); |
131 |
> |
* new Thread() { |
132 |
> |
* public void run() { |
133 |
> |
* do { |
134 |
> |
* r.run(); |
135 |
> |
* phaser.arriveAndAwaitAdvance(); |
136 |
> |
* } while(!phaser.isTerminated(); |
137 |
|
* } |
138 |
< |
* }; |
125 |
< |
* phaser.register(); |
126 |
< |
* for (Runnable r : list) { |
127 |
< |
* phaser.register(); |
128 |
< |
* new Thread() { |
129 |
< |
* public void run() { |
130 |
< |
* do { |
131 |
< |
* r.run(); |
132 |
< |
* phaser.arriveAndAwaitAdvance(); |
133 |
< |
* } while(!phaser.isTerminated(); |
134 |
< |
* } |
135 |
< |
* }.start(); |
138 |
> |
* }.start(); |
139 |
|
* } |
140 |
|
* phaser.arriveAndDeregister(); // deregister self, don't wait |
141 |
< |
* } |
139 |
< |
* </pre> |
141 |
> |
* }}</pre> |
142 |
|
* |
143 |
|
* <p> To create a set of tasks using a tree of Phasers, |
144 |
|
* you could use code of the following form, assuming a |
145 |
|
* Task class with a constructor accepting a Phaser that |
146 |
|
* it registers for upon construction: |
147 |
< |
* <pre> |
148 |
< |
* void build(Task[] actions, int lo, int hi, Phaser b) { |
149 |
< |
* int step = (hi - lo) / TASKS_PER_PHASER; |
150 |
< |
* if (step > 1) { |
151 |
< |
* int i = lo; |
152 |
< |
* while (i < hi) { |
153 |
< |
* int r = Math.min(i + step, hi); |
154 |
< |
* build(actions, i, r, new Phaser(b)); |
155 |
< |
* i = r; |
156 |
< |
* } |
157 |
< |
* } |
158 |
< |
* else { |
159 |
< |
* for (int i = lo; i < hi; ++i) |
160 |
< |
* actions[i] = new Task(b); |
161 |
< |
* // assumes new Task(b) performs b.register() |
162 |
< |
* } |
163 |
< |
* } |
164 |
< |
* // .. initially called, for n tasks via |
163 |
< |
* build(new Task[n], 0, n, new Phaser()); |
164 |
< |
* </pre> |
147 |
> |
* <pre> {@code |
148 |
> |
* void build(Task[] actions, int lo, int hi, Phaser b) { |
149 |
> |
* int step = (hi - lo) / TASKS_PER_PHASER; |
150 |
> |
* if (step > 1) { |
151 |
> |
* int i = lo; |
152 |
> |
* while (i < hi) { |
153 |
> |
* int r = Math.min(i + step, hi); |
154 |
> |
* build(actions, i, r, new Phaser(b)); |
155 |
> |
* i = r; |
156 |
> |
* } |
157 |
> |
* } else { |
158 |
> |
* for (int i = lo; i < hi; ++i) |
159 |
> |
* actions[i] = new Task(b); |
160 |
> |
* // assumes new Task(b) performs b.register() |
161 |
> |
* } |
162 |
> |
* } |
163 |
> |
* // .. initially called, for n tasks via |
164 |
> |
* build(new Task[n], 0, n, new Phaser());}</pre> |
165 |
|
* |
166 |
|
* The best value of {@code TASKS_PER_PHASER} depends mainly on |
167 |
|
* expected barrier synchronization rates. A value as low as four may |
175 |
|
* parties result in IllegalStateExceptions. However, you can and |
176 |
|
* should create tiered phasers to accommodate arbitrarily large sets |
177 |
|
* of participants. |
178 |
+ |
* |
179 |
+ |
* @since 1.7 |
180 |
+ |
* @author Doug Lea |
181 |
|
*/ |
182 |
|
public class Phaser { |
183 |
|
/* |
202 |
|
* and encoding simple, and keeping race windows short. |
203 |
|
* |
204 |
|
* Note: there are some cheats in arrive() that rely on unarrived |
205 |
< |
* being lowest 16 bits. |
205 |
> |
* count being lowest 16 bits. |
206 |
|
*/ |
207 |
|
private volatile long state; |
208 |
|
|
209 |
|
private static final int ushortBits = 16; |
210 |
< |
private static final int ushortMask = (1 << ushortBits) - 1; |
211 |
< |
private static final int phaseMask = 0x7fffffff; |
210 |
> |
private static final int ushortMask = 0xffff; |
211 |
> |
private static final int phaseMask = 0x7fffffff; |
212 |
|
|
213 |
|
private static int unarrivedOf(long s) { |
214 |
|
return (int)(s & ushortMask); |
215 |
|
} |
216 |
|
|
217 |
|
private static int partiesOf(long s) { |
218 |
< |
return (int)(s & (ushortMask << 16)) >>> 16; |
218 |
> |
return ((int)s) >>> 16; |
219 |
|
} |
220 |
|
|
221 |
|
private static int phaseOf(long s) { |
227 |
|
} |
228 |
|
|
229 |
|
private static long stateFor(int phase, int parties, int unarrived) { |
230 |
< |
return (((long)phase) << 32) | ((parties << 16) | unarrived); |
230 |
> |
return ((((long)phase) << 32) | (((long)parties) << 16) | |
231 |
> |
(long)unarrived); |
232 |
|
} |
233 |
|
|
234 |
|
private static long trippedStateFor(int phase, int parties) { |
235 |
< |
return (((long)phase) << 32) | ((parties << 16) | parties); |
235 |
> |
long lp = (long)parties; |
236 |
> |
return (((long)phase) << 32) | (lp << 16) | lp; |
237 |
|
} |
238 |
|
|
239 |
< |
private static IllegalStateException badBounds(int parties, int unarrived) { |
240 |
< |
return new IllegalStateException |
241 |
< |
("Attempt to set " + unarrived + |
242 |
< |
" unarrived of " + parties + " parties"); |
239 |
> |
/** |
240 |
> |
* Returns message string for bad bounds exceptions. |
241 |
> |
*/ |
242 |
> |
private static String badBounds(int parties, int unarrived) { |
243 |
> |
return ("Attempt to set " + unarrived + |
244 |
> |
" unarrived of " + parties + " parties"); |
245 |
|
} |
246 |
|
|
247 |
|
/** |
258 |
|
// Wait queues |
259 |
|
|
260 |
|
/** |
261 |
< |
* Heads of Treiber stacks waiting for nonFJ threads. To eliminate |
261 |
> |
* Heads of Treiber stacks for waiting threads. To eliminate |
262 |
|
* contention while releasing some threads while adding others, we |
263 |
|
* use two of them, alternating across even and odd phases. |
264 |
|
*/ |
302 |
|
|
303 |
|
/** |
304 |
|
* Creates a new Phaser without any initially registered parties, |
305 |
< |
* initial phase number 0, and no parent. |
305 |
> |
* initial phase number 0, and no parent. Any thread using this |
306 |
> |
* Phaser will need to first register for it. |
307 |
|
*/ |
308 |
|
public Phaser() { |
309 |
|
this(null); |
312 |
|
/** |
313 |
|
* Creates a new Phaser with the given numbers of registered |
314 |
|
* unarrived parties, initial phase number 0, and no parent. |
315 |
< |
* @param parties the number of parties required to trip barrier. |
315 |
> |
* |
316 |
> |
* @param parties the number of parties required to trip barrier |
317 |
|
* @throws IllegalArgumentException if parties less than zero |
318 |
< |
* or greater than the maximum number of parties supported. |
318 |
> |
* or greater than the maximum number of parties supported |
319 |
|
*/ |
320 |
|
public Phaser(int parties) { |
321 |
|
this(null, parties); |
326 |
|
* initially registered parties. If parent is non-null this phaser |
327 |
|
* is registered with the parent and its initial phase number is |
328 |
|
* the same as that of parent phaser. |
329 |
< |
* @param parent the parent phaser. |
329 |
> |
* |
330 |
> |
* @param parent the parent phaser |
331 |
|
*/ |
332 |
|
public Phaser(Phaser parent) { |
333 |
|
int phase = 0; |
343 |
|
|
344 |
|
/** |
345 |
|
* Creates a new Phaser with the given parent and numbers of |
346 |
< |
* registered unarrived parties. If parent is non-null this phaser |
346 |
> |
* registered unarrived parties. If parent is non-null, this phaser |
347 |
|
* is registered with the parent and its initial phase number is |
348 |
|
* the same as that of parent phaser. |
349 |
< |
* @param parent the parent phaser. |
350 |
< |
* @param parties the number of parties required to trip barrier. |
349 |
> |
* |
350 |
> |
* @param parent the parent phaser |
351 |
> |
* @param parties the number of parties required to trip barrier |
352 |
|
* @throws IllegalArgumentException if parties less than zero |
353 |
< |
* or greater than the maximum number of parties supported. |
353 |
> |
* or greater than the maximum number of parties supported |
354 |
|
*/ |
355 |
|
public Phaser(Phaser parent, int parties) { |
356 |
|
if (parties < 0 || parties > ushortMask) |
368 |
|
|
369 |
|
/** |
370 |
|
* Adds a new unarrived party to this phaser. |
371 |
+ |
* |
372 |
|
* @return the current barrier phase number upon registration |
373 |
|
* @throws IllegalStateException if attempting to register more |
374 |
< |
* than the maximum supported number of parties. |
374 |
> |
* than the maximum supported number of parties |
375 |
|
*/ |
376 |
|
public int register() { |
377 |
|
return doRegister(1); |
379 |
|
|
380 |
|
/** |
381 |
|
* Adds the given number of new unarrived parties to this phaser. |
382 |
< |
* @param parties the number of parties required to trip barrier. |
382 |
> |
* |
383 |
> |
* @param parties the number of parties required to trip barrier |
384 |
|
* @return the current barrier phase number upon registration |
385 |
|
* @throws IllegalStateException if attempting to register more |
386 |
< |
* than the maximum supported number of parties. |
386 |
> |
* than the maximum supported number of parties |
387 |
|
*/ |
388 |
|
public int bulkRegister(int parties) { |
389 |
|
if (parties < 0) |
406 |
|
if (phase < 0) |
407 |
|
break; |
408 |
|
if (parties > ushortMask || unarrived > ushortMask) |
409 |
< |
throw badBounds(parties, unarrived); |
409 |
> |
throw new IllegalStateException(badBounds(parties, unarrived)); |
410 |
|
if (phase == phaseOf(root.state) && |
411 |
|
casState(s, stateFor(phase, parties, unarrived))) |
412 |
|
break; |
419 |
|
* in turn wait for others via {@link #awaitAdvance}). |
420 |
|
* |
421 |
|
* @return the barrier phase number upon entry to this method, or a |
422 |
< |
* negative value if terminated; |
422 |
> |
* negative value if terminated |
423 |
|
* @throws IllegalStateException if not terminated and the number |
424 |
< |
* of unarrived parties would become negative. |
424 |
> |
* of unarrived parties would become negative |
425 |
|
*/ |
426 |
|
public int arrive() { |
427 |
|
int phase; |
428 |
|
for (;;) { |
429 |
|
long s = state; |
430 |
|
phase = phaseOf(s); |
431 |
+ |
if (phase < 0) |
432 |
+ |
break; |
433 |
|
int parties = partiesOf(s); |
434 |
|
int unarrived = unarrivedOf(s) - 1; |
435 |
|
if (unarrived > 0) { // Not the last arrival |
455 |
|
} |
456 |
|
} |
457 |
|
} |
443 |
– |
else if (phase < 0) // Don't throw exception if terminated |
444 |
– |
break; |
458 |
|
else if (phase != phaseOf(root.state)) // or if unreconciled |
459 |
|
reconcileState(); |
460 |
|
else |
461 |
< |
throw badBounds(parties, unarrived); |
461 |
> |
throw new IllegalStateException(badBounds(parties, unarrived)); |
462 |
|
} |
463 |
|
return phase; |
464 |
|
} |
471 |
|
* zero parties, this phaser is also deregistered from its parent. |
472 |
|
* |
473 |
|
* @return the current barrier phase number upon entry to |
474 |
< |
* this method, or a negative value if terminated; |
474 |
> |
* this method, or a negative value if terminated |
475 |
|
* @throws IllegalStateException if not terminated and the number |
476 |
< |
* of registered or unarrived parties would become negative. |
476 |
> |
* of registered or unarrived parties would become negative |
477 |
|
*/ |
478 |
|
public int arriveAndDeregister() { |
479 |
|
// similar code to arrive, but too different to merge |
482 |
|
for (;;) { |
483 |
|
long s = state; |
484 |
|
phase = phaseOf(s); |
485 |
+ |
if (phase < 0) |
486 |
+ |
break; |
487 |
|
int parties = partiesOf(s) - 1; |
488 |
|
int unarrived = unarrivedOf(s) - 1; |
489 |
|
if (parties >= 0) { |
509 |
|
} |
510 |
|
continue; |
511 |
|
} |
497 |
– |
if (phase < 0) |
498 |
– |
break; |
512 |
|
if (par != null && phase != phaseOf(root.state)) { |
513 |
|
reconcileState(); |
514 |
|
continue; |
515 |
|
} |
516 |
|
} |
517 |
< |
throw badBounds(parties, unarrived); |
517 |
> |
throw new IllegalStateException(badBounds(parties, unarrived)); |
518 |
|
} |
519 |
|
return phase; |
520 |
|
} |
524 |
|
* to {@code awaitAdvance(arrive())}. If you instead need to |
525 |
|
* await with interruption of timeout, and/or deregister upon |
526 |
|
* arrival, you can arrange them using analogous constructions. |
527 |
+ |
* |
528 |
|
* @return the phase on entry to this method |
529 |
|
* @throws IllegalStateException if not terminated and the number |
530 |
< |
* of unarrived parties would become negative. |
530 |
> |
* of unarrived parties would become negative |
531 |
|
*/ |
532 |
|
public int arriveAndAwaitAdvance() { |
533 |
|
return awaitAdvance(arrive()); |
537 |
|
* Awaits the phase of the barrier to advance from the given |
538 |
|
* value, or returns immediately if argument is negative or this |
539 |
|
* barrier is terminated. |
540 |
+ |
* |
541 |
|
* @param phase the phase on entry to this method |
542 |
|
* @return the phase on exit from this method |
543 |
|
*/ |
548 |
|
int p = phaseOf(s); |
549 |
|
if (p != phase) |
550 |
|
return p; |
551 |
< |
if (unarrivedOf(s) == 0) |
551 |
> |
if (unarrivedOf(s) == 0 && parent != null) |
552 |
|
parent.awaitAdvance(phase); |
553 |
|
// Fall here even if parent waited, to reconcile and help release |
554 |
|
return untimedWait(phase); |
559 |
|
* value, or returns immediately if argument is negative or this |
560 |
|
* barrier is terminated, or throws InterruptedException if |
561 |
|
* interrupted while waiting. |
562 |
+ |
* |
563 |
|
* @param phase the phase on entry to this method |
564 |
|
* @return the phase on exit from this method |
565 |
|
* @throws InterruptedException if thread interrupted while waiting |
566 |
|
*/ |
567 |
< |
public int awaitAdvanceInterruptibly(int phase) throws InterruptedException { |
567 |
> |
public int awaitAdvanceInterruptibly(int phase) |
568 |
> |
throws InterruptedException { |
569 |
|
if (phase < 0) |
570 |
|
return phase; |
571 |
|
long s = getReconciledState(); |
572 |
|
int p = phaseOf(s); |
573 |
|
if (p != phase) |
574 |
|
return p; |
575 |
< |
if (unarrivedOf(s) != 0) |
575 |
> |
if (unarrivedOf(s) == 0 && parent != null) |
576 |
|
parent.awaitAdvanceInterruptibly(phase); |
577 |
|
return interruptibleWait(phase); |
578 |
|
} |
581 |
|
* Awaits the phase of the barrier to advance from the given value |
582 |
|
* or the given timeout elapses, or returns immediately if |
583 |
|
* argument is negative or this barrier is terminated. |
584 |
+ |
* |
585 |
|
* @param phase the phase on entry to this method |
586 |
|
* @return the phase on exit from this method |
587 |
|
* @throws InterruptedException if thread interrupted while waiting |
595 |
|
int p = phaseOf(s); |
596 |
|
if (p != phase) |
597 |
|
return p; |
598 |
< |
if (unarrivedOf(s) == 0) |
598 |
> |
if (unarrivedOf(s) == 0 && parent != null) |
599 |
|
parent.awaitAdvanceInterruptibly(phase, timeout, unit); |
600 |
|
return timedWait(phase, unit.toNanos(timeout)); |
601 |
|
} |
628 |
|
* Returns the current phase number. The maximum phase number is |
629 |
|
* {@code Integer.MAX_VALUE}, after which it restarts at |
630 |
|
* zero. Upon termination, the phase number is negative. |
631 |
+ |
* |
632 |
|
* @return the phase number, or a negative value if terminated |
633 |
|
*/ |
634 |
|
public final int getPhase() { |
636 |
|
} |
637 |
|
|
638 |
|
/** |
639 |
< |
* Returns true if the current phase number equals the given phase. |
639 |
> |
* Returns {@code true} if the current phase number equals the given phase. |
640 |
> |
* |
641 |
|
* @param phase the phase |
642 |
< |
* @return true if the current phase number equals the given phase. |
642 |
> |
* @return {@code true} if the current phase number equals the given phase |
643 |
|
*/ |
644 |
|
public final boolean hasPhase(int phase) { |
645 |
|
return phaseOf(getReconciledState()) == phase; |
647 |
|
|
648 |
|
/** |
649 |
|
* Returns the number of parties registered at this barrier. |
650 |
+ |
* |
651 |
|
* @return the number of parties |
652 |
|
*/ |
653 |
|
public int getRegisteredParties() { |
657 |
|
/** |
658 |
|
* Returns the number of parties that have arrived at the current |
659 |
|
* phase of this barrier. |
660 |
+ |
* |
661 |
|
* @return the number of arrived parties |
662 |
|
*/ |
663 |
|
public int getArrivedParties() { |
667 |
|
/** |
668 |
|
* Returns the number of registered parties that have not yet |
669 |
|
* arrived at the current phase of this barrier. |
670 |
+ |
* |
671 |
|
* @return the number of unarrived parties |
672 |
|
*/ |
673 |
|
public int getUnarrivedParties() { |
676 |
|
|
677 |
|
/** |
678 |
|
* Returns the parent of this phaser, or null if none. |
679 |
< |
* @return the parent of this phaser, or null if none. |
679 |
> |
* |
680 |
> |
* @return the parent of this phaser, or null if none |
681 |
|
*/ |
682 |
|
public Phaser getParent() { |
683 |
|
return parent; |
686 |
|
/** |
687 |
|
* Returns the root ancestor of this phaser, which is the same as |
688 |
|
* this phaser if it has no parent. |
689 |
< |
* @return the root ancestor of this phaser. |
689 |
> |
* |
690 |
> |
* @return the root ancestor of this phaser |
691 |
|
*/ |
692 |
|
public Phaser getRoot() { |
693 |
|
return root; |
694 |
|
} |
695 |
|
|
696 |
|
/** |
697 |
< |
* Returns true if this barrier has been terminated. |
698 |
< |
* @return true if this barrier has been terminated |
697 |
> |
* Returns {@code true} if this barrier has been terminated. |
698 |
> |
* |
699 |
> |
* @return {@code true} if this barrier has been terminated |
700 |
|
*/ |
701 |
|
public boolean isTerminated() { |
702 |
|
return getPhase() < 0; |
728 |
|
* method. |
729 |
|
* |
730 |
|
* @param phase the phase number on entering the barrier |
731 |
< |
* @param registeredParties the current number of registered |
732 |
< |
* parties. |
707 |
< |
* @return true if this barrier should terminate |
731 |
> |
* @param registeredParties the current number of registered parties |
732 |
> |
* @return {@code true} if this barrier should terminate |
733 |
|
*/ |
734 |
|
protected boolean onAdvance(int phase, int registeredParties) { |
735 |
|
return registeredParties <= 0; |
738 |
|
/** |
739 |
|
* Returns a string identifying this phaser, as well as its |
740 |
|
* state. The state, in brackets, includes the String {@code |
741 |
< |
* "phase ="} followed by the phase number, {@code "parties ="} |
741 |
> |
* "phase = "} followed by the phase number, {@code "parties = "} |
742 |
|
* followed by the number of registered parties, and {@code |
743 |
< |
* "arrived ="} followed by the number of arrived parties |
743 |
> |
* "arrived = "} followed by the number of arrived parties. |
744 |
|
* |
745 |
|
* @return a string identifying this barrier, as well as its state |
746 |
|
*/ |
747 |
|
public String toString() { |
748 |
|
long s = getReconciledState(); |
749 |
< |
return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]"; |
749 |
> |
return super.toString() + |
750 |
> |
"[phase = " + phaseOf(s) + |
751 |
> |
" parties = " + partiesOf(s) + |
752 |
> |
" arrived = " + arrivedOf(s) + "]"; |
753 |
|
} |
754 |
|
|
755 |
|
// methods for waiting |
756 |
|
|
729 |
– |
/** The number of CPUs, for spin control */ |
730 |
– |
static final int NCPUS = Runtime.getRuntime().availableProcessors(); |
731 |
– |
|
757 |
|
/** |
758 |
< |
* The number of times to spin before blocking in timed waits. |
734 |
< |
* The value is empirically derived. |
758 |
> |
* Wait nodes for Treiber stack representing wait queue |
759 |
|
*/ |
760 |
< |
static final int maxTimedSpins = (NCPUS < 2)? 0 : 32; |
761 |
< |
|
762 |
< |
/** |
763 |
< |
* The number of times to spin before blocking in untimed waits. |
764 |
< |
* This is greater than timed value because untimed waits spin |
765 |
< |
* faster since they don't need to check times on each spin. |
766 |
< |
*/ |
767 |
< |
static final int maxUntimedSpins = maxTimedSpins * 32; |
744 |
< |
|
745 |
< |
/** |
746 |
< |
* The number of nanoseconds for which it is faster to spin |
747 |
< |
* rather than to use timed park. A rough estimate suffices. |
748 |
< |
*/ |
749 |
< |
static final long spinForTimeoutThreshold = 1000L; |
750 |
< |
|
751 |
< |
/** |
752 |
< |
* Wait nodes for Treiber stack representing wait queue for non-FJ |
753 |
< |
* tasks. |
754 |
< |
*/ |
755 |
< |
static final class QNode { |
756 |
< |
QNode next; |
760 |
> |
static final class QNode implements ForkJoinPool.ManagedBlocker { |
761 |
> |
final Phaser phaser; |
762 |
> |
final int phase; |
763 |
> |
final long startTime; |
764 |
> |
final long nanos; |
765 |
> |
final boolean timed; |
766 |
> |
final boolean interruptible; |
767 |
> |
volatile boolean wasInterrupted = false; |
768 |
|
volatile Thread thread; // nulled to cancel wait |
769 |
< |
QNode() { |
769 |
> |
QNode next; |
770 |
> |
QNode(Phaser phaser, int phase, boolean interruptible, |
771 |
> |
boolean timed, long startTime, long nanos) { |
772 |
> |
this.phaser = phaser; |
773 |
> |
this.phase = phase; |
774 |
> |
this.timed = timed; |
775 |
> |
this.interruptible = interruptible; |
776 |
> |
this.startTime = startTime; |
777 |
> |
this.nanos = nanos; |
778 |
|
thread = Thread.currentThread(); |
779 |
|
} |
780 |
+ |
public boolean isReleasable() { |
781 |
+ |
return (thread == null || |
782 |
+ |
phaser.getPhase() != phase || |
783 |
+ |
(interruptible && wasInterrupted) || |
784 |
+ |
(timed && (nanos - (System.nanoTime() - startTime)) <= 0)); |
785 |
+ |
} |
786 |
+ |
public boolean block() { |
787 |
+ |
if (Thread.interrupted()) { |
788 |
+ |
wasInterrupted = true; |
789 |
+ |
if (interruptible) |
790 |
+ |
return true; |
791 |
+ |
} |
792 |
+ |
if (!timed) |
793 |
+ |
LockSupport.park(this); |
794 |
+ |
else { |
795 |
+ |
long waitTime = nanos - (System.nanoTime() - startTime); |
796 |
+ |
if (waitTime <= 0) |
797 |
+ |
return true; |
798 |
+ |
LockSupport.parkNanos(this, waitTime); |
799 |
+ |
} |
800 |
+ |
return isReleasable(); |
801 |
+ |
} |
802 |
|
void signal() { |
803 |
|
Thread t = thread; |
804 |
|
if (t != null) { |
806 |
|
LockSupport.unpark(t); |
807 |
|
} |
808 |
|
} |
809 |
+ |
boolean doWait() { |
810 |
+ |
if (thread != null) { |
811 |
+ |
try { |
812 |
+ |
ForkJoinPool.managedBlock(this, false); |
813 |
+ |
} catch (InterruptedException ie) { |
814 |
+ |
} |
815 |
+ |
} |
816 |
+ |
return wasInterrupted; |
817 |
+ |
} |
818 |
+ |
|
819 |
|
} |
820 |
|
|
821 |
|
/** |
822 |
< |
* Removes and signals waiting threads from wait queue |
822 |
> |
* Removes and signals waiting threads from wait queue. |
823 |
|
*/ |
824 |
|
private void releaseWaiters(int phase) { |
825 |
|
AtomicReference<QNode> head = queueFor(phase); |
831 |
|
} |
832 |
|
|
833 |
|
/** |
834 |
+ |
* Tries to enqueue given node in the appropriate wait queue. |
835 |
+ |
* |
836 |
+ |
* @return true if successful |
837 |
+ |
*/ |
838 |
+ |
private boolean tryEnqueue(QNode node) { |
839 |
+ |
AtomicReference<QNode> head = queueFor(node.phase); |
840 |
+ |
return head.compareAndSet(node.next = head.get(), node); |
841 |
+ |
} |
842 |
+ |
|
843 |
+ |
/** |
844 |
|
* Enqueues node and waits unless aborted or signalled. |
845 |
+ |
* |
846 |
+ |
* @return current phase |
847 |
|
*/ |
848 |
|
private int untimedWait(int phase) { |
786 |
– |
int spins = maxUntimedSpins; |
849 |
|
QNode node = null; |
788 |
– |
boolean interrupted = false; |
850 |
|
boolean queued = false; |
851 |
+ |
boolean interrupted = false; |
852 |
|
int p; |
853 |
|
while ((p = getPhase()) == phase) { |
854 |
< |
interrupted = Thread.interrupted(); |
855 |
< |
if (node != null) { |
856 |
< |
if (!queued) { |
857 |
< |
AtomicReference<QNode> head = queueFor(phase); |
858 |
< |
queued = head.compareAndSet(node.next = head.get(), node); |
859 |
< |
} |
798 |
< |
else if (node.thread != null) |
799 |
< |
LockSupport.park(this); |
800 |
< |
} |
801 |
< |
else if (spins <= 0) |
802 |
< |
node = new QNode(); |
854 |
> |
if (Thread.interrupted()) |
855 |
> |
interrupted = true; |
856 |
> |
else if (node == null) |
857 |
> |
node = new QNode(this, phase, false, false, 0, 0); |
858 |
> |
else if (!queued) |
859 |
> |
queued = tryEnqueue(node); |
860 |
|
else |
861 |
< |
--spins; |
861 |
> |
interrupted = node.doWait(); |
862 |
|
} |
863 |
|
if (node != null) |
864 |
|
node.thread = null; |
865 |
+ |
releaseWaiters(phase); |
866 |
|
if (interrupted) |
867 |
|
Thread.currentThread().interrupt(); |
810 |
– |
releaseWaiters(phase); |
868 |
|
return p; |
869 |
|
} |
870 |
|
|
871 |
|
/** |
872 |
< |
* Messier interruptible version |
872 |
> |
* Interruptible version |
873 |
> |
* @return current phase |
874 |
|
*/ |
875 |
|
private int interruptibleWait(int phase) throws InterruptedException { |
818 |
– |
int spins = maxUntimedSpins; |
876 |
|
QNode node = null; |
877 |
|
boolean queued = false; |
878 |
|
boolean interrupted = false; |
879 |
|
int p; |
880 |
< |
while ((p = getPhase()) == phase) { |
881 |
< |
if (interrupted = Thread.interrupted()) |
882 |
< |
break; |
883 |
< |
if (node != null) { |
884 |
< |
if (!queued) { |
885 |
< |
AtomicReference<QNode> head = queueFor(phase); |
886 |
< |
queued = head.compareAndSet(node.next = head.get(), node); |
830 |
< |
} |
831 |
< |
else if (node.thread != null) |
832 |
< |
LockSupport.park(this); |
833 |
< |
} |
834 |
< |
else if (spins <= 0) |
835 |
< |
node = new QNode(); |
880 |
> |
while ((p = getPhase()) == phase && !interrupted) { |
881 |
> |
if (Thread.interrupted()) |
882 |
> |
interrupted = true; |
883 |
> |
else if (node == null) |
884 |
> |
node = new QNode(this, phase, true, false, 0, 0); |
885 |
> |
else if (!queued) |
886 |
> |
queued = tryEnqueue(node); |
887 |
|
else |
888 |
< |
--spins; |
888 |
> |
interrupted = node.doWait(); |
889 |
|
} |
890 |
|
if (node != null) |
891 |
|
node.thread = null; |
892 |
+ |
if (p != phase || (p = getPhase()) != phase) |
893 |
+ |
releaseWaiters(phase); |
894 |
|
if (interrupted) |
895 |
|
throw new InterruptedException(); |
843 |
– |
releaseWaiters(phase); |
896 |
|
return p; |
897 |
|
} |
898 |
|
|
899 |
|
/** |
900 |
< |
* Even messier timeout version. |
900 |
> |
* Timeout version. |
901 |
> |
* @return current phase |
902 |
|
*/ |
903 |
|
private int timedWait(int phase, long nanos) |
904 |
|
throws InterruptedException, TimeoutException { |
905 |
+ |
long startTime = System.nanoTime(); |
906 |
+ |
QNode node = null; |
907 |
+ |
boolean queued = false; |
908 |
+ |
boolean interrupted = false; |
909 |
|
int p; |
910 |
< |
if ((p = getPhase()) == phase) { |
911 |
< |
long lastTime = System.nanoTime(); |
912 |
< |
int spins = maxTimedSpins; |
913 |
< |
QNode node = null; |
914 |
< |
boolean queued = false; |
915 |
< |
boolean interrupted = false; |
916 |
< |
while ((p = getPhase()) == phase) { |
917 |
< |
if (interrupted = Thread.interrupted()) |
918 |
< |
break; |
919 |
< |
long now = System.nanoTime(); |
920 |
< |
if ((nanos -= now - lastTime) <= 0) |
864 |
< |
break; |
865 |
< |
lastTime = now; |
866 |
< |
if (node != null) { |
867 |
< |
if (!queued) { |
868 |
< |
AtomicReference<QNode> head = queueFor(phase); |
869 |
< |
queued = head.compareAndSet(node.next = head.get(), node); |
870 |
< |
} |
871 |
< |
else if (node.thread != null && |
872 |
< |
nanos > spinForTimeoutThreshold) { |
873 |
< |
LockSupport.parkNanos(this, nanos); |
874 |
< |
} |
875 |
< |
} |
876 |
< |
else if (spins <= 0) |
877 |
< |
node = new QNode(); |
878 |
< |
else |
879 |
< |
--spins; |
880 |
< |
} |
881 |
< |
if (node != null) |
882 |
< |
node.thread = null; |
883 |
< |
if (interrupted) |
884 |
< |
throw new InterruptedException(); |
885 |
< |
if (p == phase && (p = getPhase()) == phase) |
886 |
< |
throw new TimeoutException(); |
910 |
> |
while ((p = getPhase()) == phase && !interrupted) { |
911 |
> |
if (Thread.interrupted()) |
912 |
> |
interrupted = true; |
913 |
> |
else if (nanos - (System.nanoTime() - startTime) <= 0) |
914 |
> |
break; |
915 |
> |
else if (node == null) |
916 |
> |
node = new QNode(this, phase, true, true, startTime, nanos); |
917 |
> |
else if (!queued) |
918 |
> |
queued = tryEnqueue(node); |
919 |
> |
else |
920 |
> |
interrupted = node.doWait(); |
921 |
|
} |
922 |
< |
releaseWaiters(phase); |
922 |
> |
if (node != null) |
923 |
> |
node.thread = null; |
924 |
> |
if (p != phase || (p = getPhase()) != phase) |
925 |
> |
releaseWaiters(phase); |
926 |
> |
if (interrupted) |
927 |
> |
throw new InterruptedException(); |
928 |
> |
if (p == phase) |
929 |
> |
throw new TimeoutException(); |
930 |
|
return p; |
931 |
|
} |
932 |
|
|
933 |
|
// Temporary Unsafe mechanics for preliminary release |
934 |
+ |
private static Unsafe getUnsafe() throws Throwable { |
935 |
+ |
try { |
936 |
+ |
return Unsafe.getUnsafe(); |
937 |
+ |
} catch (SecurityException se) { |
938 |
+ |
try { |
939 |
+ |
return java.security.AccessController.doPrivileged |
940 |
+ |
(new java.security.PrivilegedExceptionAction<Unsafe>() { |
941 |
+ |
public Unsafe run() throws Exception { |
942 |
+ |
return getUnsafePrivileged(); |
943 |
+ |
}}); |
944 |
+ |
} catch (java.security.PrivilegedActionException e) { |
945 |
+ |
throw e.getCause(); |
946 |
+ |
} |
947 |
+ |
} |
948 |
+ |
} |
949 |
|
|
950 |
< |
static final Unsafe _unsafe; |
950 |
> |
private static Unsafe getUnsafePrivileged() |
951 |
> |
throws NoSuchFieldException, IllegalAccessException { |
952 |
> |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
953 |
> |
f.setAccessible(true); |
954 |
> |
return (Unsafe) f.get(null); |
955 |
> |
} |
956 |
> |
|
957 |
> |
private static long fieldOffset(String fieldName) |
958 |
> |
throws NoSuchFieldException { |
959 |
> |
return UNSAFE.objectFieldOffset |
960 |
> |
(Phaser.class.getDeclaredField(fieldName)); |
961 |
> |
} |
962 |
> |
|
963 |
> |
static final Unsafe UNSAFE; |
964 |
|
static final long stateOffset; |
965 |
|
|
966 |
|
static { |
967 |
|
try { |
968 |
< |
if (Phaser.class.getClassLoader() != null) { |
969 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
970 |
< |
f.setAccessible(true); |
902 |
< |
_unsafe = (Unsafe)f.get(null); |
903 |
< |
} |
904 |
< |
else |
905 |
< |
_unsafe = Unsafe.getUnsafe(); |
906 |
< |
stateOffset = _unsafe.objectFieldOffset |
907 |
< |
(Phaser.class.getDeclaredField("state")); |
908 |
< |
} catch (Exception e) { |
968 |
> |
UNSAFE = getUnsafe(); |
969 |
> |
stateOffset = fieldOffset("state"); |
970 |
> |
} catch (Throwable e) { |
971 |
|
throw new RuntimeException("Could not initialize intrinsics", e); |
972 |
|
} |
973 |
|
} |
974 |
|
|
975 |
|
final boolean casState(long cmp, long val) { |
976 |
< |
return _unsafe.compareAndSwapLong(this, stateOffset, cmp, val); |
976 |
> |
return UNSAFE.compareAndSwapLong(this, stateOffset, cmp, val); |
977 |
|
} |
978 |
|
} |