1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.concurrent.TimeUnit; |
10 |
import java.util.concurrent.TimeoutException; |
11 |
import java.util.concurrent.atomic.AtomicReference; |
12 |
import java.util.concurrent.locks.LockSupport; |
13 |
|
14 |
/** |
15 |
* A reusable synchronization barrier, similar in functionality to |
16 |
* {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and |
17 |
* {@link java.util.concurrent.CountDownLatch CountDownLatch} |
18 |
* but supporting more flexible usage. |
19 |
* |
20 |
* <p> <b>Registration.</b> Unlike the case for other barriers, the |
21 |
* number of parties <em>registered</em> to synchronize on a phaser |
22 |
* may vary over time. Tasks may be registered at any time (using |
23 |
* methods {@link #register}, {@link #bulkRegister}, or forms of |
24 |
* constructors establishing initial numbers of parties), and |
25 |
* optionally deregistered upon any arrival (using {@link |
26 |
* #arriveAndDeregister}). As is the case with most basic |
27 |
* synchronization constructs, registration and deregistration affect |
28 |
* only internal counts; they do not establish any further internal |
29 |
* bookkeeping, so tasks cannot query whether they are registered. |
30 |
* (However, you can introduce such bookkeeping by subclassing this |
31 |
* class.) |
32 |
* |
33 |
* <p> <b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code |
34 |
* Phaser} may be repeatedly awaited. Method {@link |
35 |
* #arriveAndAwaitAdvance} has effect analogous to {@link |
36 |
* java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each |
37 |
* generation of a phaser has an associated phase number. The phase |
38 |
* number starts at zero, and advances when all parties arrive at the |
39 |
* phaser, wrapping around to zero after reaching {@code |
40 |
* Integer.MAX_VALUE}. The use of phase numbers enables independent |
41 |
* control of actions upon arrival at a phaser and upon awaiting |
42 |
* others, via two kinds of methods that may be invoked by any |
43 |
* registered party: |
44 |
* |
45 |
* <ul> |
46 |
* |
47 |
* <li> <b>Arrival.</b> Methods {@link #arrive} and |
48 |
* {@link #arriveAndDeregister} record arrival. These methods |
49 |
* do not block, but return an associated <em>arrival phase |
50 |
* number</em>; that is, the phase number of the phaser to which |
51 |
* the arrival applied. When the final party for a given phase |
52 |
* arrives, an optional action is performed and the phase |
53 |
* advances. These actions are performed by the party |
54 |
* triggering a phase advance, and are arranged by overriding |
55 |
* method {@link #onAdvance(int, int)}, which also controls |
56 |
* termination. Overriding this method is similar to, but more |
57 |
* flexible than, providing a barrier action to a {@code |
58 |
* CyclicBarrier}. |
59 |
* |
60 |
* <li> <b>Waiting.</b> Method {@link #awaitAdvance} requires an |
61 |
* argument indicating an arrival phase number, and returns when |
62 |
* the phaser advances to (or is already at) a different phase. |
63 |
* Unlike similar constructions using {@code CyclicBarrier}, |
64 |
* method {@code awaitAdvance} continues to wait even if the |
65 |
* waiting thread is interrupted. Interruptible and timeout |
66 |
* versions are also available, but exceptions encountered while |
67 |
* tasks wait interruptibly or with timeout do not change the |
68 |
* state of the phaser. If necessary, you can perform any |
69 |
* associated recovery within handlers of those exceptions, |
70 |
* often after invoking {@code forceTermination}. Phasers may |
71 |
* also be used by tasks executing in a {@link ForkJoinPool}, |
72 |
* which will ensure sufficient parallelism to execute tasks |
73 |
* when others are blocked waiting for a phase to advance. |
74 |
* |
75 |
* </ul> |
76 |
* |
77 |
* <p> <b>Termination.</b> A phaser may enter a <em>termination</em> |
78 |
* state in which all synchronization methods immediately return |
79 |
* without updating phaser state or waiting for advance, and |
80 |
* indicating (via a negative phase value) that execution is complete. |
81 |
* Termination is triggered when an invocation of {@code onAdvance} |
82 |
* returns {@code true}. The default implementation returns {@code |
83 |
* true} if a deregistration has caused the number of registered |
84 |
* parties to become zero. As illustrated below, when phasers control |
85 |
* actions with a fixed number of iterations, it is often convenient |
86 |
* to override this method to cause termination when the current phase |
87 |
* number reaches a threshold. Method {@link #forceTermination} is |
88 |
* also available to abruptly release waiting threads and allow them |
89 |
* to terminate. |
90 |
* |
91 |
* <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e., |
92 |
* constructed in tree structures) to reduce contention. Phasers with |
93 |
* large numbers of parties that would otherwise experience heavy |
94 |
* synchronization contention costs may instead be set up so that |
95 |
* groups of sub-phasers share a common parent. This may greatly |
96 |
* increase throughput even though it incurs greater per-operation |
97 |
* overhead. |
98 |
* |
99 |
* <p>In a tree of tiered phasers, registration and deregistration of |
100 |
* child phasers with their parent are managed automatically. |
101 |
* Whenever the number of registered parties of a child phaser becomes |
102 |
* non-zero (as established in the {@link #Phaser(Phaser,int)} |
103 |
* constructor, {@link #register}, or {@link #bulkRegister}), this |
104 |
* child phaser is registered with its parent. Whenever the number of |
105 |
* registered parties becomes zero as the result of an invocation of |
106 |
* {@link #arriveAndDeregister}, this child phaser is deregistered |
107 |
* from its parent. |
108 |
* |
109 |
* <p><b>Monitoring.</b> While synchronization methods may be invoked |
110 |
* only by registered parties, the current state of a phaser may be |
111 |
* monitored by any caller. At any given moment there are {@link |
112 |
* #getRegisteredParties} parties in total, of which {@link |
113 |
* #getArrivedParties} have arrived at the current phase ({@link |
114 |
* #getPhase}). When the remaining ({@link #getUnarrivedParties}) |
115 |
* parties arrive, the phase advances. The values returned by these |
116 |
* methods may reflect transient states and so are not in general |
117 |
* useful for synchronization control. Method {@link #toString} |
118 |
* returns snapshots of these state queries in a form convenient for |
119 |
* informal monitoring. |
120 |
* |
121 |
* <p><b>Sample usages:</b> |
122 |
* |
123 |
* <p>A {@code Phaser} may be used instead of a {@code CountDownLatch} |
124 |
* to control a one-shot action serving a variable number of parties. |
125 |
* The typical idiom is for the method setting this up to first |
126 |
* register, then start the actions, then deregister, as in: |
127 |
* |
128 |
* <pre> {@code |
129 |
* void runTasks(List<Runnable> tasks) { |
130 |
* final Phaser phaser = new Phaser(1); // "1" to register self |
131 |
* // create and start threads |
132 |
* for (Runnable task : tasks) { |
133 |
* phaser.register(); |
134 |
* new Thread() { |
135 |
* public void run() { |
136 |
* phaser.arriveAndAwaitAdvance(); // await all creation |
137 |
* task.run(); |
138 |
* } |
139 |
* }.start(); |
140 |
* } |
141 |
* |
142 |
* // allow threads to start and deregister self |
143 |
* phaser.arriveAndDeregister(); |
144 |
* }}</pre> |
145 |
* |
146 |
* <p>One way to cause a set of threads to repeatedly perform actions |
147 |
* for a given number of iterations is to override {@code onAdvance}: |
148 |
* |
149 |
* <pre> {@code |
150 |
* void startTasks(List<Runnable> tasks, final int iterations) { |
151 |
* final Phaser phaser = new Phaser() { |
152 |
* protected boolean onAdvance(int phase, int registeredParties) { |
153 |
* return phase >= iterations || registeredParties == 0; |
154 |
* } |
155 |
* }; |
156 |
* phaser.register(); |
157 |
* for (final Runnable task : tasks) { |
158 |
* phaser.register(); |
159 |
* new Thread() { |
160 |
* public void run() { |
161 |
* do { |
162 |
* task.run(); |
163 |
* phaser.arriveAndAwaitAdvance(); |
164 |
* } while (!phaser.isTerminated()); |
165 |
* } |
166 |
* }.start(); |
167 |
* } |
168 |
* phaser.arriveAndDeregister(); // deregister self, don't wait |
169 |
* }}</pre> |
170 |
* |
171 |
* If the main task must later await termination, it |
172 |
* may re-register and then execute a similar loop: |
173 |
* <pre> {@code |
174 |
* // ... |
175 |
* phaser.register(); |
176 |
* while (!phaser.isTerminated()) |
177 |
* phaser.arriveAndAwaitAdvance();}</pre> |
178 |
* |
179 |
* <p>Related constructions may be used to await particular phase numbers |
180 |
* in contexts where you are sure that the phase will never wrap around |
181 |
* {@code Integer.MAX_VALUE}. For example: |
182 |
* |
183 |
* <pre> {@code |
184 |
* void awaitPhase(Phaser phaser, int phase) { |
185 |
* int p = phaser.register(); // assumes caller not already registered |
186 |
* while (p < phase) { |
187 |
* if (phaser.isTerminated()) |
188 |
* // ... deal with unexpected termination |
189 |
* else |
190 |
* p = phaser.arriveAndAwaitAdvance(); |
191 |
* } |
192 |
* phaser.arriveAndDeregister(); |
193 |
* }}</pre> |
194 |
* |
195 |
* |
196 |
* <p>To create a set of {@code n} tasks using a tree of phasers, you |
197 |
* could use code of the following form, assuming a Task class with a |
198 |
* constructor accepting a {@code Phaser} that it registers with upon |
199 |
* construction. After invocation of {@code build(new Task[n], 0, n, |
200 |
* new Phaser())}, these tasks could then be started, for example by |
201 |
* submitting to a pool: |
202 |
* |
203 |
* <pre> {@code |
204 |
* void build(Task[] tasks, int lo, int hi, Phaser ph) { |
205 |
* if (hi - lo > TASKS_PER_PHASER) { |
206 |
* for (int i = lo; i < hi; i += TASKS_PER_PHASER) { |
207 |
* int j = Math.min(i + TASKS_PER_PHASER, hi); |
208 |
* build(tasks, i, j, new Phaser(ph)); |
209 |
* } |
210 |
* } else { |
211 |
* for (int i = lo; i < hi; ++i) |
212 |
* tasks[i] = new Task(ph); |
213 |
* // assumes new Task(ph) performs ph.register() |
214 |
* } |
215 |
* }}</pre> |
216 |
* |
217 |
* The best value of {@code TASKS_PER_PHASER} depends mainly on |
218 |
* expected synchronization rates. A value as low as four may |
219 |
* be appropriate for extremely small per-phase task bodies (thus |
220 |
* high rates), or up to hundreds for extremely large ones. |
221 |
* |
222 |
* <p><b>Implementation notes</b>: This implementation restricts the |
223 |
* maximum number of parties to 65535. Attempts to register additional |
224 |
* parties result in {@code IllegalStateException}. However, you can and |
225 |
* should create tiered phasers to accommodate arbitrarily large sets |
226 |
* of participants. |
227 |
* |
228 |
* @since 1.7 |
229 |
* @author Doug Lea |
230 |
*/ |
231 |
public class Phaser { |
232 |
/* |
233 |
* This class implements an extension of X10 "clocks". Thanks to |
234 |
* Vijay Saraswat for the idea, and to Vivek Sarkar for |
235 |
* enhancements to extend functionality. |
236 |
*/ |
237 |
|
238 |
/** |
239 |
* Primary state representation, holding four fields: |
240 |
* |
241 |
* * unarrived -- the number of parties yet to hit barrier (bits 0-15) |
242 |
* * parties -- the number of parties to wait (bits 16-31) |
243 |
* * phase -- the generation of the barrier (bits 32-62) |
244 |
* * terminated -- set if barrier is terminated (bit 63 / sign) |
245 |
* |
246 |
* Except that a phaser with no registered parties is |
247 |
* distinguished with the otherwise illegal state of having zero |
248 |
* parties and one unarrived parties (encoded as EMPTY below). |
249 |
* |
250 |
* To efficiently maintain atomicity, these values are packed into |
251 |
* a single (atomic) long. Good performance relies on keeping |
252 |
* state decoding and encoding simple, and keeping race windows |
253 |
* short. |
254 |
* |
255 |
* All state updates are performed via CAS except initial |
256 |
* registration of a sub-phaser (i.e., one with a non-null |
257 |
* parent). In this (relatively rare) case, we use built-in |
258 |
* synchronization to lock while first registering with its |
259 |
* parent. |
260 |
* |
261 |
* The phase of a subphaser is allowed to lag that of its |
262 |
* ancestors until it is actually accessed. Method reconcileState |
263 |
* is usually attempted only only when the number of unarrived |
264 |
* parties appears to be zero, which indicates a potential lag in |
265 |
* updating phase after the root advanced. |
266 |
*/ |
267 |
private volatile long state; |
268 |
|
269 |
private static final int MAX_PARTIES = 0xffff; |
270 |
private static final int MAX_PHASE = 0x7fffffff; |
271 |
private static final int PARTIES_SHIFT = 16; |
272 |
private static final int PHASE_SHIFT = 32; |
273 |
private static final int UNARRIVED_MASK = 0xffff; // to mask ints |
274 |
private static final long PARTIES_MASK = 0xffff0000L; // to mask longs |
275 |
private static final long TERMINATION_BIT = 1L << 63; |
276 |
|
277 |
// some special values |
278 |
private static final int ONE_ARRIVAL = 1; |
279 |
private static final int ONE_PARTY = 1 << PARTIES_SHIFT; |
280 |
private static final int EMPTY = 1; |
281 |
|
282 |
// The following unpacking methods are usually manually inlined |
283 |
|
284 |
private static int unarrivedOf(long s) { |
285 |
int counts = (int)s; |
286 |
return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK; |
287 |
} |
288 |
|
289 |
private static int partiesOf(long s) { |
290 |
return (int)s >>> PARTIES_SHIFT; |
291 |
} |
292 |
|
293 |
private static int phaseOf(long s) { |
294 |
return (int) (s >>> PHASE_SHIFT); |
295 |
} |
296 |
|
297 |
private static int arrivedOf(long s) { |
298 |
int counts = (int)s; |
299 |
return (counts == EMPTY) ? 0 : |
300 |
(counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK); |
301 |
} |
302 |
|
303 |
/** |
304 |
* The parent of this phaser, or null if none |
305 |
*/ |
306 |
private final Phaser parent; |
307 |
|
308 |
/** |
309 |
* The root of phaser tree. Equals this if not in a tree. |
310 |
*/ |
311 |
private final Phaser root; |
312 |
|
313 |
/** |
314 |
* Heads of Treiber stacks for waiting threads. To eliminate |
315 |
* contention when releasing some threads while adding others, we |
316 |
* use two of them, alternating across even and odd phases. |
317 |
* Subphasers share queues with root to speed up releases. |
318 |
*/ |
319 |
private final AtomicReference<QNode> evenQ; |
320 |
private final AtomicReference<QNode> oddQ; |
321 |
|
322 |
private AtomicReference<QNode> queueFor(int phase) { |
323 |
return ((phase & 1) == 0) ? evenQ : oddQ; |
324 |
} |
325 |
|
326 |
/** |
327 |
* Returns message string for bounds exceptions on arrival. |
328 |
*/ |
329 |
private String badArrive(long s) { |
330 |
return "Attempted arrival of unregistered party for " + |
331 |
stateToString(s); |
332 |
} |
333 |
|
334 |
/** |
335 |
* Returns message string for bounds exceptions on registration. |
336 |
*/ |
337 |
private String badRegister(long s) { |
338 |
return "Attempt to register more than " + |
339 |
MAX_PARTIES + " parties for " + stateToString(s); |
340 |
} |
341 |
|
342 |
/** |
343 |
* Main implementation for methods arrive and arriveAndDeregister. |
344 |
* Manually tuned to speed up and minimize race windows for the |
345 |
* common case of just decrementing unarrived field. |
346 |
* |
347 |
* @param deregister false for arrive, true for arriveAndDeregister |
348 |
*/ |
349 |
private int doArrive(boolean deregister) { |
350 |
int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL; |
351 |
long s; |
352 |
int phase; |
353 |
while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0) { |
354 |
int counts = (int)s; |
355 |
int unarrived = counts & UNARRIVED_MASK; |
356 |
if (counts == EMPTY || unarrived == 0) { |
357 |
if (reconcileState() == s) |
358 |
throw new IllegalStateException(badArrive(s)); |
359 |
} |
360 |
else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) { |
361 |
if (unarrived == 1) { |
362 |
long n = s & PARTIES_MASK; // unshifted parties field |
363 |
int u = ((int)n) >>> PARTIES_SHIFT; |
364 |
Phaser par = parent; |
365 |
if (par != null) { |
366 |
par.doArrive(u == 0); |
367 |
reconcileState(); |
368 |
} |
369 |
else { |
370 |
n |= (((long)((phase+1) & MAX_PHASE)) << PHASE_SHIFT); |
371 |
if (onAdvance(phase, u)) |
372 |
n |= TERMINATION_BIT; |
373 |
else if (u == 0) |
374 |
n |= EMPTY; // reset to unregistered |
375 |
else |
376 |
n |= (long)u; // reset unarr to parties |
377 |
// assert state == s || isTerminated(); |
378 |
UNSAFE.compareAndSwapLong(this, stateOffset, s, n); |
379 |
releaseWaiters(phase); |
380 |
} |
381 |
} |
382 |
break; |
383 |
} |
384 |
} |
385 |
return phase; |
386 |
} |
387 |
|
388 |
/** |
389 |
* Implementation of register, bulkRegister |
390 |
* |
391 |
* @param registrations number to add to both parties and |
392 |
* unarrived fields. Must be greater than zero. |
393 |
*/ |
394 |
private int doRegister(int registrations) { |
395 |
// adjustment to state |
396 |
long adj = ((long)registrations << PARTIES_SHIFT) | registrations; |
397 |
Phaser par = parent; |
398 |
int phase; |
399 |
for (;;) { |
400 |
long s = state; |
401 |
int counts = (int)s; |
402 |
int parties = counts >>> PARTIES_SHIFT; |
403 |
int unarrived = counts & UNARRIVED_MASK; |
404 |
if (registrations > MAX_PARTIES - parties) |
405 |
throw new IllegalStateException(badRegister(s)); |
406 |
else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0) |
407 |
break; |
408 |
else if (counts != EMPTY) { // not 1st registration |
409 |
if (par == null || reconcileState() == s) { |
410 |
if (unarrived == 0) // wait out advance |
411 |
root.internalAwaitAdvance(phase, null); |
412 |
else if (UNSAFE.compareAndSwapLong(this, stateOffset, |
413 |
s, s + adj)) |
414 |
break; |
415 |
} |
416 |
} |
417 |
else if (par == null) { // 1st root registration |
418 |
long next = (((long) phase) << PHASE_SHIFT) | adj; |
419 |
if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) |
420 |
break; |
421 |
} |
422 |
else { |
423 |
synchronized (this) { // 1st sub registration |
424 |
if (state == s) { // recheck under lock |
425 |
par.doRegister(1); |
426 |
do { // force current phase |
427 |
phase = (int)(root.state >>> PHASE_SHIFT); |
428 |
// assert phase < 0 || (int)state == EMPTY; |
429 |
} while (!UNSAFE.compareAndSwapLong |
430 |
(this, stateOffset, state, |
431 |
(((long) phase) << PHASE_SHIFT) | adj)); |
432 |
break; |
433 |
} |
434 |
} |
435 |
} |
436 |
} |
437 |
return phase; |
438 |
} |
439 |
|
440 |
/** |
441 |
* Resolves lagged phase propagation from root if necessary. |
442 |
*/ |
443 |
private long reconcileState() { |
444 |
Phaser rt = root; |
445 |
long s = state; |
446 |
if (rt != this) { |
447 |
int phase; |
448 |
while ((phase = (int)(rt.state >>> PHASE_SHIFT)) != |
449 |
(int)(s >>> PHASE_SHIFT)) { |
450 |
// assert phase < 0 || unarrivedOf(s) == 0 |
451 |
long t; // to reread s |
452 |
long p = s & PARTIES_MASK; // unshifted parties field |
453 |
long n = (((long) phase) << PHASE_SHIFT) | p; |
454 |
if (phase >= 0) { |
455 |
if (p == 0L) |
456 |
n |= EMPTY; // reset to empty |
457 |
else |
458 |
n |= p >>> PARTIES_SHIFT; // set unarr to parties |
459 |
} |
460 |
if ((t = state) == s && |
461 |
UNSAFE.compareAndSwapLong(this, stateOffset, s, s = n)) |
462 |
break; |
463 |
s = t; |
464 |
} |
465 |
} |
466 |
return s; |
467 |
} |
468 |
|
469 |
/** |
470 |
* Creates a new phaser with no initially registered parties, no |
471 |
* parent, and initial phase number 0. Any thread using this |
472 |
* phaser will need to first register for it. |
473 |
*/ |
474 |
public Phaser() { |
475 |
this(null, 0); |
476 |
} |
477 |
|
478 |
/** |
479 |
* Creates a new phaser with the given number of registered |
480 |
* unarrived parties, no parent, and initial phase number 0. |
481 |
* |
482 |
* @param parties the number of parties required to advance to the |
483 |
* next phase |
484 |
* @throws IllegalArgumentException if parties less than zero |
485 |
* or greater than the maximum number of parties supported |
486 |
*/ |
487 |
public Phaser(int parties) { |
488 |
this(null, parties); |
489 |
} |
490 |
|
491 |
/** |
492 |
* Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}. |
493 |
* |
494 |
* @param parent the parent phaser |
495 |
*/ |
496 |
public Phaser(Phaser parent) { |
497 |
this(parent, 0); |
498 |
} |
499 |
|
500 |
/** |
501 |
* Creates a new phaser with the given parent and number of |
502 |
* registered unarrived parties. If the given parent is non-null |
503 |
* and the given number of parties is greater than zero, this |
504 |
* child phaser is registered with its parent. |
505 |
* |
506 |
* @param parent the parent phaser |
507 |
* @param parties the number of parties required to advance to the |
508 |
* next phase |
509 |
* @throws IllegalArgumentException if parties less than zero |
510 |
* or greater than the maximum number of parties supported |
511 |
*/ |
512 |
public Phaser(Phaser parent, int parties) { |
513 |
if (parties >>> PARTIES_SHIFT != 0) |
514 |
throw new IllegalArgumentException("Illegal number of parties"); |
515 |
int phase = 0; |
516 |
this.parent = parent; |
517 |
if (parent != null) { |
518 |
final Phaser root = parent.root; |
519 |
this.root = root; |
520 |
this.evenQ = root.evenQ; |
521 |
this.oddQ = root.oddQ; |
522 |
if (parties != 0) |
523 |
phase = parent.doRegister(1); |
524 |
} |
525 |
else { |
526 |
this.root = this; |
527 |
this.evenQ = new AtomicReference<QNode>(); |
528 |
this.oddQ = new AtomicReference<QNode>(); |
529 |
} |
530 |
this.state = (parties == 0) ? (long) EMPTY : |
531 |
((((long) phase) << PHASE_SHIFT) | |
532 |
(((long) parties) << PARTIES_SHIFT) | |
533 |
((long) parties)); |
534 |
} |
535 |
|
536 |
/** |
537 |
* Adds a new unarrived party to this phaser. If an ongoing |
538 |
* invocation of {@link #onAdvance} is in progress, this method |
539 |
* may await its completion before returning. If this phaser has |
540 |
* a parent, and this phaser previously had no registered parties, |
541 |
* this child phaser is also registered with its parent. |
542 |
* |
543 |
* @return the arrival phase number to which this registration applied |
544 |
* @throws IllegalStateException if attempting to register more |
545 |
* than the maximum supported number of parties |
546 |
*/ |
547 |
public int register() { |
548 |
return doRegister(1); |
549 |
} |
550 |
|
551 |
/** |
552 |
* Adds the given number of new unarrived parties to this phaser. |
553 |
* If an ongoing invocation of {@link #onAdvance} is in progress, |
554 |
* this method may await its completion before returning. If this |
555 |
* phaser has a parent, and the given number of parties is |
556 |
* greater than zero, and this phaser previously had no registered |
557 |
* parties, this child phaser is also registered with its parent. |
558 |
* |
559 |
* @param parties the number of additional parties required to |
560 |
* advance to the next phase |
561 |
* @return the arrival phase number to which this registration applied |
562 |
* @throws IllegalStateException if attempting to register more |
563 |
* than the maximum supported number of parties |
564 |
* @throws IllegalArgumentException if {@code parties < 0} |
565 |
*/ |
566 |
public int bulkRegister(int parties) { |
567 |
if (parties < 0) |
568 |
throw new IllegalArgumentException(); |
569 |
if (parties == 0) |
570 |
return getPhase(); |
571 |
return doRegister(parties); |
572 |
} |
573 |
|
574 |
/** |
575 |
* Arrives at this phaser, without waiting for others to arrive. |
576 |
* |
577 |
* <p>It is a usage error for an unregistered party to invoke this |
578 |
* method. However, this error may result in an {@code |
579 |
* IllegalStateException} only upon some subsequent operation on |
580 |
* this phaser, if ever. |
581 |
* |
582 |
* @return the arrival phase number, or a negative value if terminated |
583 |
* @throws IllegalStateException if not terminated and the number |
584 |
* of unarrived parties would become negative |
585 |
*/ |
586 |
public int arrive() { |
587 |
return doArrive(false); |
588 |
} |
589 |
|
590 |
/** |
591 |
* Arrives at this phaser and deregisters from it without waiting |
592 |
* for others to arrive. Deregistration reduces the number of |
593 |
* parties required to advance in future phases. If this phaser |
594 |
* has a parent, and deregistration causes this phaser to have |
595 |
* zero parties, this phaser is also deregistered from its parent. |
596 |
* |
597 |
* <p>It is a usage error for an unregistered party to invoke this |
598 |
* method. However, this error may result in an {@code |
599 |
* IllegalStateException} only upon some subsequent operation on |
600 |
* this phaser, if ever. |
601 |
* |
602 |
* @return the arrival phase number, or a negative value if terminated |
603 |
* @throws IllegalStateException if not terminated and the number |
604 |
* of registered or unarrived parties would become negative |
605 |
*/ |
606 |
public int arriveAndDeregister() { |
607 |
return doArrive(true); |
608 |
} |
609 |
|
610 |
/** |
611 |
* Arrives at this phaser and awaits others. Equivalent in effect |
612 |
* to {@code awaitAdvance(arrive())}. If you need to await with |
613 |
* interruption or timeout, you can arrange this with an analogous |
614 |
* construction using one of the other forms of the {@code |
615 |
* awaitAdvance} method. If instead you need to deregister upon |
616 |
* arrival, use {@code awaitAdvance(arriveAndDeregister())}. |
617 |
* |
618 |
* <p>It is a usage error for an unregistered party to invoke this |
619 |
* method. However, this error may result in an {@code |
620 |
* IllegalStateException} only upon some subsequent operation on |
621 |
* this phaser, if ever. |
622 |
* |
623 |
* @return the arrival phase number, or a negative number if terminated |
624 |
* @throws IllegalStateException if not terminated and the number |
625 |
* of unarrived parties would become negative |
626 |
*/ |
627 |
public int arriveAndAwaitAdvance() { |
628 |
return awaitAdvance(doArrive(false)); |
629 |
} |
630 |
|
631 |
/** |
632 |
* Awaits the phase of this phaser to advance from the given phase |
633 |
* value, returning immediately if the current phase is not equal |
634 |
* to the given phase value or this phaser is terminated. |
635 |
* |
636 |
* @param phase an arrival phase number, or negative value if |
637 |
* terminated; this argument is normally the value returned by a |
638 |
* previous call to {@code arrive} or {@code arriveAndDeregister}. |
639 |
* @return the next arrival phase number, or a negative value |
640 |
* if terminated or argument is negative |
641 |
*/ |
642 |
public int awaitAdvance(int phase) { |
643 |
if (phase < 0) |
644 |
return phase; |
645 |
int p = (int)(state >>> PHASE_SHIFT); |
646 |
if (p == phase) { |
647 |
final Phaser root = this.root; |
648 |
p = (int)(root.state >>> PHASE_SHIFT); |
649 |
if (p == phase) |
650 |
return root.internalAwaitAdvance(phase, null); |
651 |
reconcileState(); |
652 |
} |
653 |
return p; |
654 |
} |
655 |
|
656 |
/** |
657 |
* Awaits the phase of this phaser to advance from the given phase |
658 |
* value, throwing {@code InterruptedException} if interrupted |
659 |
* while waiting, or returning immediately if the current phase is |
660 |
* not equal to the given phase value or this phaser is |
661 |
* terminated. |
662 |
* |
663 |
* @param phase an arrival phase number, or negative value if |
664 |
* terminated; this argument is normally the value returned by a |
665 |
* previous call to {@code arrive} or {@code arriveAndDeregister}. |
666 |
* @return the next arrival phase number, or a negative value |
667 |
* if terminated or argument is negative |
668 |
* @throws InterruptedException if thread interrupted while waiting |
669 |
*/ |
670 |
public int awaitAdvanceInterruptibly(int phase) |
671 |
throws InterruptedException { |
672 |
if (phase < 0) |
673 |
return phase; |
674 |
int p = (int)(state >>> PHASE_SHIFT); |
675 |
if (p == phase) { |
676 |
final Phaser root = this.root; |
677 |
p = (int)(root.state >>> PHASE_SHIFT); |
678 |
if (p == phase) { |
679 |
QNode node = new QNode(this, phase, true, false, 0L); |
680 |
p = root.internalAwaitAdvance(phase, node); |
681 |
if (node.wasInterrupted) |
682 |
throw new InterruptedException(); |
683 |
} |
684 |
else |
685 |
reconcileState(); |
686 |
} |
687 |
return p; |
688 |
} |
689 |
|
690 |
/** |
691 |
* Awaits the phase of this phaser to advance from the given phase |
692 |
* value or the given timeout to elapse, throwing {@code |
693 |
* InterruptedException} if interrupted while waiting, or |
694 |
* returning immediately if the current phase is not equal to the |
695 |
* given phase value or this phaser is terminated. |
696 |
* |
697 |
* @param phase an arrival phase number, or negative value if |
698 |
* terminated; this argument is normally the value returned by a |
699 |
* previous call to {@code arrive} or {@code arriveAndDeregister}. |
700 |
* @param timeout how long to wait before giving up, in units of |
701 |
* {@code unit} |
702 |
* @param unit a {@code TimeUnit} determining how to interpret the |
703 |
* {@code timeout} parameter |
704 |
* @return the next arrival phase number, or a negative value |
705 |
* if terminated or argument is negative |
706 |
* @throws InterruptedException if thread interrupted while waiting |
707 |
* @throws TimeoutException if timed out while waiting |
708 |
*/ |
709 |
public int awaitAdvanceInterruptibly(int phase, |
710 |
long timeout, TimeUnit unit) |
711 |
throws InterruptedException, TimeoutException { |
712 |
if (phase < 0) |
713 |
return phase; |
714 |
long nanos = unit.toNanos(timeout); |
715 |
int p = (int)(state >>> PHASE_SHIFT); |
716 |
if (p == phase) { |
717 |
final Phaser root = this.root; |
718 |
p = (int)(root.state >>> PHASE_SHIFT); |
719 |
if (p == phase) { |
720 |
QNode node = new QNode(this, phase, true, true, nanos); |
721 |
p = root.internalAwaitAdvance(phase, node); |
722 |
if (node.wasInterrupted) |
723 |
throw new InterruptedException(); |
724 |
else if (p == phase) |
725 |
throw new TimeoutException(); |
726 |
} |
727 |
else |
728 |
reconcileState(); |
729 |
} |
730 |
return p; |
731 |
} |
732 |
|
733 |
/** |
734 |
* Forces this phaser to enter termination state. Counts of |
735 |
* registered parties are unaffected. If this phaser is a member |
736 |
* of a tiered set of phasers, then all of the phasers in the set |
737 |
* are terminated. If this phaser is already terminated, this |
738 |
* method has no effect. This method may be useful for |
739 |
* coordinating recovery after one or more tasks encounter |
740 |
* unexpected exceptions. |
741 |
*/ |
742 |
public void forceTermination() { |
743 |
// Only need to change root state |
744 |
final Phaser root = this.root; |
745 |
long s; |
746 |
while ((s = root.state) >= 0) { |
747 |
long next = (s & ~((long)UNARRIVED_MASK)) | TERMINATION_BIT; |
748 |
if (UNSAFE.compareAndSwapLong(root, stateOffset, s, next)) { |
749 |
// signal all threads |
750 |
releaseWaiters(0); |
751 |
releaseWaiters(1); |
752 |
return; |
753 |
} |
754 |
} |
755 |
} |
756 |
|
757 |
/** |
758 |
* Returns the current phase number. The maximum phase number is |
759 |
* {@code Integer.MAX_VALUE}, after which it restarts at |
760 |
* zero. Upon termination, the phase number is negative, |
761 |
* in which case the prevailing phase prior to termination |
762 |
* may be obtained via {@code getPhase() + Integer.MIN_VALUE}. |
763 |
* |
764 |
* @return the phase number, or a negative value if terminated |
765 |
*/ |
766 |
public final int getPhase() { |
767 |
return (int)(root.state >>> PHASE_SHIFT); |
768 |
} |
769 |
|
770 |
/** |
771 |
* Returns the number of parties registered at this phaser. |
772 |
* |
773 |
* @return the number of parties |
774 |
*/ |
775 |
public int getRegisteredParties() { |
776 |
return partiesOf(state); |
777 |
} |
778 |
|
779 |
/** |
780 |
* Returns the number of registered parties that have arrived at |
781 |
* the current phase of this phaser. |
782 |
* |
783 |
* @return the number of arrived parties |
784 |
*/ |
785 |
public int getArrivedParties() { |
786 |
return arrivedOf(reconcileState()); |
787 |
} |
788 |
|
789 |
/** |
790 |
* Returns the number of registered parties that have not yet |
791 |
* arrived at the current phase of this phaser. |
792 |
* |
793 |
* @return the number of unarrived parties |
794 |
*/ |
795 |
public int getUnarrivedParties() { |
796 |
return unarrivedOf(reconcileState()); |
797 |
} |
798 |
|
799 |
/** |
800 |
* Returns the parent of this phaser, or {@code null} if none. |
801 |
* |
802 |
* @return the parent of this phaser, or {@code null} if none |
803 |
*/ |
804 |
public Phaser getParent() { |
805 |
return parent; |
806 |
} |
807 |
|
808 |
/** |
809 |
* Returns the root ancestor of this phaser, which is the same as |
810 |
* this phaser if it has no parent. |
811 |
* |
812 |
* @return the root ancestor of this phaser |
813 |
*/ |
814 |
public Phaser getRoot() { |
815 |
return root; |
816 |
} |
817 |
|
818 |
/** |
819 |
* Returns {@code true} if this phaser has been terminated. |
820 |
* |
821 |
* @return {@code true} if this phaser has been terminated |
822 |
*/ |
823 |
public boolean isTerminated() { |
824 |
return root.state < 0L; |
825 |
} |
826 |
|
827 |
/** |
828 |
* Overridable method to perform an action upon impending phase |
829 |
* advance, and to control termination. This method is invoked |
830 |
* upon arrival of the party advancing this phaser (when all other |
831 |
* waiting parties are dormant). If this method returns {@code |
832 |
* true}, this phaser will be set to a final termination state |
833 |
* upon advance, and subsequent calls to {@link #isTerminated} |
834 |
* will return true. Any (unchecked) Exception or Error thrown by |
835 |
* an invocation of this method is propagated to the party |
836 |
* attempting to advance this phaser, in which case no advance |
837 |
* occurs. |
838 |
* |
839 |
* <p>The arguments to this method provide the state of the phaser |
840 |
* prevailing for the current transition. The effects of invoking |
841 |
* arrival, registration, and waiting methods on this phaser from |
842 |
* within {@code onAdvance} are unspecified and should not be |
843 |
* relied on. |
844 |
* |
845 |
* <p>If this phaser is a member of a tiered set of phasers, then |
846 |
* {@code onAdvance} is invoked only for its root phaser on each |
847 |
* advance. |
848 |
* |
849 |
* <p>To support the most common use cases, the default |
850 |
* implementation of this method returns {@code true} when the |
851 |
* number of registered parties has become zero as the result of a |
852 |
* party invoking {@code arriveAndDeregister}. You can disable |
853 |
* this behavior, thus enabling continuation upon future |
854 |
* registrations, by overriding this method to always return |
855 |
* {@code false}: |
856 |
* |
857 |
* <pre> {@code |
858 |
* Phaser phaser = new Phaser() { |
859 |
* protected boolean onAdvance(int phase, int parties) { return false; } |
860 |
* }}</pre> |
861 |
* |
862 |
* @param phase the current phase number on entry to this method, |
863 |
* before this phaser is advanced |
864 |
* @param registeredParties the current number of registered parties |
865 |
* @return {@code true} if this phaser should terminate |
866 |
*/ |
867 |
protected boolean onAdvance(int phase, int registeredParties) { |
868 |
return registeredParties == 0; |
869 |
} |
870 |
|
871 |
/** |
872 |
* Returns a string identifying this phaser, as well as its |
873 |
* state. The state, in brackets, includes the String {@code |
874 |
* "phase = "} followed by the phase number, {@code "parties = "} |
875 |
* followed by the number of registered parties, and {@code |
876 |
* "arrived = "} followed by the number of arrived parties. |
877 |
* |
878 |
* @return a string identifying this phaser, as well as its state |
879 |
*/ |
880 |
public String toString() { |
881 |
return stateToString(reconcileState()); |
882 |
} |
883 |
|
884 |
/** |
885 |
* Implementation of toString and string-based error messages |
886 |
*/ |
887 |
private String stateToString(long s) { |
888 |
return super.toString() + |
889 |
"[phase = " + phaseOf(s) + |
890 |
" parties = " + partiesOf(s) + |
891 |
" arrived = " + arrivedOf(s) + "]"; |
892 |
} |
893 |
|
894 |
// Waiting mechanics |
895 |
|
896 |
/** |
897 |
* Removes and signals threads from queue for phase. |
898 |
*/ |
899 |
private void releaseWaiters(int phase) { |
900 |
QNode q; // first element of queue |
901 |
int p; // its phase |
902 |
Thread t; // its thread |
903 |
// assert phase != phaseOf(root.state); |
904 |
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ; |
905 |
while ((q = head.get()) != null && |
906 |
q.phase != (int)(root.state >>> PHASE_SHIFT)) { |
907 |
if (head.compareAndSet(q, q.next) && |
908 |
(t = q.thread) != null) { |
909 |
q.thread = null; |
910 |
LockSupport.unpark(t); |
911 |
} |
912 |
} |
913 |
} |
914 |
|
915 |
/** The number of CPUs, for spin control */ |
916 |
private static final int NCPU = Runtime.getRuntime().availableProcessors(); |
917 |
|
918 |
/** |
919 |
* The number of times to spin before blocking while waiting for |
920 |
* advance, per arrival while waiting. On multiprocessors, fully |
921 |
* blocking and waking up a large number of threads all at once is |
922 |
* usually a very slow process, so we use rechargeable spins to |
923 |
* avoid it when threads regularly arrive: When a thread in |
924 |
* internalAwaitAdvance notices another arrival before blocking, |
925 |
* and there appear to be enough CPUs available, it spins |
926 |
* SPINS_PER_ARRIVAL more times before blocking. The value trades |
927 |
* off good-citizenship vs big unnecessary slowdowns. |
928 |
*/ |
929 |
static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8; |
930 |
|
931 |
/** |
932 |
* Possibly blocks and waits for phase to advance unless aborted. |
933 |
* Call only from root node. |
934 |
* |
935 |
* @param phase current phase |
936 |
* @param node if non-null, the wait node to track interrupt and timeout; |
937 |
* if null, denotes noninterruptible wait |
938 |
* @return current phase |
939 |
*/ |
940 |
private int internalAwaitAdvance(int phase, QNode node) { |
941 |
releaseWaiters(phase-1); // ensure old queue clean |
942 |
boolean queued = false; // true when node is enqueued |
943 |
int lastUnarrived = 0; // to increase spins upon change |
944 |
int spins = SPINS_PER_ARRIVAL; |
945 |
long s; |
946 |
int p; |
947 |
while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) { |
948 |
if (node == null) { // spinning in noninterruptible mode |
949 |
int unarrived = (int)s & UNARRIVED_MASK; |
950 |
if (unarrived != lastUnarrived && |
951 |
(lastUnarrived = unarrived) < NCPU) |
952 |
spins += SPINS_PER_ARRIVAL; |
953 |
boolean interrupted = Thread.interrupted(); |
954 |
if (interrupted || --spins < 0) { // need node to record intr |
955 |
node = new QNode(this, phase, false, false, 0L); |
956 |
node.wasInterrupted = interrupted; |
957 |
} |
958 |
} |
959 |
else if (node.isReleasable()) // done or aborted |
960 |
break; |
961 |
else if (!queued) { // push onto queue |
962 |
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ; |
963 |
QNode q = node.next = head.get(); |
964 |
if ((q == null || q.phase == phase) && |
965 |
(int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq |
966 |
queued = head.compareAndSet(q, node); |
967 |
} |
968 |
else { |
969 |
try { |
970 |
ForkJoinPool.managedBlock(node); |
971 |
} catch (InterruptedException ie) { |
972 |
node.wasInterrupted = true; |
973 |
} |
974 |
} |
975 |
} |
976 |
|
977 |
if (node != null) { |
978 |
if (node.thread != null) |
979 |
node.thread = null; // avoid need for unpark() |
980 |
if (node.wasInterrupted && !node.interruptible) |
981 |
Thread.currentThread().interrupt(); |
982 |
if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase) |
983 |
return p; // recheck abort |
984 |
} |
985 |
releaseWaiters(phase); |
986 |
return p; |
987 |
} |
988 |
|
989 |
/** |
990 |
* Wait nodes for Treiber stack representing wait queue |
991 |
*/ |
992 |
static final class QNode implements ForkJoinPool.ManagedBlocker { |
993 |
final Phaser phaser; |
994 |
final int phase; |
995 |
final boolean interruptible; |
996 |
final boolean timed; |
997 |
boolean wasInterrupted; |
998 |
long nanos; |
999 |
long lastTime; |
1000 |
volatile Thread thread; // nulled to cancel wait |
1001 |
QNode next; |
1002 |
|
1003 |
QNode(Phaser phaser, int phase, boolean interruptible, |
1004 |
boolean timed, long nanos) { |
1005 |
this.phaser = phaser; |
1006 |
this.phase = phase; |
1007 |
this.interruptible = interruptible; |
1008 |
this.nanos = nanos; |
1009 |
this.timed = timed; |
1010 |
this.lastTime = timed ? System.nanoTime() : 0L; |
1011 |
thread = Thread.currentThread(); |
1012 |
} |
1013 |
|
1014 |
public boolean isReleasable() { |
1015 |
if (thread == null) |
1016 |
return true; |
1017 |
if (phaser.getPhase() != phase) { |
1018 |
thread = null; |
1019 |
return true; |
1020 |
} |
1021 |
if (Thread.interrupted()) |
1022 |
wasInterrupted = true; |
1023 |
if (wasInterrupted && interruptible) { |
1024 |
thread = null; |
1025 |
return true; |
1026 |
} |
1027 |
if (timed) { |
1028 |
if (nanos > 0L) { |
1029 |
long now = System.nanoTime(); |
1030 |
nanos -= now - lastTime; |
1031 |
lastTime = now; |
1032 |
} |
1033 |
if (nanos <= 0L) { |
1034 |
thread = null; |
1035 |
return true; |
1036 |
} |
1037 |
} |
1038 |
return false; |
1039 |
} |
1040 |
|
1041 |
public boolean block() { |
1042 |
if (isReleasable()) |
1043 |
return true; |
1044 |
else if (!timed) |
1045 |
LockSupport.park(this); |
1046 |
else if (nanos > 0) |
1047 |
LockSupport.parkNanos(this, nanos); |
1048 |
return isReleasable(); |
1049 |
} |
1050 |
} |
1051 |
|
1052 |
// Unsafe mechanics |
1053 |
|
1054 |
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); |
1055 |
private static final long stateOffset = |
1056 |
objectFieldOffset("state", Phaser.class); |
1057 |
|
1058 |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1059 |
try { |
1060 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1061 |
} catch (NoSuchFieldException e) { |
1062 |
// Convert Exception to corresponding Error |
1063 |
NoSuchFieldError error = new NoSuchFieldError(field); |
1064 |
error.initCause(e); |
1065 |
throw error; |
1066 |
} |
1067 |
} |
1068 |
} |