6 |
|
|
7 |
|
package jsr166y; |
8 |
|
|
9 |
– |
import java.util.concurrent.*; |
10 |
– |
|
9 |
|
import java.util.Random; |
10 |
|
import java.util.Collection; |
11 |
|
import java.util.concurrent.locks.LockSupport; |
12 |
+ |
import java.util.concurrent.RejectedExecutionException; |
13 |
|
|
14 |
|
/** |
15 |
< |
* A thread managed by a {@link ForkJoinPool}. This class is |
16 |
< |
* subclassable solely for the sake of adding functionality -- there |
17 |
< |
* are no overridable methods dealing with scheduling or execution. |
18 |
< |
* However, you can override initialization and termination methods |
19 |
< |
* surrounding the main task processing loop. If you do create such a |
20 |
< |
* subclass, you will also need to supply a custom {@link |
21 |
< |
* ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code |
22 |
< |
* ForkJoinPool}. |
15 |
> |
* A thread managed by a {@link ForkJoinPool}, which executes |
16 |
> |
* {@link ForkJoinTask}s. |
17 |
> |
* This class is subclassable solely for the sake of adding |
18 |
> |
* functionality -- there are no overridable methods dealing with |
19 |
> |
* scheduling or execution. However, you can override initialization |
20 |
> |
* and termination methods surrounding the main task processing loop. |
21 |
> |
* If you do create such a subclass, you will also need to supply a |
22 |
> |
* custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it |
23 |
> |
* in a {@code ForkJoinPool}. |
24 |
|
* |
25 |
|
* @since 1.7 |
26 |
|
* @author Doug Lea |
83 |
|
* by the ForkJoinPool). This allows use in message-passing |
84 |
|
* frameworks in which tasks are never joined. |
85 |
|
* |
86 |
< |
* Efficient implementation of this approach currently relies on |
87 |
< |
* an uncomfortable amount of "Unsafe" mechanics. To maintain |
86 |
> |
* When a worker would otherwise be blocked waiting to join a |
87 |
> |
* task, it first tries a form of linear helping: Each worker |
88 |
> |
* records (in field currentSteal) the most recent task it stole |
89 |
> |
* from some other worker. Plus, it records (in field currentJoin) |
90 |
> |
* the task it is currently actively joining. Method joinTask uses |
91 |
> |
* these markers to try to find a worker to help (i.e., steal back |
92 |
> |
* a task from and execute it) that could hasten completion of the |
93 |
> |
* actively joined task. In essence, the joiner executes a task |
94 |
> |
* that would be on its own local deque had the to-be-joined task |
95 |
> |
* not been stolen. This may be seen as a conservative variant of |
96 |
> |
* the approach in Wagner & Calder "Leapfrogging: a portable |
97 |
> |
* technique for implementing efficient futures" SIGPLAN Notices, |
98 |
> |
* 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs |
99 |
> |
* in that: (1) We only maintain dependency links across workers |
100 |
> |
* upon steals, rather than use per-task bookkeeping. This may |
101 |
> |
* require a linear scan of workers array to locate stealers, but |
102 |
> |
* usually doesn't because stealers leave hints (that may become |
103 |
> |
* stale/wrong) of where to locate them. This isolates cost to |
104 |
> |
* when it is needed, rather than adding to per-task overhead. |
105 |
> |
* (2) It is "shallow", ignoring nesting and potentially cyclic |
106 |
> |
* mutual steals. (3) It is intentionally racy: field currentJoin |
107 |
> |
* is updated only while actively joining, which means that we |
108 |
> |
* miss links in the chain during long-lived tasks, GC stalls etc |
109 |
> |
* (which is OK since blocking in such cases is usually a good |
110 |
> |
* idea). (4) We bound the number of attempts to find work (see |
111 |
> |
* MAX_HELP_DEPTH) and fall back to suspending the worker and if |
112 |
> |
* necessary replacing it with a spare (see |
113 |
> |
* ForkJoinPool.awaitJoin). |
114 |
> |
* |
115 |
> |
* Efficient implementation of these algorithms currently relies |
116 |
> |
* on an uncomfortable amount of "Unsafe" mechanics. To maintain |
117 |
|
* correct orderings, reads and writes of variable base require |
118 |
|
* volatile ordering. Variable sp does not require volatile |
119 |
|
* writes but still needs store-ordering, which we accomplish by |
120 |
|
* pre-incrementing sp before filling the slot with an ordered |
121 |
|
* store. (Pre-incrementing also enables backouts used in |
122 |
< |
* scanWhileJoining.) Because they are protected by volatile base |
123 |
< |
* reads, reads of the queue array and its slots by other threads |
124 |
< |
* do not need volatile load semantics, but writes (in push) |
125 |
< |
* require store order and CASes (in pop and deq) require |
126 |
< |
* (volatile) CAS semantics. (Michael, Saraswat, and Vechev's |
127 |
< |
* algorithm has similar properties, but without support for |
128 |
< |
* nulling slots.) Since these combinations aren't supported |
129 |
< |
* using ordinary volatiles, the only way to accomplish these |
130 |
< |
* efficiently is to use direct Unsafe calls. (Using external |
131 |
< |
* AtomicIntegers and AtomicReferenceArrays for the indices and |
132 |
< |
* array is significantly slower because of memory locality and |
133 |
< |
* indirection effects.) |
122 |
> |
* joinTask.) Because they are protected by volatile base reads, |
123 |
> |
* reads of the queue array and its slots by other threads do not |
124 |
> |
* need volatile load semantics, but writes (in push) require |
125 |
> |
* store order and CASes (in pop and deq) require (volatile) CAS |
126 |
> |
* semantics. (Michael, Saraswat, and Vechev's algorithm has |
127 |
> |
* similar properties, but without support for nulling slots.) |
128 |
> |
* Since these combinations aren't supported using ordinary |
129 |
> |
* volatiles, the only way to accomplish these efficiently is to |
130 |
> |
* use direct Unsafe calls. (Using external AtomicIntegers and |
131 |
> |
* AtomicReferenceArrays for the indices and array is |
132 |
> |
* significantly slower because of memory locality and indirection |
133 |
> |
* effects.) |
134 |
|
* |
135 |
|
* Further, performance on most platforms is very sensitive to |
136 |
|
* placement and sizing of the (resizable) queue array. Even |
155 |
|
private static final Random seedGenerator = new Random(); |
156 |
|
|
157 |
|
/** |
158 |
< |
* The timeout value for suspending spares. Spare workers that |
159 |
< |
* remain unsignalled for more than this time may be trimmed |
160 |
< |
* (killed and removed from pool). Since our goal is to avoid |
161 |
< |
* long-term thread buildup, the exact value of timeout does not |
162 |
< |
* matter too much so long as it avoids most false-alarm timeouts |
134 |
< |
* under GC stalls or momentarily high system load. |
158 |
> |
* The maximum stolen->joining link depth allowed in helpJoinTask. |
159 |
> |
* Depths for legitimate chains are unbounded, but we use a fixed |
160 |
> |
* constant to avoid (otherwise unchecked) cycles and bound |
161 |
> |
* staleness of traversal parameters at the expense of sometimes |
162 |
> |
* blocking when we could be helping. |
163 |
|
*/ |
164 |
< |
private static final long SPARE_KEEPALIVE_NANOS = |
137 |
< |
5L * 1000L * 1000L * 1000L; // 5 secs |
164 |
> |
private static final int MAX_HELP_DEPTH = 8; |
165 |
|
|
166 |
|
/** |
167 |
|
* Capacity of work-stealing queue array upon initialization. |
172 |
|
|
173 |
|
/** |
174 |
|
* Maximum work-stealing queue array size. Must be less than or |
175 |
< |
* equal to 1 << 28 to ensure lack of index wraparound. (This |
176 |
< |
* is less than usual bounds, because we need leftshift by 3 |
177 |
< |
* to be in int range). |
175 |
> |
* equal to 1 << (31 - width of array entry) to ensure lack of |
176 |
> |
* index wraparound. The value is set in the static block |
177 |
> |
* at the end of this file after obtaining width. |
178 |
|
*/ |
179 |
< |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28; |
179 |
> |
private static final int MAXIMUM_QUEUE_CAPACITY; |
180 |
|
|
181 |
|
/** |
182 |
|
* The pool this thread works in. Accessed directly by ForkJoinTask. |
205 |
|
private int sp; |
206 |
|
|
207 |
|
/** |
208 |
+ |
* The index of most recent stealer, used as a hint to avoid |
209 |
+ |
* traversal in method helpJoinTask. This is only a hint because a |
210 |
+ |
* worker might have had multiple steals and this only holds one |
211 |
+ |
* of them (usually the most current). Declared non-volatile, |
212 |
+ |
* relying on other prevailing sync to keep reasonably current. |
213 |
+ |
*/ |
214 |
+ |
private int stealHint; |
215 |
+ |
|
216 |
+ |
/** |
217 |
|
* Run state of this worker. In addition to the usual run levels, |
218 |
|
* tracks if this worker is suspended as a spare, and if it was |
219 |
|
* killed (trimmed) while suspended. However, "active" status is |
220 |
< |
* maintained separately. |
220 |
> |
* maintained separately and modified only in conjunction with |
221 |
> |
* CASes of the pool's runState (which are currently sadly |
222 |
> |
* manually inlined for performance.) Accessed directly by pool |
223 |
> |
* to simplify checks for normal (zero) status. |
224 |
|
*/ |
225 |
< |
private volatile int runState; |
225 |
> |
volatile int runState; |
226 |
|
|
227 |
|
private static final int TERMINATING = 0x01; |
228 |
|
private static final int TERMINATED = 0x02; |
230 |
|
private static final int TRIMMED = 0x08; // killed while suspended |
231 |
|
|
232 |
|
/** |
233 |
< |
* Number of LockSupport.park calls to block this thread for |
234 |
< |
* suspension or event waits. Used for internal instrumention; |
196 |
< |
* currently not exported but included because volatile write upon |
197 |
< |
* park also provides a workaround for a JVM bug. |
198 |
< |
*/ |
199 |
< |
private volatile int parkCount; |
200 |
< |
|
201 |
< |
/** |
202 |
< |
* Number of steals, transferred and reset in pool callbacks pool |
203 |
< |
* when idle Accessed directly by pool. |
233 |
> |
* Number of steals. Directly accessed (and reset) by |
234 |
> |
* pool.tryAccumulateStealCount when idle. |
235 |
|
*/ |
236 |
|
int stealCount; |
237 |
|
|
249 |
|
|
250 |
|
/** |
251 |
|
* True if use local fifo, not default lifo, for local polling. |
252 |
< |
* Shadows value from ForkJoinPool, which resets it if changed |
222 |
< |
* pool-wide. |
252 |
> |
* Shadows value from ForkJoinPool. |
253 |
|
*/ |
254 |
< |
private boolean locallyFifo; |
254 |
> |
private final boolean locallyFifo; |
255 |
|
|
256 |
|
/** |
257 |
|
* Index of this worker in pool array. Set once by pool before |
267 |
|
int lastEventCount; |
268 |
|
|
269 |
|
/** |
270 |
< |
* Encoded index and event count of next event waiter. Used only |
271 |
< |
* by ForkJoinPool for managing event waiters. |
270 |
> |
* Encoded index and event count of next event waiter. Accessed |
271 |
> |
* only by ForkJoinPool for managing event waiters. |
272 |
|
*/ |
273 |
|
volatile long nextWaiter; |
274 |
|
|
275 |
|
/** |
276 |
+ |
* Number of times this thread suspended as spare. Accessed only |
277 |
+ |
* by pool. |
278 |
+ |
*/ |
279 |
+ |
int spareCount; |
280 |
+ |
|
281 |
+ |
/** |
282 |
+ |
* Encoded index and count of next spare waiter. Accessed only |
283 |
+ |
* by ForkJoinPool for managing spares. |
284 |
+ |
*/ |
285 |
+ |
volatile int nextSpare; |
286 |
+ |
|
287 |
+ |
/** |
288 |
+ |
* The task currently being joined, set only when actively trying |
289 |
+ |
* to help other stealers in helpJoinTask. Written only by this |
290 |
+ |
* thread, but read by others. |
291 |
+ |
*/ |
292 |
+ |
private volatile ForkJoinTask<?> currentJoin; |
293 |
+ |
|
294 |
+ |
/** |
295 |
+ |
* The task most recently stolen from another worker (or |
296 |
+ |
* submission queue). Written only by this thread, but read by |
297 |
+ |
* others. |
298 |
+ |
*/ |
299 |
+ |
private volatile ForkJoinTask<?> currentSteal; |
300 |
+ |
|
301 |
+ |
/** |
302 |
|
* Creates a ForkJoinWorkerThread operating in the given pool. |
303 |
|
* |
304 |
|
* @param pool the pool this thread works in |
305 |
|
* @throws NullPointerException if pool is null |
306 |
|
*/ |
307 |
|
protected ForkJoinWorkerThread(ForkJoinPool pool) { |
252 |
– |
if (pool == null) throw new NullPointerException(); |
308 |
|
this.pool = pool; |
309 |
+ |
this.locallyFifo = pool.locallyFifo; |
310 |
+ |
setDaemon(true); |
311 |
|
// To avoid exposing construction details to subclasses, |
312 |
|
// remaining initialization is in start() and onStart() |
313 |
|
} |
314 |
|
|
315 |
|
/** |
316 |
< |
* Performs additional initialization and starts this thread |
316 |
> |
* Performs additional initialization and starts this thread. |
317 |
|
*/ |
318 |
< |
final void start(int poolIndex, boolean locallyFifo, |
262 |
< |
UncaughtExceptionHandler ueh) { |
318 |
> |
final void start(int poolIndex, UncaughtExceptionHandler ueh) { |
319 |
|
this.poolIndex = poolIndex; |
264 |
– |
this.locallyFifo = locallyFifo; |
320 |
|
if (ueh != null) |
321 |
|
setUncaughtExceptionHandler(ueh); |
267 |
– |
setDaemon(true); |
322 |
|
start(); |
323 |
|
} |
324 |
|
|
349 |
|
/** |
350 |
|
* Initializes internal state after construction but before |
351 |
|
* processing any tasks. If you override this method, you must |
352 |
< |
* invoke super.onStart() at the beginning of the method. |
352 |
> |
* invoke {@code super.onStart()} at the beginning of the method. |
353 |
|
* Initialization requires care: Most fields must have legal |
354 |
|
* default values, to ensure that attempted accesses from other |
355 |
|
* threads work correctly even before this thread starts |
359 |
|
int rs = seedGenerator.nextInt(); |
360 |
|
seed = rs == 0? 1 : rs; // seed must be nonzero |
361 |
|
|
362 |
< |
// Allocate name string and queue array in this thread |
362 |
> |
// Allocate name string and arrays in this thread |
363 |
|
String pid = Integer.toString(pool.getPoolNumber()); |
364 |
|
String wid = Integer.toString(poolIndex); |
365 |
|
setName("ForkJoinPool-" + pid + "-worker-" + wid); |
377 |
|
*/ |
378 |
|
protected void onTermination(Throwable exception) { |
379 |
|
try { |
380 |
+ |
ForkJoinPool p = pool; |
381 |
+ |
if (active) { |
382 |
+ |
int a; // inline p.tryDecrementActiveCount |
383 |
+ |
active = false; |
384 |
+ |
do {} while (!UNSAFE.compareAndSwapInt |
385 |
+ |
(p, poolRunStateOffset, a = p.runState, a - 1)); |
386 |
+ |
} |
387 |
|
cancelTasks(); |
388 |
|
setTerminated(); |
389 |
< |
pool.workerTerminated(this); |
389 |
> |
p.workerTerminated(this); |
390 |
|
} catch (Throwable ex) { // Shouldn't ever happen |
391 |
|
if (exception == null) // but if so, at least rethrown |
392 |
|
exception = ex; |
399 |
|
/** |
400 |
|
* This method is required to be public, but should never be |
401 |
|
* called explicitly. It performs the main run loop to execute |
402 |
< |
* ForkJoinTasks. |
402 |
> |
* {@link ForkJoinTask}s. |
403 |
|
*/ |
404 |
|
public void run() { |
405 |
|
Throwable exception = null; |
416 |
|
// helpers for run() |
417 |
|
|
418 |
|
/** |
419 |
< |
* Find and execute tasks and check status while running |
419 |
> |
* Finds and executes tasks, and checks status while running. |
420 |
|
*/ |
421 |
|
private void mainLoop() { |
422 |
< |
boolean ran = false; // true if ran task in last loop iter |
362 |
< |
boolean prevRan = false; // true if ran on last or previous step |
422 |
> |
boolean ran = false; // true if ran a task on last step |
423 |
|
ForkJoinPool p = pool; |
424 |
|
for (;;) { |
425 |
< |
p.preStep(this, prevRan); |
425 |
> |
p.preStep(this, ran); |
426 |
|
if (runState != 0) |
427 |
< |
return; |
428 |
< |
ForkJoinTask<?> t; // try to get and run stolen or submitted task |
369 |
< |
if ((t = scan()) != null || (t = pollSubmission()) != null) { |
370 |
< |
t.tryExec(); |
371 |
< |
if (base != sp) |
372 |
< |
runLocalTasks(); |
373 |
< |
prevRan = ran = true; |
374 |
< |
} |
375 |
< |
else { |
376 |
< |
prevRan = ran; |
377 |
< |
ran = false; |
378 |
< |
} |
427 |
> |
break; |
428 |
> |
ran = tryExecSteal() || tryExecSubmission(); |
429 |
|
} |
430 |
|
} |
431 |
|
|
432 |
|
/** |
433 |
< |
* Runs local tasks until queue is empty or shut down. Call only |
434 |
< |
* while active. |
433 |
> |
* Tries to steal a task and execute it. |
434 |
> |
* |
435 |
> |
* @return true if ran a task |
436 |
|
*/ |
437 |
< |
private void runLocalTasks() { |
438 |
< |
while (runState == 0) { |
439 |
< |
ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask(); |
440 |
< |
if (t != null) |
441 |
< |
t.tryExec(); |
442 |
< |
else if (base == sp) |
443 |
< |
break; |
437 |
> |
private boolean tryExecSteal() { |
438 |
> |
ForkJoinTask<?> t; |
439 |
> |
if ((t = scan()) != null) { |
440 |
> |
t.quietlyExec(); |
441 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
442 |
> |
if (sp != base) |
443 |
> |
execLocalTasks(); |
444 |
> |
return true; |
445 |
|
} |
446 |
+ |
return false; |
447 |
|
} |
448 |
|
|
449 |
|
/** |
450 |
< |
* If a submission exists, try to activate and take it |
450 |
> |
* If a submission exists, try to activate and run it. |
451 |
|
* |
452 |
< |
* @return a task, if available |
452 |
> |
* @return true if ran a task |
453 |
|
*/ |
454 |
< |
private ForkJoinTask<?> pollSubmission() { |
454 |
> |
private boolean tryExecSubmission() { |
455 |
|
ForkJoinPool p = pool; |
456 |
+ |
// This loop is needed in case attempt to activate fails, in |
457 |
+ |
// which case we only retry if there still appears to be a |
458 |
+ |
// submission. |
459 |
|
while (p.hasQueuedSubmissions()) { |
460 |
< |
if (active || (active = p.tryIncrementActiveCount())) { |
461 |
< |
ForkJoinTask<?> t = p.pollSubmission(); |
462 |
< |
return t != null ? t : scan(); // if missed, rescan |
460 |
> |
ForkJoinTask<?> t; int a; |
461 |
> |
if (active || // inline p.tryIncrementActiveCount |
462 |
> |
(active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
463 |
> |
a = p.runState, a + 1))) { |
464 |
> |
if ((t = p.pollSubmission()) != null) { |
465 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, t); |
466 |
> |
t.quietlyExec(); |
467 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
468 |
> |
if (sp != base) |
469 |
> |
execLocalTasks(); |
470 |
> |
return true; |
471 |
> |
} |
472 |
|
} |
473 |
|
} |
474 |
< |
return null; |
474 |
> |
return false; |
475 |
> |
} |
476 |
> |
|
477 |
> |
/** |
478 |
> |
* Runs local tasks until queue is empty or shut down. Call only |
479 |
> |
* while active. |
480 |
> |
*/ |
481 |
> |
private void execLocalTasks() { |
482 |
> |
while (runState == 0) { |
483 |
> |
ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask(); |
484 |
> |
if (t != null) |
485 |
> |
t.quietlyExec(); |
486 |
> |
else if (sp == base) |
487 |
> |
break; |
488 |
> |
} |
489 |
|
} |
490 |
|
|
491 |
|
/* |
492 |
|
* Intrinsics-based atomic writes for queue slots. These are |
493 |
< |
* basically the same as methods in AtomicObjectArray, but |
493 |
> |
* basically the same as methods in AtomicReferenceArray, but |
494 |
|
* specialized for (1) ForkJoinTask elements (2) requirement that |
495 |
|
* nullness and bounds checks have already been performed by |
496 |
|
* callers and (3) effective offsets are known not to overflow |
497 |
|
* from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't |
498 |
|
* need corresponding version for reads: plain array reads are OK |
499 |
< |
* because they protected by other volatile reads and are |
499 |
> |
* because they are protected by other volatile reads and are |
500 |
|
* confirmed by CASes. |
501 |
|
* |
502 |
|
* Most uses don't actually call these methods, but instead contain |
520 |
|
* range. This method is used only during resets and backouts. |
521 |
|
*/ |
522 |
|
private static final void writeSlot(ForkJoinTask<?>[] q, int i, |
523 |
< |
ForkJoinTask<?> t) { |
523 |
> |
ForkJoinTask<?> t) { |
524 |
|
UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t); |
525 |
|
} |
526 |
|
|
545 |
|
/** |
546 |
|
* Tries to take a task from the base of the queue, failing if |
547 |
|
* empty or contended. Note: Specializations of this code appear |
548 |
< |
* in scan and scanWhileJoining. |
548 |
> |
* in locallyDeqTask and elsewhere. |
549 |
|
* |
550 |
|
* @return a task, or null if none or contended |
551 |
|
*/ |
553 |
|
ForkJoinTask<?> t; |
554 |
|
ForkJoinTask<?>[] q; |
555 |
|
int b, i; |
556 |
< |
if ((b = base) != sp && |
556 |
> |
if (sp != (b = base) && |
557 |
|
(q = queue) != null && // must read q after b |
558 |
< |
(t = q[i = (q.length - 1) & b]) != null && |
558 |
> |
(t = q[i = (q.length - 1) & b]) != null && base == b && |
559 |
|
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
560 |
|
base = b + 1; |
561 |
|
return t; |
565 |
|
|
566 |
|
/** |
567 |
|
* Tries to take a task from the base of own queue. Assumes active |
568 |
< |
* status. Called only by current thread. |
568 |
> |
* status. Called only by this thread. |
569 |
|
* |
570 |
|
* @return a task, or null if none |
571 |
|
*/ |
575 |
|
ForkJoinTask<?> t; |
576 |
|
int b, i; |
577 |
|
while (sp != (b = base)) { |
578 |
< |
if ((t = q[i = (q.length - 1) & b]) != null && |
578 |
> |
if ((t = q[i = (q.length - 1) & b]) != null && base == b && |
579 |
|
UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, |
580 |
|
t, null)) { |
581 |
|
base = b + 1; |
588 |
|
|
589 |
|
/** |
590 |
|
* Returns a popped task, or null if empty. Assumes active status. |
591 |
< |
* Called only by current thread. (Note: a specialization of this |
513 |
< |
* code appears in popWhileJoining.) |
591 |
> |
* Called only by this thread. |
592 |
|
*/ |
593 |
< |
final ForkJoinTask<?> popTask() { |
594 |
< |
int s; |
595 |
< |
ForkJoinTask<?>[] q; |
596 |
< |
if (base != (s = sp) && (q = queue) != null) { |
597 |
< |
int i = (q.length - 1) & --s; |
598 |
< |
ForkJoinTask<?> t = q[i]; |
599 |
< |
if (t != null && UNSAFE.compareAndSwapObject |
600 |
< |
(q, (i << qShift) + qBase, t, null)) { |
601 |
< |
sp = s; |
602 |
< |
return t; |
593 |
> |
private ForkJoinTask<?> popTask() { |
594 |
> |
ForkJoinTask<?>[] q = queue; |
595 |
> |
if (q != null) { |
596 |
> |
int s; |
597 |
> |
while ((s = sp) != base) { |
598 |
> |
int i = (q.length - 1) & --s; |
599 |
> |
long u = (i << qShift) + qBase; // raw offset |
600 |
> |
ForkJoinTask<?> t = q[i]; |
601 |
> |
if (t == null) // lost to stealer |
602 |
> |
break; |
603 |
> |
if (UNSAFE.compareAndSwapObject(q, u, t, null)) { |
604 |
> |
/* |
605 |
> |
* Note: here and in related methods, as a |
606 |
> |
* performance (not correctness) issue, we'd like |
607 |
> |
* to encourage compiler not to arbitrarily |
608 |
> |
* postpone setting sp after successful CAS. |
609 |
> |
* Currently there is no intrinsic for arranging |
610 |
> |
* this, but using Unsafe putOrderedInt may be a |
611 |
> |
* preferable strategy on some compilers even |
612 |
> |
* though its main effect is a pre-, not post- |
613 |
> |
* fence. To simplify possible changes, the option |
614 |
> |
* is left in comments next to the associated |
615 |
> |
* assignments. |
616 |
> |
*/ |
617 |
> |
sp = s; // putOrderedInt may encourage more timely write |
618 |
> |
// UNSAFE.putOrderedInt(this, spOffset, s); |
619 |
> |
return t; |
620 |
> |
} |
621 |
|
} |
622 |
|
} |
623 |
|
return null; |
625 |
|
|
626 |
|
/** |
627 |
|
* Specialized version of popTask to pop only if topmost element |
628 |
< |
* is the given task. Called only by current thread while |
533 |
< |
* active. |
628 |
> |
* is the given task. Called only by this thread while active. |
629 |
|
* |
630 |
|
* @param t the task. Caller must ensure non-null. |
631 |
|
*/ |
632 |
|
final boolean unpushTask(ForkJoinTask<?> t) { |
633 |
|
int s; |
634 |
< |
ForkJoinTask<?>[] q; |
635 |
< |
if (base != (s = sp) && (q = queue) != null && |
634 |
> |
ForkJoinTask<?>[] q = queue; |
635 |
> |
if ((s = sp) != base && q != null && |
636 |
|
UNSAFE.compareAndSwapObject |
637 |
|
(q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) { |
638 |
< |
sp = s; |
638 |
> |
sp = s; // putOrderedInt may encourage more timely write |
639 |
> |
// UNSAFE.putOrderedInt(this, spOffset, s); |
640 |
|
return true; |
641 |
|
} |
642 |
|
return false; |
643 |
|
} |
644 |
|
|
645 |
|
/** |
646 |
< |
* Returns next task or null if empty or contended |
646 |
> |
* Returns next task, or null if empty or contended. |
647 |
|
*/ |
648 |
|
final ForkJoinTask<?> peekTask() { |
649 |
|
ForkJoinTask<?>[] q = queue; |
685 |
|
* Computes next value for random victim probe in scan(). Scans |
686 |
|
* don't require a very high quality generator, but also not a |
687 |
|
* crummy one. Marsaglia xor-shift is cheap and works well enough. |
688 |
< |
* Note: This is manually inlined in scan() |
688 |
> |
* Note: This is manually inlined in scan(). |
689 |
|
*/ |
690 |
|
private static final int xorShift(int r) { |
691 |
|
r ^= r << 13; |
724 |
|
for (;;) { |
725 |
|
ForkJoinWorkerThread v = ws[k & mask]; |
726 |
|
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift |
727 |
< |
if (v != null && v.base != v.sp) { |
728 |
< |
int b, i; // inline specialized deqTask |
729 |
< |
ForkJoinTask<?>[] q; |
730 |
< |
ForkJoinTask<?> t; |
731 |
< |
if ((canSteal || // ensure active status |
732 |
< |
(canSteal = active = p.tryIncrementActiveCount())) && |
733 |
< |
(q = v.queue) != null && |
734 |
< |
(t = q[i = (q.length - 1) & (b = v.base)]) != null && |
735 |
< |
UNSAFE.compareAndSwapObject |
736 |
< |
(q, (i << qShift) + qBase, t, null)) { |
737 |
< |
v.base = b + 1; |
738 |
< |
seed = r; |
739 |
< |
++stealCount; |
740 |
< |
return t; |
727 |
> |
ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a; |
728 |
> |
if (v != null && (b = v.base) != v.sp && |
729 |
> |
(q = v.queue) != null) { |
730 |
> |
int i = (q.length - 1) & b; |
731 |
> |
long u = (i << qShift) + qBase; // raw offset |
732 |
> |
int pid = poolIndex; |
733 |
> |
if ((t = q[i]) != null) { |
734 |
> |
if (!canSteal && // inline p.tryIncrementActiveCount |
735 |
> |
UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
736 |
> |
a = p.runState, a + 1)) |
737 |
> |
canSteal = active = true; |
738 |
> |
if (canSteal && v.base == b++ && |
739 |
> |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
740 |
> |
v.base = b; |
741 |
> |
v.stealHint = pid; |
742 |
> |
UNSAFE.putOrderedObject(this, |
743 |
> |
currentStealOffset, t); |
744 |
> |
seed = r; |
745 |
> |
++stealCount; |
746 |
> |
return t; |
747 |
> |
} |
748 |
|
} |
749 |
|
j = -n; |
750 |
|
k = r; // restart on contention |
763 |
|
// Run State management |
764 |
|
|
765 |
|
// status check methods used mainly by ForkJoinPool |
766 |
< |
final boolean isTerminating() { return (runState & TERMINATING) != 0; } |
767 |
< |
final boolean isTerminated() { return (runState & TERMINATED) != 0; } |
768 |
< |
final boolean isSuspended() { return (runState & SUSPENDED) != 0; } |
769 |
< |
final boolean isTrimmed() { return (runState & TRIMMED) != 0; } |
766 |
> |
final boolean isRunning() { return runState == 0; } |
767 |
> |
final boolean isTerminated() { return (runState & TERMINATED) != 0; } |
768 |
> |
final boolean isSuspended() { return (runState & SUSPENDED) != 0; } |
769 |
> |
final boolean isTrimmed() { return (runState & TRIMMED) != 0; } |
770 |
> |
|
771 |
> |
final boolean isTerminating() { |
772 |
> |
if ((runState & TERMINATING) != 0) |
773 |
> |
return true; |
774 |
> |
if (pool.isAtLeastTerminating()) { // propagate pool state |
775 |
> |
shutdown(); |
776 |
> |
return true; |
777 |
> |
} |
778 |
> |
return false; |
779 |
> |
} |
780 |
|
|
781 |
|
/** |
782 |
< |
* Sets state to TERMINATING, also resuming if suspended. |
782 |
> |
* Sets state to TERMINATING. Does NOT unpark or interrupt |
783 |
> |
* to wake up if currently blocked. Callers must do so if desired. |
784 |
|
*/ |
785 |
|
final void shutdown() { |
786 |
|
for (;;) { |
787 |
|
int s = runState; |
788 |
+ |
if ((s & (TERMINATING|TERMINATED)) != 0) |
789 |
+ |
break; |
790 |
|
if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended |
791 |
|
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
792 |
|
(s & ~SUSPENDED) | |
793 |
< |
(TRIMMED|TERMINATING))) { |
678 |
< |
LockSupport.unpark(this); |
793 |
> |
(TRIMMED|TERMINATING))) |
794 |
|
break; |
680 |
– |
} |
795 |
|
} |
796 |
|
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
797 |
|
s | TERMINATING)) |
800 |
|
} |
801 |
|
|
802 |
|
/** |
803 |
< |
* Sets state to TERMINATED. Called only by this thread. |
803 |
> |
* Sets state to TERMINATED. Called only by onTermination(). |
804 |
|
*/ |
805 |
|
private void setTerminated() { |
806 |
|
int s; |
810 |
|
} |
811 |
|
|
812 |
|
/** |
699 |
– |
* Instrumented version of park. Also used by ForkJoinPool.awaitEvent |
700 |
– |
*/ |
701 |
– |
final void doPark() { |
702 |
– |
++parkCount; |
703 |
– |
LockSupport.park(this); |
704 |
– |
} |
705 |
– |
|
706 |
– |
/** |
813 |
|
* If suspended, tries to set status to unsuspended. |
814 |
< |
* Caller must unpark to actually resume |
814 |
> |
* Does NOT wake up if blocked. |
815 |
|
* |
816 |
|
* @return true if successful |
817 |
|
*/ |
818 |
|
final boolean tryUnsuspend() { |
819 |
|
int s; |
820 |
< |
return (((s = runState) & SUSPENDED) != 0 && |
821 |
< |
UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
822 |
< |
s & ~SUSPENDED)); |
820 |
> |
while (((s = runState) & SUSPENDED) != 0) { |
821 |
> |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
822 |
> |
s & ~SUSPENDED)) |
823 |
> |
return true; |
824 |
> |
} |
825 |
> |
return false; |
826 |
|
} |
827 |
|
|
828 |
|
/** |
829 |
< |
* Sets suspended status and blocks as spare until resumed, |
830 |
< |
* shutdown, or timed out. |
722 |
< |
* |
723 |
< |
* @return false if trimmed |
829 |
> |
* Sets suspended status and blocks as spare until resumed |
830 |
> |
* or shutdown. |
831 |
|
*/ |
832 |
< |
final boolean suspendAsSpare() { |
833 |
< |
for (;;) { // set suspended unless terminating |
832 |
> |
final void suspendAsSpare() { |
833 |
> |
for (;;) { // set suspended unless terminating |
834 |
|
int s = runState; |
835 |
|
if ((s & TERMINATING) != 0) { // must kill |
836 |
|
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
837 |
|
s | (TRIMMED | TERMINATING))) |
838 |
< |
return false; |
838 |
> |
return; |
839 |
|
} |
840 |
|
else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
841 |
|
s | SUSPENDED)) |
842 |
|
break; |
843 |
|
} |
737 |
– |
lastEventCount = 0; // reset upon resume |
844 |
|
ForkJoinPool p = pool; |
845 |
< |
p.releaseWaiters(); // help others progress |
740 |
< |
p.accumulateStealCount(this); |
741 |
< |
interrupted(); // clear/ignore interrupts |
742 |
< |
if (poolIndex < p.getParallelism()) { // untimed wait |
743 |
< |
while ((runState & SUSPENDED) != 0) |
744 |
< |
doPark(); |
745 |
< |
return true; |
746 |
< |
} |
747 |
< |
return timedSuspend(); // timed wait if apparently non-core |
748 |
< |
} |
749 |
< |
|
750 |
< |
/** |
751 |
< |
* Blocks as spare until resumed or timed out |
752 |
< |
* @return false if trimmed |
753 |
< |
*/ |
754 |
< |
private boolean timedSuspend() { |
755 |
< |
long nanos = SPARE_KEEPALIVE_NANOS; |
756 |
< |
long startTime = System.nanoTime(); |
845 |
> |
p.pushSpare(this); |
846 |
|
while ((runState & SUSPENDED) != 0) { |
847 |
< |
++parkCount; |
848 |
< |
if ((nanos -= (System.nanoTime() - startTime)) > 0) |
849 |
< |
LockSupport.parkNanos(this, nanos); |
850 |
< |
else { // try to trim on timeout |
851 |
< |
int s = runState; |
763 |
< |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, |
764 |
< |
(s & ~SUSPENDED) | |
765 |
< |
(TRIMMED|TERMINATING))) |
766 |
< |
return false; |
847 |
> |
if (p.tryAccumulateStealCount(this)) { |
848 |
> |
interrupted(); // clear/ignore interrupts |
849 |
> |
if ((runState & SUSPENDED) == 0) |
850 |
> |
break; |
851 |
> |
LockSupport.park(this); |
852 |
|
} |
853 |
|
} |
769 |
– |
return true; |
854 |
|
} |
855 |
|
|
856 |
|
// Misc support methods for ForkJoinPool |
860 |
|
* used by ForkJoinTask. |
861 |
|
*/ |
862 |
|
final int getQueueSize() { |
863 |
< |
return -base + sp; |
864 |
< |
} |
781 |
< |
|
782 |
< |
/** |
783 |
< |
* Set locallyFifo mode. Called only by ForkJoinPool |
784 |
< |
*/ |
785 |
< |
final void setAsyncMode(boolean async) { |
786 |
< |
locallyFifo = async; |
863 |
> |
int n; // external calls must read base first |
864 |
> |
return (n = -base + sp) <= 0 ? 0 : n; |
865 |
|
} |
866 |
|
|
867 |
|
/** |
869 |
|
* thread. |
870 |
|
*/ |
871 |
|
final void cancelTasks() { |
872 |
+ |
ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks |
873 |
+ |
if (cj != null && cj.status >= 0) { |
874 |
+ |
cj.cancelIgnoringExceptions(); |
875 |
+ |
try { |
876 |
+ |
this.interrupt(); // awaken wait |
877 |
+ |
} catch (SecurityException ignore) { |
878 |
+ |
} |
879 |
+ |
} |
880 |
+ |
ForkJoinTask<?> cs = currentSteal; |
881 |
+ |
if (cs != null && cs.status >= 0) |
882 |
+ |
cs.cancelIgnoringExceptions(); |
883 |
|
while (base != sp) { |
884 |
|
ForkJoinTask<?> t = deqTask(); |
885 |
|
if (t != null) |
907 |
|
// Support methods for ForkJoinTask |
908 |
|
|
909 |
|
/** |
910 |
+ |
* Gets and removes a local task. |
911 |
+ |
* |
912 |
+ |
* @return a task, if available |
913 |
+ |
*/ |
914 |
+ |
final ForkJoinTask<?> pollLocalTask() { |
915 |
+ |
ForkJoinPool p = pool; |
916 |
+ |
while (sp != base) { |
917 |
+ |
int a; // inline p.tryIncrementActiveCount |
918 |
+ |
if (active || |
919 |
+ |
(active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset, |
920 |
+ |
a = p.runState, a + 1))) |
921 |
+ |
return locallyFifo ? locallyDeqTask() : popTask(); |
922 |
+ |
} |
923 |
+ |
return null; |
924 |
+ |
} |
925 |
+ |
|
926 |
+ |
/** |
927 |
+ |
* Gets and removes a local or stolen task. |
928 |
+ |
* |
929 |
+ |
* @return a task, if available |
930 |
+ |
*/ |
931 |
+ |
final ForkJoinTask<?> pollTask() { |
932 |
+ |
ForkJoinTask<?> t = pollLocalTask(); |
933 |
+ |
if (t == null) { |
934 |
+ |
t = scan(); |
935 |
+ |
// cannot retain/track/help steal |
936 |
+ |
UNSAFE.putOrderedObject(this, currentStealOffset, null); |
937 |
+ |
} |
938 |
+ |
return t; |
939 |
+ |
} |
940 |
+ |
|
941 |
+ |
/** |
942 |
+ |
* Possibly runs some tasks and/or blocks, until task is done. |
943 |
+ |
* |
944 |
+ |
* @param joinMe the task to join |
945 |
+ |
* @param timed true if use timed wait |
946 |
+ |
* @param nanos wait time if timed |
947 |
+ |
*/ |
948 |
+ |
final void joinTask(ForkJoinTask<?> joinMe, boolean timed, long nanos) { |
949 |
+ |
// currentJoin only written by this thread; only need ordered store |
950 |
+ |
ForkJoinTask<?> prevJoin = currentJoin; |
951 |
+ |
UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe); |
952 |
+ |
pool.awaitJoin(joinMe, this, timed, nanos); |
953 |
+ |
UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin); |
954 |
+ |
} |
955 |
+ |
|
956 |
+ |
/** |
957 |
+ |
* Tries to locate and help perform tasks for a stealer of the |
958 |
+ |
* given task, or in turn one of its stealers. Traces |
959 |
+ |
* currentSteal->currentJoin links looking for a thread working on |
960 |
+ |
* a descendant of the given task and with a non-empty queue to |
961 |
+ |
* steal back and execute tasks from. |
962 |
+ |
* |
963 |
+ |
* The implementation is very branchy to cope with potential |
964 |
+ |
* inconsistencies or loops encountering chains that are stale, |
965 |
+ |
* unknown, or of length greater than MAX_HELP_DEPTH links. All |
966 |
+ |
* of these cases are dealt with by just returning back to the |
967 |
+ |
* caller, who is expected to retry if other join mechanisms also |
968 |
+ |
* don't work out. |
969 |
+ |
* |
970 |
+ |
* @param joinMe the task to join |
971 |
+ |
* @param running if false, then must update pool count upon |
972 |
+ |
* running a task |
973 |
+ |
* @return value of running on exit |
974 |
+ |
*/ |
975 |
+ |
final boolean helpJoinTask(ForkJoinTask<?> joinMe, boolean running) { |
976 |
+ |
/* |
977 |
+ |
* Initial checks to (1) abort if terminating; (2) clean out |
978 |
+ |
* old cancelled tasks from local queue; (3) if joinMe is next |
979 |
+ |
* task, run it; (4) omit scan if local queue nonempty (since |
980 |
+ |
* it may contain non-descendents of joinMe). |
981 |
+ |
*/ |
982 |
+ |
ForkJoinPool p = pool; |
983 |
+ |
for (;;) { |
984 |
+ |
ForkJoinTask<?>[] q; |
985 |
+ |
int s; |
986 |
+ |
if (joinMe.status < 0) |
987 |
+ |
return running; |
988 |
+ |
else if ((runState & TERMINATING) != 0) |
989 |
+ |
joinMe.cancelIgnoringExceptions(); |
990 |
+ |
else if ((s = sp) == base || (q = queue) == null) |
991 |
+ |
break; // queue empty |
992 |
+ |
else { |
993 |
+ |
int i = (q.length - 1) & --s; |
994 |
+ |
long u = (i << qShift) + qBase; // raw offset |
995 |
+ |
ForkJoinTask<?> t = q[i]; |
996 |
+ |
if (t == null) |
997 |
+ |
break; // lost to a stealer |
998 |
+ |
else if (t != joinMe && t.status >= 0) |
999 |
+ |
return running; // cannot safely help |
1000 |
+ |
else if ((running || |
1001 |
+ |
(running = p.tryIncrementRunningCount())) && |
1002 |
+ |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
1003 |
+ |
sp = s; // putOrderedInt may encourage more timely write |
1004 |
+ |
// UNSAFE.putOrderedInt(this, spOffset, s); |
1005 |
+ |
if (t.status >= 0) |
1006 |
+ |
t.quietlyExec(); |
1007 |
+ |
} |
1008 |
+ |
} |
1009 |
+ |
} |
1010 |
+ |
|
1011 |
+ |
int n; // worker array size |
1012 |
+ |
ForkJoinWorkerThread[] ws = p.workers; |
1013 |
+ |
if (ws != null && (n = ws.length) > 1) { // need at least 2 workers |
1014 |
+ |
ForkJoinTask<?> task = joinMe; // base of chain |
1015 |
+ |
ForkJoinWorkerThread thread = this; // thread with stolen task |
1016 |
+ |
|
1017 |
+ |
outer:for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length |
1018 |
+ |
// Try to find v, the stealer of task, by first using hint |
1019 |
+ |
ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)]; |
1020 |
+ |
if (v == null || v.currentSteal != task) { |
1021 |
+ |
for (int j = 0; ; ++j) { // search array |
1022 |
+ |
if (j < n) { |
1023 |
+ |
ForkJoinTask<?> vs; |
1024 |
+ |
if ((v = ws[j]) != null && |
1025 |
+ |
(vs = v.currentSteal) != null) { |
1026 |
+ |
if (joinMe.status < 0) |
1027 |
+ |
break outer; |
1028 |
+ |
if (vs == task) { |
1029 |
+ |
if (task.status < 0) |
1030 |
+ |
break outer; // stale |
1031 |
+ |
thread.stealHint = j; |
1032 |
+ |
break; // save hint for next time |
1033 |
+ |
} |
1034 |
+ |
} |
1035 |
+ |
} |
1036 |
+ |
else |
1037 |
+ |
break outer; // no stealer |
1038 |
+ |
} |
1039 |
+ |
} |
1040 |
+ |
|
1041 |
+ |
// Try to help v, using specialized form of deqTask |
1042 |
+ |
for (;;) { |
1043 |
+ |
if (joinMe.status < 0) |
1044 |
+ |
break outer; |
1045 |
+ |
int b = v.base; |
1046 |
+ |
ForkJoinTask<?>[] q = v.queue; |
1047 |
+ |
if (b == v.sp || q == null) |
1048 |
+ |
break; // empty |
1049 |
+ |
int i = (q.length - 1) & b; |
1050 |
+ |
long u = (i << qShift) + qBase; |
1051 |
+ |
ForkJoinTask<?> t = q[i]; |
1052 |
+ |
if (task.status < 0) |
1053 |
+ |
break outer; // stale |
1054 |
+ |
if (t != null && |
1055 |
+ |
(running || |
1056 |
+ |
(running = p.tryIncrementRunningCount())) && |
1057 |
+ |
v.base == b++ && |
1058 |
+ |
UNSAFE.compareAndSwapObject(q, u, t, null)) { |
1059 |
+ |
if (t != joinMe && joinMe.status < 0) { |
1060 |
+ |
UNSAFE.putObjectVolatile(q, u, t); |
1061 |
+ |
break outer; // joinMe cancelled; back out |
1062 |
+ |
} |
1063 |
+ |
v.base = b; |
1064 |
+ |
if (t.status >= 0) { |
1065 |
+ |
ForkJoinTask<?> ps = currentSteal; |
1066 |
+ |
int pid = poolIndex; |
1067 |
+ |
v.stealHint = pid; |
1068 |
+ |
UNSAFE.putOrderedObject(this, |
1069 |
+ |
currentStealOffset, t); |
1070 |
+ |
t.quietlyExec(); |
1071 |
+ |
UNSAFE.putOrderedObject(this, |
1072 |
+ |
currentStealOffset, ps); |
1073 |
+ |
} |
1074 |
+ |
} |
1075 |
+ |
} |
1076 |
+ |
|
1077 |
+ |
// Try to descend to find v's stealer |
1078 |
+ |
ForkJoinTask<?> next = v.currentJoin; |
1079 |
+ |
if (task.status < 0 || next == null || next == task) |
1080 |
+ |
break; // stale, dead-end, or cyclic |
1081 |
+ |
if ((runState & TERMINATING) != 0) |
1082 |
+ |
joinMe.cancelIgnoringExceptions(); |
1083 |
+ |
if (joinMe.status < 0) |
1084 |
+ |
break; |
1085 |
+ |
task = next; |
1086 |
+ |
thread = v; |
1087 |
+ |
} |
1088 |
+ |
} |
1089 |
+ |
return running; |
1090 |
+ |
} |
1091 |
+ |
|
1092 |
+ |
/** |
1093 |
+ |
* Implements ForkJoinTask.getSurplusQueuedTaskCount(). |
1094 |
|
* Returns an estimate of the number of tasks, offset by a |
1095 |
|
* function of number of idle workers. |
1096 |
|
* |
1142 |
|
} |
1143 |
|
|
1144 |
|
/** |
872 |
– |
* Gets and removes a local task. |
873 |
– |
* |
874 |
– |
* @return a task, if available |
875 |
– |
*/ |
876 |
– |
final ForkJoinTask<?> pollLocalTask() { |
877 |
– |
while (base != sp) { |
878 |
– |
if (active || (active = pool.tryIncrementActiveCount())) |
879 |
– |
return locallyFifo? locallyDeqTask() : popTask(); |
880 |
– |
} |
881 |
– |
return null; |
882 |
– |
} |
883 |
– |
|
884 |
– |
/** |
885 |
– |
* Gets and removes a local or stolen task. |
886 |
– |
* |
887 |
– |
* @return a task, if available |
888 |
– |
*/ |
889 |
– |
final ForkJoinTask<?> pollTask() { |
890 |
– |
ForkJoinTask<?> t; |
891 |
– |
return (t = pollLocalTask()) != null ? t : scan(); |
892 |
– |
} |
893 |
– |
|
894 |
– |
/** |
895 |
– |
* Executes or processes other tasks awaiting the given task |
896 |
– |
* @return task completion status |
897 |
– |
*/ |
898 |
– |
final int execWhileJoining(ForkJoinTask<?> joinMe) { |
899 |
– |
int s; |
900 |
– |
while ((s = joinMe.status) >= 0) { |
901 |
– |
ForkJoinTask<?> t = base != sp? |
902 |
– |
popWhileJoining(joinMe) : |
903 |
– |
scanWhileJoining(joinMe); |
904 |
– |
if (t != null) |
905 |
– |
t.tryExec(); |
906 |
– |
} |
907 |
– |
return s; |
908 |
– |
} |
909 |
– |
|
910 |
– |
/** |
911 |
– |
* Returns or stolen task, if available, unless joinMe is done |
912 |
– |
* |
913 |
– |
* This method is intrinsically nonmodular. To maintain the |
914 |
– |
* property that tasks are never stolen if the awaited task is |
915 |
– |
* ready, we must interleave mechanics of scan with status |
916 |
– |
* checks. We rely here on the commit points of deq that allow us |
917 |
– |
* to cancel a steal even after CASing slot to null, but before |
918 |
– |
* adjusting base index: If, after the CAS, we see that joinMe is |
919 |
– |
* ready, we can back out by placing the task back into the slot, |
920 |
– |
* without adjusting index. The loop is otherwise a variant of the |
921 |
– |
* one in scan(). |
922 |
– |
* |
923 |
– |
*/ |
924 |
– |
private ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) { |
925 |
– |
int r = seed; |
926 |
– |
ForkJoinPool p = pool; |
927 |
– |
ForkJoinWorkerThread[] ws; |
928 |
– |
int n; |
929 |
– |
outer:while ((ws = p.workers) != null && (n = ws.length) > 1) { |
930 |
– |
int mask = n - 1; |
931 |
– |
int k = r; |
932 |
– |
boolean contended = false; // to retry loop if deq contends |
933 |
– |
for (int j = -n; j <= n; ++j) { |
934 |
– |
if (joinMe.status < 0) |
935 |
– |
break outer; |
936 |
– |
int b; |
937 |
– |
ForkJoinTask<?>[] q; |
938 |
– |
ForkJoinWorkerThread v = ws[k & mask]; |
939 |
– |
r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift |
940 |
– |
if (v != null && (b=v.base) != v.sp && (q=v.queue) != null) { |
941 |
– |
int i = (q.length - 1) & b; |
942 |
– |
ForkJoinTask<?> t = q[i]; |
943 |
– |
if (t != null && UNSAFE.compareAndSwapObject |
944 |
– |
(q, (i << qShift) + qBase, t, null)) { |
945 |
– |
if (joinMe.status >= 0) { |
946 |
– |
v.base = b + 1; |
947 |
– |
seed = r; |
948 |
– |
++stealCount; |
949 |
– |
return t; |
950 |
– |
} |
951 |
– |
UNSAFE.putObjectVolatile(q, (i<<qShift)+qBase, t); |
952 |
– |
break outer; // back out |
953 |
– |
} |
954 |
– |
contended = true; |
955 |
– |
} |
956 |
– |
k = j < 0 ? r : (k + ((n >>> 1) | 1)); |
957 |
– |
} |
958 |
– |
if (!contended && p.tryAwaitBusyJoin(joinMe)) |
959 |
– |
break; |
960 |
– |
} |
961 |
– |
return null; |
962 |
– |
} |
963 |
– |
|
964 |
– |
/** |
965 |
– |
* Version of popTask with join checks surrounding extraction. |
966 |
– |
* Uses the same backout strategy as helpJoinTask. Note that |
967 |
– |
* we ignore locallyFifo flag for local tasks here since helping |
968 |
– |
* joins only make sense in LIFO mode. |
969 |
– |
* |
970 |
– |
* @return a popped task, if available, unless joinMe is done |
971 |
– |
*/ |
972 |
– |
private ForkJoinTask<?> popWhileJoining(ForkJoinTask<?> joinMe) { |
973 |
– |
int s; |
974 |
– |
ForkJoinTask<?>[] q; |
975 |
– |
while ((s = sp) != base && (q = queue) != null && joinMe.status >= 0) { |
976 |
– |
int i = (q.length - 1) & --s; |
977 |
– |
ForkJoinTask<?> t = q[i]; |
978 |
– |
if (t != null && UNSAFE.compareAndSwapObject |
979 |
– |
(q, (i << qShift) + qBase, t, null)) { |
980 |
– |
if (joinMe.status >= 0) { |
981 |
– |
sp = s; |
982 |
– |
return t; |
983 |
– |
} |
984 |
– |
UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t); |
985 |
– |
break; // back out |
986 |
– |
} |
987 |
– |
} |
988 |
– |
return null; |
989 |
– |
} |
990 |
– |
|
991 |
– |
/** |
1145 |
|
* Runs tasks until {@code pool.isQuiescent()}. |
1146 |
|
*/ |
1147 |
|
final void helpQuiescePool() { |
1148 |
+ |
ForkJoinTask<?> ps = currentSteal; // to restore below |
1149 |
|
for (;;) { |
1150 |
|
ForkJoinTask<?> t = pollLocalTask(); |
1151 |
|
if (t != null || (t = scan()) != null) |
1152 |
< |
t.tryExec(); |
1152 |
> |
t.quietlyExec(); |
1153 |
|
else { |
1154 |
|
ForkJoinPool p = pool; |
1155 |
+ |
int a; // to inline CASes |
1156 |
|
if (active) { |
1157 |
+ |
if (!UNSAFE.compareAndSwapInt |
1158 |
+ |
(p, poolRunStateOffset, a = p.runState, a - 1)) |
1159 |
+ |
continue; // retry later |
1160 |
|
active = false; // inactivate |
1161 |
< |
do {} while (!p.tryDecrementActiveCount()); |
1161 |
> |
UNSAFE.putOrderedObject(this, currentStealOffset, ps); |
1162 |
|
} |
1163 |
|
if (p.isQuiescent()) { |
1164 |
|
active = true; // re-activate |
1165 |
< |
do {} while (!p.tryIncrementActiveCount()); |
1165 |
> |
do {} while (!UNSAFE.compareAndSwapInt |
1166 |
> |
(p, poolRunStateOffset, a = p.runState, a+1)); |
1167 |
|
return; |
1168 |
|
} |
1169 |
|
} |
1173 |
|
// Unsafe mechanics |
1174 |
|
|
1175 |
|
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1176 |
+ |
private static final long spOffset = |
1177 |
+ |
objectFieldOffset("sp", ForkJoinWorkerThread.class); |
1178 |
|
private static final long runStateOffset = |
1179 |
|
objectFieldOffset("runState", ForkJoinWorkerThread.class); |
1180 |
+ |
private static final long currentJoinOffset = |
1181 |
+ |
objectFieldOffset("currentJoin", ForkJoinWorkerThread.class); |
1182 |
+ |
private static final long currentStealOffset = |
1183 |
+ |
objectFieldOffset("currentSteal", ForkJoinWorkerThread.class); |
1184 |
|
private static final long qBase = |
1185 |
|
UNSAFE.arrayBaseOffset(ForkJoinTask[].class); |
1186 |
+ |
private static final long poolRunStateOffset = // to inline CAS |
1187 |
+ |
objectFieldOffset("runState", ForkJoinPool.class); |
1188 |
+ |
|
1189 |
|
private static final int qShift; |
1190 |
|
|
1191 |
|
static { |
1193 |
|
if ((s & (s-1)) != 0) |
1194 |
|
throw new Error("data type scale not a power of two"); |
1195 |
|
qShift = 31 - Integer.numberOfLeadingZeros(s); |
1196 |
+ |
MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift); |
1197 |
|
} |
1198 |
|
|
1199 |
|
private static long objectFieldOffset(String field, Class<?> klazz) { |