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