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.Random; |
10 |
import java.util.Collection; |
11 |
import java.util.concurrent.locks.LockSupport; |
12 |
|
13 |
/** |
14 |
* A thread managed by a {@link ForkJoinPool}. This class is |
15 |
* subclassable solely for the sake of adding functionality -- there |
16 |
* are no overridable methods dealing with scheduling or execution. |
17 |
* However, you can override initialization and termination methods |
18 |
* surrounding the main task processing loop. If you do create such a |
19 |
* subclass, you will also need to supply a custom {@link |
20 |
* ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code |
21 |
* ForkJoinPool}. |
22 |
* |
23 |
* @since 1.7 |
24 |
* @author Doug Lea |
25 |
*/ |
26 |
public class ForkJoinWorkerThread extends Thread { |
27 |
/* |
28 |
* Overview: |
29 |
* |
30 |
* ForkJoinWorkerThreads are managed by ForkJoinPools and perform |
31 |
* ForkJoinTasks. This class includes bookkeeping in support of |
32 |
* worker activation, suspension, and lifecycle control described |
33 |
* in more detail in the internal documentation of class |
34 |
* ForkJoinPool. And as described further below, this class also |
35 |
* includes special-cased support for some ForkJoinTask |
36 |
* methods. But the main mechanics involve work-stealing: |
37 |
* |
38 |
* Work-stealing queues are special forms of Deques that support |
39 |
* only three of the four possible end-operations -- push, pop, |
40 |
* and deq (aka steal), under the further constraints that push |
41 |
* and pop are called only from the owning thread, while deq may |
42 |
* be called from other threads. (If you are unfamiliar with |
43 |
* them, you probably want to read Herlihy and Shavit's book "The |
44 |
* Art of Multiprocessor programming", chapter 16 describing these |
45 |
* in more detail before proceeding.) The main work-stealing |
46 |
* queue design is roughly similar to those in the papers "Dynamic |
47 |
* Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005 |
48 |
* (http://research.sun.com/scalable/pubs/index.html) and |
49 |
* "Idempotent work stealing" by Michael, Saraswat, and Vechev, |
50 |
* PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186). |
51 |
* The main differences ultimately stem from gc requirements that |
52 |
* we null out taken slots as soon as we can, to maintain as small |
53 |
* a footprint as possible even in programs generating huge |
54 |
* numbers of tasks. To accomplish this, we shift the CAS |
55 |
* arbitrating pop vs deq (steal) from being on the indices |
56 |
* ("base" and "sp") to the slots themselves (mainly via method |
57 |
* "casSlotNull()"). So, both a successful pop and deq mainly |
58 |
* entail a CAS of a slot from non-null to null. Because we rely |
59 |
* on CASes of references, we do not need tag bits on base or sp. |
60 |
* They are simple ints as used in any circular array-based queue |
61 |
* (see for example ArrayDeque). Updates to the indices must |
62 |
* still be ordered in a way that guarantees that sp == base means |
63 |
* the queue is empty, but otherwise may err on the side of |
64 |
* possibly making the queue appear nonempty when a push, pop, or |
65 |
* deq have not fully committed. Note that this means that the deq |
66 |
* operation, considered individually, is not wait-free. One thief |
67 |
* cannot successfully continue until another in-progress one (or, |
68 |
* if previously empty, a push) completes. However, in the |
69 |
* aggregate, we ensure at least probabilistic non-blockingness. |
70 |
* If an attempted steal fails, a thief always chooses a different |
71 |
* random victim target to try next. So, in order for one thief to |
72 |
* progress, it suffices for any in-progress deq or new push on |
73 |
* any empty queue to complete. One reason this works well here is |
74 |
* that apparently-nonempty often means soon-to-be-stealable, |
75 |
* which gives threads a chance to set activation status if |
76 |
* necessary before stealing. |
77 |
* |
78 |
* This approach also enables support for "async mode" where local |
79 |
* task processing is in FIFO, not LIFO order; simply by using a |
80 |
* version of deq rather than pop when locallyFifo is true (as set |
81 |
* by the ForkJoinPool). This allows use in message-passing |
82 |
* frameworks in which tasks are never joined. |
83 |
* |
84 |
* When a worker would otherwise be blocked waiting to join a |
85 |
* task, it first tries a form of linear helping: Each worker |
86 |
* records (in field stolen) the most recent task it stole |
87 |
* from some other worker. Plus, it records (in field joining) the |
88 |
* task it is currently actively joining. Method joinTask uses |
89 |
* these markers to try to find a worker to help (i.e., steal back |
90 |
* a task from and execute it) that could hasten completion of the |
91 |
* actively joined task. In essence, the joiner executes a task |
92 |
* that would be on its own local deque had the to-be-joined task |
93 |
* not been stolen. This may be seen as a conservative variant of |
94 |
* the approach in Wagner & Calder "Leapfrogging: a portable |
95 |
* technique for implementing efficient futures" SIGPLAN Notices, |
96 |
* 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs |
97 |
* in that: (1) We only maintain dependency links across workers |
98 |
* upon steals, rather than maintain per-task bookkeeping. This |
99 |
* requires a linear scan of workers array to locate stealers, |
100 |
* which isolates cost to when it is needed, rather than adding to |
101 |
* per-task overhead. (2) It is "shallow", ignoring nesting and |
102 |
* potentially cyclic mutual steals. (3) It is intentionally |
103 |
* racy: field joining is updated only while actively joining, |
104 |
* which means that we could miss links in the chain during |
105 |
* long-lived tasks, GC stalls etc. (4) We fall back to |
106 |
* suspending the worker and if necessary replacing it with a |
107 |
* spare (see ForkJoinPool.tryAwaitJoin). |
108 |
* |
109 |
* Efficient implementation of these algorithms currently relies on |
110 |
* an uncomfortable amount of "Unsafe" mechanics. To maintain |
111 |
* correct orderings, reads and writes of variable base require |
112 |
* volatile ordering. Variable sp does not require volatile |
113 |
* writes but still needs store-ordering, which we accomplish by |
114 |
* pre-incrementing sp before filling the slot with an ordered |
115 |
* store. (Pre-incrementing also enables backouts used in |
116 |
* scanWhileJoining.) Because they are protected by volatile base |
117 |
* reads, reads of the queue array and its slots by other threads |
118 |
* do not need volatile load semantics, but writes (in push) |
119 |
* require store order and CASes (in pop and deq) require |
120 |
* (volatile) CAS semantics. (Michael, Saraswat, and Vechev's |
121 |
* algorithm has similar properties, but without support for |
122 |
* nulling slots.) Since these combinations aren't supported |
123 |
* using ordinary volatiles, the only way to accomplish these |
124 |
* efficiently is to use direct Unsafe calls. (Using external |
125 |
* AtomicIntegers and AtomicReferenceArrays for the indices and |
126 |
* array is significantly slower because of memory locality and |
127 |
* indirection effects.) |
128 |
* |
129 |
* Further, performance on most platforms is very sensitive to |
130 |
* placement and sizing of the (resizable) queue array. Even |
131 |
* though these queues don't usually become all that big, the |
132 |
* initial size must be large enough to counteract cache |
133 |
* contention effects across multiple queues (especially in the |
134 |
* presence of GC cardmarking). Also, to improve thread-locality, |
135 |
* queues are initialized after starting. All together, these |
136 |
* low-level implementation choices produce as much as a factor of |
137 |
* 4 performance improvement compared to naive implementations, |
138 |
* and enable the processing of billions of tasks per second, |
139 |
* sometimes at the expense of ugliness. |
140 |
*/ |
141 |
|
142 |
/** |
143 |
* Generator for initial random seeds for random victim |
144 |
* selection. This is used only to create initial seeds. Random |
145 |
* steals use a cheaper xorshift generator per steal attempt. We |
146 |
* expect only rare contention on seedGenerator, so just use a |
147 |
* plain Random. |
148 |
*/ |
149 |
private static final Random seedGenerator = new Random(); |
150 |
|
151 |
/** |
152 |
* The timeout value for suspending spares. Spare workers that |
153 |
* remain unsignalled for more than this time may be trimmed |
154 |
* (killed and removed from pool). Since our goal is to avoid |
155 |
* long-term thread buildup, the exact value of timeout does not |
156 |
* matter too much so long as it avoids most false-alarm timeouts |
157 |
* under GC stalls or momentarily high system load. |
158 |
*/ |
159 |
private static final long SPARE_KEEPALIVE_NANOS = |
160 |
5L * 1000L * 1000L * 1000L; // 5 secs |
161 |
|
162 |
/** |
163 |
* Capacity of work-stealing queue array upon initialization. |
164 |
* Must be a power of two. Initial size must be at least 4, but is |
165 |
* padded to minimize cache effects. |
166 |
*/ |
167 |
private static final int INITIAL_QUEUE_CAPACITY = 1 << 13; |
168 |
|
169 |
/** |
170 |
* Maximum work-stealing queue array size. Must be less than or |
171 |
* equal to 1 << 28 to ensure lack of index wraparound. (This |
172 |
* is less than usual bounds, because we need leftshift by 3 |
173 |
* to be in int range). |
174 |
*/ |
175 |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28; |
176 |
|
177 |
/** |
178 |
* The pool this thread works in. Accessed directly by ForkJoinTask. |
179 |
*/ |
180 |
final ForkJoinPool pool; |
181 |
|
182 |
/** |
183 |
* The task most recently stolen from another worker |
184 |
*/ |
185 |
private volatile ForkJoinTask<?> stolen; |
186 |
|
187 |
/** |
188 |
* The task currently being joined, set only when actively |
189 |
* trying to helpStealer. |
190 |
*/ |
191 |
private volatile ForkJoinTask<?> joining; |
192 |
|
193 |
/** |
194 |
* The work-stealing queue array. Size must be a power of two. |
195 |
* Initialized in onStart, to improve memory locality. |
196 |
*/ |
197 |
private ForkJoinTask<?>[] queue; |
198 |
|
199 |
/** |
200 |
* Index (mod queue.length) of least valid queue slot, which is |
201 |
* always the next position to steal from if nonempty. |
202 |
*/ |
203 |
private volatile int base; |
204 |
|
205 |
/** |
206 |
* Index (mod queue.length) of next queue slot to push to or pop |
207 |
* from. It is written only by owner thread, and accessed by other |
208 |
* threads only after reading (volatile) base. Both sp and base |
209 |
* are allowed to wrap around on overflow, but (sp - base) still |
210 |
* estimates size. |
211 |
*/ |
212 |
private int sp; |
213 |
|
214 |
/** |
215 |
* Run state of this worker. In addition to the usual run levels, |
216 |
* tracks if this worker is suspended as a spare, and if it was |
217 |
* killed (trimmed) while suspended. However, "active" status is |
218 |
* maintained separately. |
219 |
*/ |
220 |
private volatile int runState; |
221 |
|
222 |
private static final int TERMINATING = 0x01; |
223 |
private static final int TERMINATED = 0x02; |
224 |
private static final int SUSPENDED = 0x04; // inactive spare |
225 |
private static final int TRIMMED = 0x08; // killed while suspended |
226 |
|
227 |
/** |
228 |
* Number of LockSupport.park calls to block this thread for |
229 |
* suspension or event waits. Used for internal instrumention; |
230 |
* currently not exported but included because volatile write upon |
231 |
* park also provides a workaround for a JVM bug. |
232 |
*/ |
233 |
volatile int parkCount; |
234 |
|
235 |
/** |
236 |
* Number of steals, transferred and reset in pool callbacks pool |
237 |
* when idle Accessed directly by pool. |
238 |
*/ |
239 |
int stealCount; |
240 |
|
241 |
/** |
242 |
* Seed for random number generator for choosing steal victims. |
243 |
* Uses Marsaglia xorshift. Must be initialized as nonzero. |
244 |
*/ |
245 |
private int seed; |
246 |
|
247 |
/** |
248 |
* Activity status. When true, this worker is considered active. |
249 |
* Accessed directly by pool. Must be false upon construction. |
250 |
*/ |
251 |
boolean active; |
252 |
|
253 |
/** |
254 |
* True if use local fifo, not default lifo, for local polling. |
255 |
* Shadows value from ForkJoinPool, which resets it if changed |
256 |
* pool-wide. |
257 |
*/ |
258 |
private final boolean locallyFifo; |
259 |
|
260 |
/** |
261 |
* Index of this worker in pool array. Set once by pool before |
262 |
* running, and accessed directly by pool to locate this worker in |
263 |
* its workers array. |
264 |
*/ |
265 |
int poolIndex; |
266 |
|
267 |
/** |
268 |
* The last pool event waited for. Accessed only by pool in |
269 |
* callback methods invoked within this thread. |
270 |
*/ |
271 |
int lastEventCount; |
272 |
|
273 |
/** |
274 |
* Encoded index and event count of next event waiter. Used only |
275 |
* by ForkJoinPool for managing event waiters. |
276 |
*/ |
277 |
volatile long nextWaiter; |
278 |
|
279 |
/** |
280 |
* Creates a ForkJoinWorkerThread operating in the given pool. |
281 |
* |
282 |
* @param pool the pool this thread works in |
283 |
* @throws NullPointerException if pool is null |
284 |
*/ |
285 |
protected ForkJoinWorkerThread(ForkJoinPool pool) { |
286 |
this.pool = pool; |
287 |
this.locallyFifo = pool.locallyFifo; |
288 |
// To avoid exposing construction details to subclasses, |
289 |
// remaining initialization is in start() and onStart() |
290 |
} |
291 |
|
292 |
/** |
293 |
* Performs additional initialization and starts this thread |
294 |
*/ |
295 |
final void start(int poolIndex, UncaughtExceptionHandler ueh) { |
296 |
this.poolIndex = poolIndex; |
297 |
if (ueh != null) |
298 |
setUncaughtExceptionHandler(ueh); |
299 |
setDaemon(true); |
300 |
start(); |
301 |
} |
302 |
|
303 |
// Public/protected methods |
304 |
|
305 |
/** |
306 |
* Returns the pool hosting this thread. |
307 |
* |
308 |
* @return the pool |
309 |
*/ |
310 |
public ForkJoinPool getPool() { |
311 |
return pool; |
312 |
} |
313 |
|
314 |
/** |
315 |
* Returns the index number of this thread in its pool. The |
316 |
* returned value ranges from zero to the maximum number of |
317 |
* threads (minus one) that have ever been created in the pool. |
318 |
* This method may be useful for applications that track status or |
319 |
* collect results per-worker rather than per-task. |
320 |
* |
321 |
* @return the index number |
322 |
*/ |
323 |
public int getPoolIndex() { |
324 |
return poolIndex; |
325 |
} |
326 |
|
327 |
/** |
328 |
* Initializes internal state after construction but before |
329 |
* processing any tasks. If you override this method, you must |
330 |
* invoke super.onStart() at the beginning of the method. |
331 |
* Initialization requires care: Most fields must have legal |
332 |
* default values, to ensure that attempted accesses from other |
333 |
* threads work correctly even before this thread starts |
334 |
* processing tasks. |
335 |
*/ |
336 |
protected void onStart() { |
337 |
int rs = seedGenerator.nextInt(); |
338 |
seed = rs == 0? 1 : rs; // seed must be nonzero |
339 |
|
340 |
// Allocate name string and arrays in this thread |
341 |
String pid = Integer.toString(pool.getPoolNumber()); |
342 |
String wid = Integer.toString(poolIndex); |
343 |
setName("ForkJoinPool-" + pid + "-worker-" + wid); |
344 |
|
345 |
queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
346 |
} |
347 |
|
348 |
/** |
349 |
* Performs cleanup associated with termination of this worker |
350 |
* thread. If you override this method, you must invoke |
351 |
* {@code super.onTermination} at the end of the overridden method. |
352 |
* |
353 |
* @param exception the exception causing this thread to abort due |
354 |
* to an unrecoverable error, or {@code null} if completed normally |
355 |
*/ |
356 |
protected void onTermination(Throwable exception) { |
357 |
try { |
358 |
stolen = null; |
359 |
joining = null; |
360 |
cancelTasks(); |
361 |
setTerminated(); |
362 |
pool.workerTerminated(this); |
363 |
} catch (Throwable ex) { // Shouldn't ever happen |
364 |
if (exception == null) // but if so, at least rethrown |
365 |
exception = ex; |
366 |
} finally { |
367 |
if (exception != null) |
368 |
UNSAFE.throwException(exception); |
369 |
} |
370 |
} |
371 |
|
372 |
/** |
373 |
* This method is required to be public, but should never be |
374 |
* called explicitly. It performs the main run loop to execute |
375 |
* ForkJoinTasks. |
376 |
*/ |
377 |
public void run() { |
378 |
Throwable exception = null; |
379 |
try { |
380 |
onStart(); |
381 |
mainLoop(); |
382 |
} catch (Throwable ex) { |
383 |
exception = ex; |
384 |
} finally { |
385 |
onTermination(exception); |
386 |
} |
387 |
} |
388 |
|
389 |
// helpers for run() |
390 |
|
391 |
/** |
392 |
* Find and execute tasks and check status while running |
393 |
*/ |
394 |
private void mainLoop() { |
395 |
boolean ran = false; // true if ran task in last loop iter |
396 |
boolean prevRan = false; // true if ran on last or previous step |
397 |
ForkJoinPool p = pool; |
398 |
for (;;) { |
399 |
p.preStep(this, prevRan); |
400 |
if (runState != 0) |
401 |
return; |
402 |
ForkJoinTask<?> t; // try to get and run stolen or submitted task |
403 |
if ((t = scan()) != null || (t = pollSubmission()) != null) { |
404 |
t.tryExec(); |
405 |
if (base != sp) |
406 |
runLocalTasks(); |
407 |
stolen = null; |
408 |
prevRan = ran = true; |
409 |
} |
410 |
else { |
411 |
prevRan = ran; |
412 |
ran = false; |
413 |
} |
414 |
} |
415 |
} |
416 |
|
417 |
/** |
418 |
* Runs local tasks until queue is empty or shut down. Call only |
419 |
* while active. |
420 |
*/ |
421 |
private void runLocalTasks() { |
422 |
while (runState == 0) { |
423 |
ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask(); |
424 |
if (t != null) |
425 |
t.tryExec(); |
426 |
else if (base == sp) |
427 |
break; |
428 |
} |
429 |
} |
430 |
|
431 |
/** |
432 |
* If a submission exists, try to activate and take it |
433 |
* |
434 |
* @return a task, if available |
435 |
*/ |
436 |
private ForkJoinTask<?> pollSubmission() { |
437 |
ForkJoinPool p = pool; |
438 |
while (p.hasQueuedSubmissions()) { |
439 |
if (active || (active = p.tryIncrementActiveCount())) { |
440 |
ForkJoinTask<?> t = p.pollSubmission(); |
441 |
return t != null ? t : scan(); // if missed, rescan |
442 |
} |
443 |
} |
444 |
return null; |
445 |
} |
446 |
|
447 |
/* |
448 |
* Intrinsics-based atomic writes for queue slots. These are |
449 |
* basically the same as methods in AtomicObjectArray, but |
450 |
* specialized for (1) ForkJoinTask elements (2) requirement that |
451 |
* nullness and bounds checks have already been performed by |
452 |
* callers and (3) effective offsets are known not to overflow |
453 |
* from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't |
454 |
* need corresponding version for reads: plain array reads are OK |
455 |
* because they protected by other volatile reads and are |
456 |
* confirmed by CASes. |
457 |
* |
458 |
* Most uses don't actually call these methods, but instead contain |
459 |
* inlined forms that enable more predictable optimization. We |
460 |
* don't define the version of write used in pushTask at all, but |
461 |
* instead inline there a store-fenced array slot write. |
462 |
*/ |
463 |
|
464 |
/** |
465 |
* CASes slot i of array q from t to null. Caller must ensure q is |
466 |
* non-null and index is in range. |
467 |
*/ |
468 |
private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i, |
469 |
ForkJoinTask<?> t) { |
470 |
return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null); |
471 |
} |
472 |
|
473 |
/** |
474 |
* Performs a volatile write of the given task at given slot of |
475 |
* array q. Caller must ensure q is non-null and index is in |
476 |
* range. This method is used only during resets and backouts. |
477 |
*/ |
478 |
private static final void writeSlot(ForkJoinTask<?>[] q, int i, |
479 |
ForkJoinTask<?> t) { |
480 |
UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t); |
481 |
} |
482 |
|
483 |
// queue methods |
484 |
|
485 |
/** |
486 |
* Pushes a task. Call only from this thread. |
487 |
* |
488 |
* @param t the task. Caller must ensure non-null. |
489 |
*/ |
490 |
final void pushTask(ForkJoinTask<?> t) { |
491 |
ForkJoinTask<?>[] q = queue; |
492 |
int mask = q.length - 1; // implicit assert q != null |
493 |
int s = sp++; // ok to increment sp before slot write |
494 |
UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t); |
495 |
if ((s -= base) == 0) |
496 |
pool.signalWork(); // was empty |
497 |
else if (s == mask) |
498 |
growQueue(); // is full |
499 |
} |
500 |
|
501 |
/** |
502 |
* Tries to take a task from the base of the queue, failing if |
503 |
* empty or contended. Note: Specializations of this code appear |
504 |
* in locallyDeqTask and elsewhere. |
505 |
* |
506 |
* @return a task, or null if none or contended |
507 |
*/ |
508 |
final ForkJoinTask<?> deqTask() { |
509 |
ForkJoinTask<?> t; |
510 |
ForkJoinTask<?>[] q; |
511 |
int b, i; |
512 |
if ((b = base) != sp && |
513 |
(q = queue) != null && // must read q after b |
514 |
(t = q[i = (q.length - 1) & b]) != null && base == b && |
515 |
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
516 |
base = b + 1; |
517 |
return t; |
518 |
} |
519 |
return null; |
520 |
} |
521 |
|
522 |
/** |
523 |
* Tries to take a task from the base of own queue. Assumes active |
524 |
* status. Called only by current thread. |
525 |
* |
526 |
* @return a task, or null if none |
527 |
*/ |
528 |
final ForkJoinTask<?> locallyDeqTask() { |
529 |
ForkJoinTask<?>[] q = queue; |
530 |
if (q != null) { |
531 |
ForkJoinTask<?> t; |
532 |
int b, i; |
533 |
while (sp != (b = base)) { |
534 |
if ((t = q[i = (q.length - 1) & b]) != null && base == b && |
535 |
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, |
536 |
t, null)) { |
537 |
base = b + 1; |
538 |
return t; |
539 |
} |
540 |
} |
541 |
} |
542 |
return null; |
543 |
} |
544 |
|
545 |
/** |
546 |
* Returns a popped task, or null if empty. Assumes active status. |
547 |
* Called only by current thread. (Note: a specialization of this |
548 |
* code appears in popWhileJoining.) |
549 |
*/ |
550 |
final ForkJoinTask<?> popTask() { |
551 |
int s; |
552 |
ForkJoinTask<?>[] q; |
553 |
if (base != (s = sp) && (q = queue) != null) { |
554 |
int i = (q.length - 1) & --s; |
555 |
ForkJoinTask<?> t = q[i]; |
556 |
if (t != null && UNSAFE.compareAndSwapObject |
557 |
(q, (i << qShift) + qBase, t, null)) { |
558 |
sp = s; |
559 |
return t; |
560 |
} |
561 |
} |
562 |
return null; |
563 |
} |
564 |
|
565 |
/** |
566 |
* Specialized version of popTask to pop only if topmost element |
567 |
* is the given task. Called only by current thread while |
568 |
* active. |
569 |
* |
570 |
* @param t the task. Caller must ensure non-null. |
571 |
*/ |
572 |
final boolean unpushTask(ForkJoinTask<?> t) { |
573 |
int s; |
574 |
ForkJoinTask<?>[] q; |
575 |
if (base != (s = sp) && (q = queue) != null && |
576 |
UNSAFE.compareAndSwapObject |
577 |
(q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) { |
578 |
sp = s; |
579 |
return true; |
580 |
} |
581 |
return false; |
582 |
} |
583 |
|
584 |
/** |
585 |
* Returns next task or null if empty or contended |
586 |
*/ |
587 |
final ForkJoinTask<?> peekTask() { |
588 |
ForkJoinTask<?>[] q = queue; |
589 |
if (q == null) |
590 |
return null; |
591 |
int mask = q.length - 1; |
592 |
int i = locallyFifo ? base : (sp - 1); |
593 |
return q[i & mask]; |
594 |
} |
595 |
|
596 |
/** |
597 |
* Doubles queue array size. Transfers elements by emulating |
598 |
* steals (deqs) from old array and placing, oldest first, into |
599 |
* new array. |
600 |
*/ |
601 |
private void growQueue() { |
602 |
ForkJoinTask<?>[] oldQ = queue; |
603 |
int oldSize = oldQ.length; |
604 |
int newSize = oldSize << 1; |
605 |
if (newSize > MAXIMUM_QUEUE_CAPACITY) |
606 |
throw new RejectedExecutionException("Queue capacity exceeded"); |
607 |
ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize]; |
608 |
|
609 |
int b = base; |
610 |
int bf = b + oldSize; |
611 |
int oldMask = oldSize - 1; |
612 |
int newMask = newSize - 1; |
613 |
do { |
614 |
int oldIndex = b & oldMask; |
615 |
ForkJoinTask<?> t = oldQ[oldIndex]; |
616 |
if (t != null && !casSlotNull(oldQ, oldIndex, t)) |
617 |
t = null; |
618 |
writeSlot(newQ, b & newMask, t); |
619 |
} while (++b != bf); |
620 |
pool.signalWork(); |
621 |
} |
622 |
|
623 |
/** |
624 |
* Computes next value for random victim probe in scan(). Scans |
625 |
* don't require a very high quality generator, but also not a |
626 |
* crummy one. Marsaglia xor-shift is cheap and works well enough. |
627 |
* Note: This is manually inlined in scan() |
628 |
*/ |
629 |
private static final int xorShift(int r) { |
630 |
r ^= r << 13; |
631 |
r ^= r >>> 17; |
632 |
return r ^ (r << 5); |
633 |
} |
634 |
|
635 |
/** |
636 |
* Tries to steal a task from another worker. Starts at a random |
637 |
* index of workers array, and probes workers until finding one |
638 |
* with non-empty queue or finding that all are empty. It |
639 |
* randomly selects the first n probes. If these are empty, it |
640 |
* resorts to a circular sweep, which is necessary to accurately |
641 |
* set active status. (The circular sweep uses steps of |
642 |
* approximately half the array size plus 1, to avoid bias |
643 |
* stemming from leftmost packing of the array in ForkJoinPool.) |
644 |
* |
645 |
* This method must be both fast and quiet -- usually avoiding |
646 |
* memory accesses that could disrupt cache sharing etc other than |
647 |
* those needed to check for and take tasks (or to activate if not |
648 |
* already active). This accounts for, among other things, |
649 |
* updating random seed in place without storing it until exit. |
650 |
* |
651 |
* @return a task, or null if none found |
652 |
*/ |
653 |
private ForkJoinTask<?> scan() { |
654 |
ForkJoinPool p = pool; |
655 |
ForkJoinWorkerThread[] ws; // worker array |
656 |
int n; // upper bound of #workers |
657 |
if ((ws = p.workers) != null && (n = ws.length) > 1) { |
658 |
boolean canSteal = active; // shadow active status |
659 |
int r = seed; // extract seed once |
660 |
int mask = n - 1; |
661 |
int j = -n; // loop counter |
662 |
int k = r; // worker index, random if j < 0 |
663 |
for (;;) { |
664 |
ForkJoinWorkerThread v = ws[k & mask]; |
665 |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift |
666 |
if (v != null && v.base != v.sp) { |
667 |
if (canSteal || // ensure active status |
668 |
(canSteal = active = p.tryIncrementActiveCount())) { |
669 |
int b = v.base; // inline specialized deqTask |
670 |
ForkJoinTask<?>[] q; |
671 |
if (b != v.sp && (q = v.queue) != null) { |
672 |
ForkJoinTask<?> t; |
673 |
int i = (q.length - 1) & b; |
674 |
long u = (i << qShift) + qBase; // raw offset |
675 |
if ((t = q[i]) != null && v.base == b && |
676 |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
677 |
stolen = t; |
678 |
v.base = b + 1; |
679 |
seed = r; |
680 |
++stealCount; |
681 |
return t; |
682 |
} |
683 |
} |
684 |
} |
685 |
j = -n; |
686 |
k = r; // restart on contention |
687 |
} |
688 |
else if (++j <= 0) |
689 |
k = r; |
690 |
else if (j <= n) |
691 |
k += (n >>> 1) | 1; |
692 |
else |
693 |
break; |
694 |
} |
695 |
} |
696 |
return null; |
697 |
} |
698 |
|
699 |
// Run State management |
700 |
|
701 |
// status check methods used mainly by ForkJoinPool |
702 |
final boolean isTerminating() { return (runState & TERMINATING) != 0; } |
703 |
final boolean isTerminated() { return (runState & TERMINATED) != 0; } |
704 |
final boolean isSuspended() { return (runState & SUSPENDED) != 0; } |
705 |
final boolean isTrimmed() { return (runState & TRIMMED) != 0; } |
706 |
|
707 |
/** |
708 |
* Sets state to TERMINATING, also resuming if suspended. |
709 |
*/ |
710 |
final void shutdown() { |
711 |
for (;;) { |
712 |
int s = runState; |
713 |
if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended |
714 |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
715 |
(s & ~SUSPENDED) | |
716 |
(TRIMMED|TERMINATING))) { |
717 |
LockSupport.unpark(this); |
718 |
break; |
719 |
} |
720 |
} |
721 |
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
722 |
s | TERMINATING)) |
723 |
break; |
724 |
} |
725 |
} |
726 |
|
727 |
/** |
728 |
* Sets state to TERMINATED. Called only by this thread. |
729 |
*/ |
730 |
private void setTerminated() { |
731 |
int s; |
732 |
do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset, |
733 |
s = runState, |
734 |
s | (TERMINATING|TERMINATED))); |
735 |
} |
736 |
|
737 |
/** |
738 |
* Instrumented version of park used by ForkJoinPool.awaitEvent |
739 |
*/ |
740 |
final void doPark() { |
741 |
++parkCount; |
742 |
LockSupport.park(this); |
743 |
} |
744 |
|
745 |
/** |
746 |
* If suspended, tries to set status to unsuspended. |
747 |
* Caller must unpark to actually resume |
748 |
* |
749 |
* @return true if successful |
750 |
*/ |
751 |
final boolean tryUnsuspend() { |
752 |
int s = runState; |
753 |
if ((s & SUSPENDED) != 0) |
754 |
return UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
755 |
s & ~SUSPENDED); |
756 |
return false; |
757 |
} |
758 |
|
759 |
/** |
760 |
* Sets suspended status and blocks as spare until resumed, |
761 |
* shutdown, or timed out. |
762 |
* |
763 |
* @return false if trimmed |
764 |
*/ |
765 |
final boolean suspendAsSpare() { |
766 |
for (;;) { // set suspended unless terminating |
767 |
int s = runState; |
768 |
if ((s & TERMINATING) != 0) { // must kill |
769 |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
770 |
s | (TRIMMED | TERMINATING))) |
771 |
return false; |
772 |
} |
773 |
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
774 |
s | SUSPENDED)) |
775 |
break; |
776 |
} |
777 |
boolean timed; |
778 |
long nanos; |
779 |
long startTime; |
780 |
if (poolIndex < pool.parallelism) { |
781 |
timed = false; |
782 |
nanos = 0L; |
783 |
startTime = 0L; |
784 |
} |
785 |
else { |
786 |
timed = true; |
787 |
nanos = SPARE_KEEPALIVE_NANOS; |
788 |
startTime = System.nanoTime(); |
789 |
} |
790 |
pool.accumulateStealCount(this); |
791 |
lastEventCount = 0; // reset upon resume |
792 |
interrupted(); // clear/ignore interrupts |
793 |
while ((runState & SUSPENDED) != 0) { |
794 |
++parkCount; |
795 |
if (!timed) |
796 |
LockSupport.park(this); |
797 |
else if ((nanos -= (System.nanoTime() - startTime)) > 0) |
798 |
LockSupport.parkNanos(this, nanos); |
799 |
else { // try to trim on timeout |
800 |
int s = runState; |
801 |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
802 |
(s & ~SUSPENDED) | |
803 |
(TRIMMED|TERMINATING))) |
804 |
return false; |
805 |
} |
806 |
} |
807 |
return true; |
808 |
} |
809 |
|
810 |
// Misc support methods for ForkJoinPool |
811 |
|
812 |
/** |
813 |
* Returns an estimate of the number of tasks in the queue. Also |
814 |
* used by ForkJoinTask. |
815 |
*/ |
816 |
final int getQueueSize() { |
817 |
return -base + sp; |
818 |
} |
819 |
|
820 |
/** |
821 |
* Removes and cancels all tasks in queue. Can be called from any |
822 |
* thread. |
823 |
*/ |
824 |
final void cancelTasks() { |
825 |
while (base != sp) { |
826 |
ForkJoinTask<?> t = deqTask(); |
827 |
if (t != null) |
828 |
t.cancelIgnoringExceptions(); |
829 |
} |
830 |
} |
831 |
|
832 |
/** |
833 |
* Drains tasks to given collection c. |
834 |
* |
835 |
* @return the number of tasks drained |
836 |
*/ |
837 |
final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
838 |
int n = 0; |
839 |
while (base != sp) { |
840 |
ForkJoinTask<?> t = deqTask(); |
841 |
if (t != null) { |
842 |
c.add(t); |
843 |
++n; |
844 |
} |
845 |
} |
846 |
return n; |
847 |
} |
848 |
|
849 |
// Support methods for ForkJoinTask |
850 |
|
851 |
/** |
852 |
* Possibly runs some tasks and/or blocks, until task is done. |
853 |
* |
854 |
* @param joinMe the task to join |
855 |
*/ |
856 |
final void joinTask(ForkJoinTask<?> joinMe) { |
857 |
ForkJoinTask<?> prevJoining = joining; |
858 |
joining = joinMe; |
859 |
while (joinMe.status >= 0) { |
860 |
int s = sp; |
861 |
if (s == base) { |
862 |
nonlocalJoinTask(joinMe); |
863 |
break; |
864 |
} |
865 |
// process local task |
866 |
ForkJoinTask<?> t; |
867 |
ForkJoinTask<?>[] q = queue; |
868 |
int i = (q.length - 1) & --s; |
869 |
long u = (i << qShift) + qBase; // raw offset |
870 |
if ((t = q[i]) != null && |
871 |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
872 |
/* |
873 |
* This recheck (and similarly in nonlocalJoinTask) |
874 |
* handles cases where joinMe is independently |
875 |
* cancelled or forced even though there is other work |
876 |
* available. Back out of the pop by putting t back |
877 |
* into slot before we commit by setting sp. |
878 |
*/ |
879 |
if (joinMe.status < 0) { |
880 |
UNSAFE.putObjectVolatile(q, u, t); |
881 |
break; |
882 |
} |
883 |
sp = s; |
884 |
t.tryExec(); |
885 |
} |
886 |
} |
887 |
joining = prevJoining; |
888 |
} |
889 |
|
890 |
/** |
891 |
* Tries to locate and help perform tasks for a stealer of the |
892 |
* given task (or in turn one of its stealers), blocking (via |
893 |
* pool.tryAwaitJoin) upon failure to find work. Traces |
894 |
* stolen->joining links looking for a thread working on |
895 |
* a descendant of the given task and with a non-empty queue to |
896 |
* steal back and execute tasks from. Inhibits mutual steal chains |
897 |
* and scans on outer joins upon nesting to avoid unbounded |
898 |
* growth. Restarts search upon encountering inconsistencies. |
899 |
* Tries to block if two passes agree that there are no remaining |
900 |
* targets. |
901 |
* |
902 |
* @param joinMe the task to join |
903 |
*/ |
904 |
private void nonlocalJoinTask(ForkJoinTask<?> joinMe) { |
905 |
ForkJoinPool p = pool; |
906 |
int scans = p.parallelism; // give up if too many retries |
907 |
ForkJoinTask<?> bottom = null; // target seen when can't descend |
908 |
restart: while (joinMe.status >= 0) { |
909 |
ForkJoinTask<?> target = null; |
910 |
ForkJoinTask<?> next = joinMe; |
911 |
while (scans >= 0 && next != null) { |
912 |
--scans; |
913 |
target = next; |
914 |
next = null; |
915 |
ForkJoinWorkerThread v = null; |
916 |
ForkJoinWorkerThread[] ws = p.workers; |
917 |
int n = ws.length; |
918 |
for (int j = 0; j < n; ++j) { |
919 |
ForkJoinWorkerThread w = ws[j]; |
920 |
if (w != null && w.stolen == target) { |
921 |
v = w; |
922 |
break; |
923 |
} |
924 |
} |
925 |
if (v != null && v != this) { |
926 |
ForkJoinTask<?> prevStolen = stolen; |
927 |
int b; |
928 |
ForkJoinTask<?>[] q; |
929 |
while ((b = v.base) != v.sp && (q = v.queue) != null) { |
930 |
int i = (q.length - 1) & b; |
931 |
long u = (i << qShift) + qBase; |
932 |
ForkJoinTask<?> t = q[i]; |
933 |
if (target.status < 0) |
934 |
continue restart; |
935 |
if (t != null && v.base == b && |
936 |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
937 |
if (joinMe.status < 0) { |
938 |
UNSAFE.putObjectVolatile(q, u, t); |
939 |
return; // back out |
940 |
} |
941 |
stolen = t; |
942 |
v.base = b + 1; |
943 |
t.tryExec(); |
944 |
stolen = prevStolen; |
945 |
} |
946 |
if (joinMe.status < 0) |
947 |
return; |
948 |
} |
949 |
next = v.joining; |
950 |
} |
951 |
if (target.status < 0) |
952 |
continue restart; // inconsistent |
953 |
if (joinMe.status < 0) |
954 |
return; |
955 |
} |
956 |
|
957 |
if (bottom != target) |
958 |
bottom = target; // recheck landing spot |
959 |
else if (p.tryAwaitJoin(joinMe) < 0) |
960 |
return; // successfully blocked |
961 |
Thread.yield(); // tame spin in case too many active |
962 |
} |
963 |
} |
964 |
|
965 |
/** |
966 |
* Returns an estimate of the number of tasks, offset by a |
967 |
* function of number of idle workers. |
968 |
* |
969 |
* This method provides a cheap heuristic guide for task |
970 |
* partitioning when programmers, frameworks, tools, or languages |
971 |
* have little or no idea about task granularity. In essence by |
972 |
* offering this method, we ask users only about tradeoffs in |
973 |
* overhead vs expected throughput and its variance, rather than |
974 |
* how finely to partition tasks. |
975 |
* |
976 |
* In a steady state strict (tree-structured) computation, each |
977 |
* thread makes available for stealing enough tasks for other |
978 |
* threads to remain active. Inductively, if all threads play by |
979 |
* the same rules, each thread should make available only a |
980 |
* constant number of tasks. |
981 |
* |
982 |
* The minimum useful constant is just 1. But using a value of 1 |
983 |
* would require immediate replenishment upon each steal to |
984 |
* maintain enough tasks, which is infeasible. Further, |
985 |
* partitionings/granularities of offered tasks should minimize |
986 |
* steal rates, which in general means that threads nearer the top |
987 |
* of computation tree should generate more than those nearer the |
988 |
* bottom. In perfect steady state, each thread is at |
989 |
* approximately the same level of computation tree. However, |
990 |
* producing extra tasks amortizes the uncertainty of progress and |
991 |
* diffusion assumptions. |
992 |
* |
993 |
* So, users will want to use values larger, but not much larger |
994 |
* than 1 to both smooth over transient shortages and hedge |
995 |
* against uneven progress; as traded off against the cost of |
996 |
* extra task overhead. We leave the user to pick a threshold |
997 |
* value to compare with the results of this call to guide |
998 |
* decisions, but recommend values such as 3. |
999 |
* |
1000 |
* When all threads are active, it is on average OK to estimate |
1001 |
* surplus strictly locally. In steady-state, if one thread is |
1002 |
* maintaining say 2 surplus tasks, then so are others. So we can |
1003 |
* just use estimated queue length (although note that (sp - base) |
1004 |
* can be an overestimate because of stealers lagging increments |
1005 |
* of base). However, this strategy alone leads to serious |
1006 |
* mis-estimates in some non-steady-state conditions (ramp-up, |
1007 |
* ramp-down, other stalls). We can detect many of these by |
1008 |
* further considering the number of "idle" threads, that are |
1009 |
* known to have zero queued tasks, so compensate by a factor of |
1010 |
* (#idle/#active) threads. |
1011 |
*/ |
1012 |
final int getEstimatedSurplusTaskCount() { |
1013 |
return sp - base - pool.idlePerActive(); |
1014 |
} |
1015 |
|
1016 |
/** |
1017 |
* Gets and removes a local task. |
1018 |
* |
1019 |
* @return a task, if available |
1020 |
*/ |
1021 |
final ForkJoinTask<?> pollLocalTask() { |
1022 |
while (sp != base) { |
1023 |
if (active || (active = pool.tryIncrementActiveCount())) |
1024 |
return locallyFifo? locallyDeqTask() : popTask(); |
1025 |
} |
1026 |
return null; |
1027 |
} |
1028 |
|
1029 |
/** |
1030 |
* Gets and removes a local or stolen task. |
1031 |
* |
1032 |
* @return a task, if available |
1033 |
*/ |
1034 |
final ForkJoinTask<?> pollTask() { |
1035 |
ForkJoinTask<?> t; |
1036 |
return (t = pollLocalTask()) != null ? t : scan(); |
1037 |
} |
1038 |
|
1039 |
/** |
1040 |
* Runs tasks until {@code pool.isQuiescent()}. |
1041 |
*/ |
1042 |
final void helpQuiescePool() { |
1043 |
for (;;) { |
1044 |
ForkJoinTask<?> t = pollLocalTask(); |
1045 |
if (t != null || (t = scan()) != null) { |
1046 |
t.tryExec(); |
1047 |
stolen = null; |
1048 |
} |
1049 |
else { |
1050 |
ForkJoinPool p = pool; |
1051 |
if (active) { |
1052 |
active = false; // inactivate |
1053 |
do {} while (!p.tryDecrementActiveCount()); |
1054 |
} |
1055 |
if (p.isQuiescent()) { |
1056 |
active = true; // re-activate |
1057 |
do {} while (!p.tryIncrementActiveCount()); |
1058 |
return; |
1059 |
} |
1060 |
} |
1061 |
} |
1062 |
} |
1063 |
|
1064 |
// Unsafe mechanics |
1065 |
|
1066 |
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); |
1067 |
private static final long runStateOffset = |
1068 |
objectFieldOffset("runState", ForkJoinWorkerThread.class); |
1069 |
private static final long qBase = |
1070 |
UNSAFE.arrayBaseOffset(ForkJoinTask[].class); |
1071 |
private static final int qShift; |
1072 |
|
1073 |
static { |
1074 |
int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class); |
1075 |
if ((s & (s-1)) != 0) |
1076 |
throw new Error("data type scale not a power of two"); |
1077 |
qShift = 31 - Integer.numberOfLeadingZeros(s); |
1078 |
} |
1079 |
|
1080 |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1081 |
try { |
1082 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1083 |
} catch (NoSuchFieldException e) { |
1084 |
// Convert Exception to corresponding Error |
1085 |
NoSuchFieldError error = new NoSuchFieldError(field); |
1086 |
error.initCause(e); |
1087 |
throw error; |
1088 |
} |
1089 |
} |
1090 |
} |