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