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