5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.util.*; |
8 |
> |
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.atomic.*; |
11 |
< |
import java.util.concurrent.locks.*; |
12 |
< |
import sun.misc.Unsafe; |
13 |
< |
import java.lang.reflect.*; |
10 |
> |
|
11 |
> |
import java.util.Collection; |
12 |
|
|
13 |
|
/** |
14 |
< |
* A thread that is internally managed by a ForkJoinPool to execute |
15 |
< |
* ForkJoinTasks. This class additionally provides public |
16 |
< |
* <tt>static</tt> methods accessing some basic scheduling and |
17 |
< |
* execution mechanics for the <em>current</em> |
18 |
< |
* ForkJoinWorkerThread. These methods may be invoked only from within |
19 |
< |
* other ForkJoinTask computations. Attempts to invoke in other |
20 |
< |
* contexts result in exceptions or errors including |
23 |
< |
* ClassCastException. These methods enable construction of |
24 |
< |
* special-purpose task classes, as well as specialized idioms |
25 |
< |
* occasionally useful in ForkJoinTask processing. |
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 |
17 |
> |
* execution. However, you can override initialization and termination |
18 |
> |
* methods surrounding the main task processing loop. If you do |
19 |
> |
* create such a subclass, you will also need to supply a custom |
20 |
> |
* ForkJoinWorkerThreadFactory to use it in a ForkJoinPool. |
21 |
|
* |
22 |
< |
* <p>The form of supported static methods reflects the fact that |
23 |
< |
* worker threads may access and process tasks obtained in any of |
29 |
< |
* three ways. In preference order: <em>Local</em> tasks are processed |
30 |
< |
* in LIFO (newest first) order. <em>Stolen</em> tasks are obtained |
31 |
< |
* from other threads in FIFO (oldest first) order, only if there are |
32 |
< |
* no local tasks to run. <em>Submissions</em> form a FIFO queue |
33 |
< |
* common to the entire pool, and are started only if no other |
34 |
< |
* work is available. |
35 |
< |
* |
36 |
< |
* <p> This class is subclassable solely for the sake of adding |
37 |
< |
* functionality -- there are no overridable methods dealing with |
38 |
< |
* scheduling or execution. However, you can override initialization |
39 |
< |
* and termination cleanup methods surrounding the main task |
40 |
< |
* processing loop. If you do create such a subclass, you will also |
41 |
< |
* need to supply a custom ForkJoinWorkerThreadFactory to use it in a |
42 |
< |
* ForkJoinPool. |
22 |
> |
* @since 1.7 |
23 |
> |
* @author Doug Lea |
24 |
|
*/ |
25 |
|
public class ForkJoinWorkerThread extends Thread { |
26 |
|
/* |
44 |
|
* of tasks. To accomplish this, we shift the CAS arbitrating pop |
45 |
|
* vs deq (steal) from being on the indices ("base" and "sp") to |
46 |
|
* the slots themselves (mainly via method "casSlotNull()"). So, |
47 |
< |
* both a successful pop and deq mainly entail CAS'ing a nonnull |
47 |
> |
* both a successful pop and deq mainly entail CAS'ing a non-null |
48 |
|
* slot to null. Because we rely on CASes of references, we do |
49 |
|
* not need tag bits on base or sp. They are simple ints as used |
50 |
|
* in any circular array-based queue (see for example ArrayDeque). |
56 |
|
* considered individually, is not wait-free. One thief cannot |
57 |
|
* successfully continue until another in-progress one (or, if |
58 |
|
* previously empty, a push) completes. However, in the |
59 |
< |
* aggregate, we ensure at least probablistic non-blockingness. If |
59 |
> |
* aggregate, we ensure at least probabilistic non-blockingness. If |
60 |
|
* an attempted steal fails, a thief always chooses a different |
61 |
|
* random victim target to try next. So, in order for one thief to |
62 |
|
* progress, it suffices for any in-progress deq or new push on |
65 |
|
* which gives threads a chance to activate if necessary before |
66 |
|
* stealing (see below). |
67 |
|
* |
68 |
+ |
* This approach also enables support for "async mode" where local |
69 |
+ |
* task processing is in FIFO, not LIFO order; simply by using a |
70 |
+ |
* version of deq rather than pop when locallyFifo is true (as set |
71 |
+ |
* by the ForkJoinPool). This allows use in message-passing |
72 |
+ |
* frameworks in which tasks are never joined. |
73 |
+ |
* |
74 |
|
* Efficient implementation of this approach currently relies on |
75 |
|
* an uncomfortable amount of "Unsafe" mechanics. To maintain |
76 |
|
* correct orderings, reads and writes of variable base require |
81 |
|
* push) require store order and CASes (in pop and deq) require |
82 |
|
* (volatile) CAS semantics. Since these combinations aren't |
83 |
|
* supported using ordinary volatiles, the only way to accomplish |
84 |
< |
* these effciently is to use direct Unsafe calls. (Using external |
84 |
> |
* these efficiently is to use direct Unsafe calls. (Using external |
85 |
|
* AtomicIntegers and AtomicReferenceArrays for the indices and |
86 |
|
* array is significantly slower because of memory locality and |
87 |
|
* indirection effects.) Further, performance on most platforms is |
136 |
|
|
137 |
|
/** |
138 |
|
* Maximum work-stealing queue array size. Must be less than or |
139 |
< |
* equal to 1 << 30 to ensure lack of index wraparound. |
139 |
> |
* equal to 1 << 28 to ensure lack of index wraparound. (This |
140 |
> |
* is less than usual bounds, because we need leftshift by 3 |
141 |
> |
* to be in int range). |
142 |
|
*/ |
143 |
< |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30; |
143 |
> |
private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28; |
144 |
|
|
145 |
|
/** |
146 |
< |
* Generator of seeds for per-thread random numbers. |
146 |
> |
* The pool this thread works in. Accessed directly by ForkJoinTask. |
147 |
|
*/ |
148 |
< |
private static final Random randomSeedGenerator = new Random(); |
148 |
> |
final ForkJoinPool pool; |
149 |
|
|
150 |
|
/** |
151 |
|
* The work-stealing queue array. Size must be a power of two. |
152 |
+ |
* Initialized when thread starts, to improve memory locality. |
153 |
|
*/ |
154 |
|
private ForkJoinTask<?>[] queue; |
155 |
|
|
168 |
|
private volatile int base; |
169 |
|
|
170 |
|
/** |
171 |
< |
* The pool this thread works in. |
172 |
< |
*/ |
173 |
< |
final ForkJoinPool pool; |
174 |
< |
|
185 |
< |
/** |
186 |
< |
* Index of this worker in pool array. Set once by pool before |
187 |
< |
* running, and accessed directly by pool during cleanup etc |
171 |
> |
* Activity status. When true, this worker is considered active. |
172 |
> |
* Must be false upon construction. It must be true when executing |
173 |
> |
* tasks, and BEFORE stealing a task. It must be false before |
174 |
> |
* calling pool.sync. |
175 |
|
*/ |
176 |
< |
int poolIndex; |
176 |
> |
private boolean active; |
177 |
|
|
178 |
|
/** |
179 |
|
* Run state of this worker. Supports simple versions of the usual |
181 |
|
*/ |
182 |
|
private volatile int runState; |
183 |
|
|
197 |
– |
// Runstate values. Order matters |
198 |
– |
private static final int RUNNING = 0; |
199 |
– |
private static final int SHUTDOWN = 1; |
200 |
– |
private static final int TERMINATING = 2; |
201 |
– |
private static final int TERMINATED = 3; |
202 |
– |
|
184 |
|
/** |
185 |
< |
* Activity status. When true, this worker is considered active. |
186 |
< |
* Must be false upon construction. It must be true when executing |
206 |
< |
* tasks, and BEFORE stealing a task. It must be false before |
207 |
< |
* blocking on the Pool Barrier. |
185 |
> |
* Seed for random number generator for choosing steal victims. |
186 |
> |
* Uses Marsaglia xorshift. Must be nonzero upon initialization. |
187 |
|
*/ |
188 |
< |
private boolean active; |
188 |
> |
private int seed; |
189 |
|
|
190 |
|
/** |
191 |
|
* Number of steals, transferred to pool when idle |
193 |
|
private int stealCount; |
194 |
|
|
195 |
|
/** |
196 |
< |
* Seed for random number generator for choosing steal victims |
196 |
> |
* Index of this worker in pool array. Set once by pool before |
197 |
> |
* running, and accessed directly by pool during cleanup etc. |
198 |
|
*/ |
199 |
< |
private int randomVictimSeed; |
199 |
> |
int poolIndex; |
200 |
|
|
201 |
|
/** |
202 |
< |
* Seed for embedded Jurandom |
202 |
> |
* The last barrier event waited for. Accessed in pool callback |
203 |
> |
* methods, but only by current thread. |
204 |
|
*/ |
205 |
< |
private long juRandomSeed; |
205 |
> |
long lastEventCount; |
206 |
|
|
207 |
|
/** |
208 |
< |
* The last barrier event waited for |
208 |
> |
* True if use local fifo, not default lifo, for local polling |
209 |
|
*/ |
210 |
< |
private long eventCount; |
210 |
> |
private boolean locallyFifo; |
211 |
|
|
212 |
|
/** |
213 |
|
* Creates a ForkJoinWorkerThread operating in the given pool. |
214 |
+ |
* |
215 |
|
* @param pool the pool this thread works in |
216 |
|
* @throws NullPointerException if pool is null |
217 |
|
*/ |
218 |
|
protected ForkJoinWorkerThread(ForkJoinPool pool) { |
219 |
|
if (pool == null) throw new NullPointerException(); |
220 |
|
this.pool = pool; |
221 |
< |
// remaining initialization deferred to onStart |
221 |
> |
// Note: poolIndex is set by pool during construction |
222 |
> |
// Remaining initialization is deferred to onStart |
223 |
|
} |
224 |
|
|
225 |
< |
// Access methods used by Pool |
225 |
> |
// Public access methods |
226 |
|
|
227 |
|
/** |
228 |
< |
* Get and clear steal count for accumulation by pool. Called |
229 |
< |
* only when known to be idle (in pool.sync and termination). |
228 |
> |
* Returns the pool hosting this thread. |
229 |
> |
* |
230 |
> |
* @return the pool |
231 |
|
*/ |
232 |
< |
final int getAndClearStealCount() { |
233 |
< |
int sc = stealCount; |
250 |
< |
stealCount = 0; |
251 |
< |
return sc; |
232 |
> |
public ForkJoinPool getPool() { |
233 |
> |
return pool; |
234 |
|
} |
235 |
|
|
236 |
|
/** |
237 |
< |
* Returns estimate of the number of tasks in the queue, without |
238 |
< |
* correcting for transient negative values |
237 |
> |
* Returns the index number of this thread in its pool. The |
238 |
> |
* returned value ranges from zero to the maximum number of |
239 |
> |
* threads (minus one) that have ever been created in the pool. |
240 |
> |
* This method may be useful for applications that track status or |
241 |
> |
* collect results per-worker rather than per-task. |
242 |
> |
* |
243 |
> |
* @return the index number |
244 |
|
*/ |
245 |
< |
final int getRawQueueSize() { |
246 |
< |
return sp - base; |
245 |
> |
public int getPoolIndex() { |
246 |
> |
return poolIndex; |
247 |
|
} |
248 |
|
|
249 |
< |
// Intrinsics-based support for queue operations. |
250 |
< |
// Currently these three (setSp, setSlot, casSlotNull) are |
251 |
< |
// usually manually inlined to improve performance |
249 |
> |
/** |
250 |
> |
* Establishes local first-in-first-out scheduling mode for forked |
251 |
> |
* tasks that are never joined. |
252 |
> |
* |
253 |
> |
* @param async if true, use locally FIFO scheduling |
254 |
> |
*/ |
255 |
> |
void setAsyncMode(boolean async) { |
256 |
> |
locallyFifo = async; |
257 |
> |
} |
258 |
> |
|
259 |
> |
// Runstate management |
260 |
> |
|
261 |
> |
// Runstate values. Order matters |
262 |
> |
private static final int RUNNING = 0; |
263 |
> |
private static final int SHUTDOWN = 1; |
264 |
> |
private static final int TERMINATING = 2; |
265 |
> |
private static final int TERMINATED = 3; |
266 |
> |
|
267 |
> |
final boolean isShutdown() { return runState >= SHUTDOWN; } |
268 |
> |
final boolean isTerminating() { return runState >= TERMINATING; } |
269 |
> |
final boolean isTerminated() { return runState == TERMINATED; } |
270 |
> |
final boolean shutdown() { return transitionRunStateTo(SHUTDOWN); } |
271 |
> |
final boolean shutdownNow() { return transitionRunStateTo(TERMINATING); } |
272 |
|
|
273 |
|
/** |
274 |
< |
* Sets sp in store-order. |
274 |
> |
* Transitions to at least the given state. |
275 |
> |
* |
276 |
> |
* @return {@code true} if not already at least at given state |
277 |
> |
*/ |
278 |
> |
private boolean transitionRunStateTo(int state) { |
279 |
> |
for (;;) { |
280 |
> |
int s = runState; |
281 |
> |
if (s >= state) |
282 |
> |
return false; |
283 |
> |
if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state)) |
284 |
> |
return true; |
285 |
> |
} |
286 |
> |
} |
287 |
> |
|
288 |
> |
/** |
289 |
> |
* Tries to set status to active; fails on contention. |
290 |
> |
*/ |
291 |
> |
private boolean tryActivate() { |
292 |
> |
if (!active) { |
293 |
> |
if (!pool.tryIncrementActiveCount()) |
294 |
> |
return false; |
295 |
> |
active = true; |
296 |
> |
} |
297 |
> |
return true; |
298 |
> |
} |
299 |
> |
|
300 |
> |
/** |
301 |
> |
* Tries to set status to inactive; fails on contention. |
302 |
> |
*/ |
303 |
> |
private boolean tryInactivate() { |
304 |
> |
if (active) { |
305 |
> |
if (!pool.tryDecrementActiveCount()) |
306 |
> |
return false; |
307 |
> |
active = false; |
308 |
> |
} |
309 |
> |
return true; |
310 |
> |
} |
311 |
> |
|
312 |
> |
/** |
313 |
> |
* Computes next value for random victim probe. Scans don't |
314 |
> |
* require a very high quality generator, but also not a crummy |
315 |
> |
* one. Marsaglia xor-shift is cheap and works well. |
316 |
> |
*/ |
317 |
> |
private static int xorShift(int r) { |
318 |
> |
r ^= (r << 13); |
319 |
> |
r ^= (r >>> 17); |
320 |
> |
return r ^ (r << 5); |
321 |
> |
} |
322 |
> |
|
323 |
> |
// Lifecycle methods |
324 |
> |
|
325 |
> |
/** |
326 |
> |
* This method is required to be public, but should never be |
327 |
> |
* called explicitly. It performs the main run loop to execute |
328 |
> |
* ForkJoinTasks. |
329 |
> |
*/ |
330 |
> |
public void run() { |
331 |
> |
Throwable exception = null; |
332 |
> |
try { |
333 |
> |
onStart(); |
334 |
> |
pool.sync(this); // await first pool event |
335 |
> |
mainLoop(); |
336 |
> |
} catch (Throwable ex) { |
337 |
> |
exception = ex; |
338 |
> |
} finally { |
339 |
> |
onTermination(exception); |
340 |
> |
} |
341 |
> |
} |
342 |
> |
|
343 |
> |
/** |
344 |
> |
* Executes tasks until shut down. |
345 |
> |
*/ |
346 |
> |
private void mainLoop() { |
347 |
> |
while (!isShutdown()) { |
348 |
> |
ForkJoinTask<?> t = pollTask(); |
349 |
> |
if (t != null || (t = pollSubmission()) != null) |
350 |
> |
t.quietlyExec(); |
351 |
> |
else if (tryInactivate()) |
352 |
> |
pool.sync(this); |
353 |
> |
} |
354 |
> |
} |
355 |
> |
|
356 |
> |
/** |
357 |
> |
* Initializes internal state after construction but before |
358 |
> |
* processing any tasks. If you override this method, you must |
359 |
> |
* invoke super.onStart() at the beginning of the method. |
360 |
> |
* Initialization requires care: Most fields must have legal |
361 |
> |
* default values, to ensure that attempted accesses from other |
362 |
> |
* threads work correctly even before this thread starts |
363 |
> |
* processing tasks. |
364 |
|
*/ |
365 |
< |
private void setSp(int s) { |
366 |
< |
_unsafe.putOrderedInt(this, spOffset, s); |
365 |
> |
protected void onStart() { |
366 |
> |
// Allocate while starting to improve chances of thread-local |
367 |
> |
// isolation |
368 |
> |
queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
369 |
> |
// Initial value of seed need not be especially random but |
370 |
> |
// should differ across workers and must be nonzero |
371 |
> |
int p = poolIndex + 1; |
372 |
> |
seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits |
373 |
|
} |
374 |
|
|
375 |
|
/** |
376 |
< |
* Add in store-order the given task at given slot of q to |
377 |
< |
* null. Caller must ensure q is nonnull and index is in range. |
376 |
> |
* Performs cleanup associated with termination of this worker |
377 |
> |
* thread. If you override this method, you must invoke |
378 |
> |
* {@code super.onTermination} at the end of the overridden method. |
379 |
> |
* |
380 |
> |
* @param exception the exception causing this thread to abort due |
381 |
> |
* to an unrecoverable error, or {@code null} if completed normally |
382 |
> |
*/ |
383 |
> |
protected void onTermination(Throwable exception) { |
384 |
> |
// Execute remaining local tasks unless aborting or terminating |
385 |
> |
while (exception == null && !pool.isTerminating() && base != sp) { |
386 |
> |
try { |
387 |
> |
ForkJoinTask<?> t = popTask(); |
388 |
> |
if (t != null) |
389 |
> |
t.quietlyExec(); |
390 |
> |
} catch (Throwable ex) { |
391 |
> |
exception = ex; |
392 |
> |
} |
393 |
> |
} |
394 |
> |
// Cancel other tasks, transition status, notify pool, and |
395 |
> |
// propagate exception to uncaught exception handler |
396 |
> |
try { |
397 |
> |
do {} while (!tryInactivate()); // ensure inactive |
398 |
> |
cancelTasks(); |
399 |
> |
runState = TERMINATED; |
400 |
> |
pool.workerTerminated(this); |
401 |
> |
} catch (Throwable ex) { // Shouldn't ever happen |
402 |
> |
if (exception == null) // but if so, at least rethrown |
403 |
> |
exception = ex; |
404 |
> |
} finally { |
405 |
> |
if (exception != null) |
406 |
> |
ForkJoinTask.rethrowException(exception); |
407 |
> |
} |
408 |
> |
} |
409 |
> |
|
410 |
> |
// Intrinsics-based support for queue operations. |
411 |
> |
|
412 |
> |
/** |
413 |
> |
* Adds in store-order the given task at given slot of q to null. |
414 |
> |
* Caller must ensure q is non-null and index is in range. |
415 |
|
*/ |
416 |
|
private static void setSlot(ForkJoinTask<?>[] q, int i, |
417 |
< |
ForkJoinTask<?> t){ |
418 |
< |
_unsafe.putOrderedObject(q, (i << qShift) + qBase, t); |
417 |
> |
ForkJoinTask<?> t) { |
418 |
> |
UNSAFE.putOrderedObject(q, (i << qShift) + qBase, t); |
419 |
|
} |
420 |
|
|
421 |
|
/** |
422 |
< |
* CAS given slot of q to null. Caller must ensure q is nonnull |
422 |
> |
* CAS given slot of q to null. Caller must ensure q is non-null |
423 |
|
* and index is in range. |
424 |
|
*/ |
425 |
|
private static boolean casSlotNull(ForkJoinTask<?>[] q, int i, |
426 |
|
ForkJoinTask<?> t) { |
427 |
< |
return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null); |
427 |
> |
return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null); |
428 |
> |
} |
429 |
> |
|
430 |
> |
/** |
431 |
> |
* Sets sp in store-order. |
432 |
> |
*/ |
433 |
> |
private void storeSp(int s) { |
434 |
> |
UNSAFE.putOrderedInt(this, spOffset, s); |
435 |
|
} |
436 |
|
|
437 |
|
// Main queue methods |
438 |
|
|
439 |
|
/** |
440 |
|
* Pushes a task. Called only by current thread. |
441 |
< |
* @param t the task. Caller must ensure nonnull |
441 |
> |
* |
442 |
> |
* @param t the task. Caller must ensure non-null. |
443 |
|
*/ |
444 |
|
final void pushTask(ForkJoinTask<?> t) { |
445 |
|
ForkJoinTask<?>[] q = queue; |
446 |
|
int mask = q.length - 1; |
447 |
|
int s = sp; |
448 |
< |
_unsafe.putOrderedObject(q, ((s & mask) << qShift) + qBase, t); |
449 |
< |
_unsafe.putOrderedInt(this, spOffset, ++s); |
448 |
> |
setSlot(q, s & mask, t); |
449 |
> |
storeSp(++s); |
450 |
|
if ((s -= base) == 1) |
451 |
< |
pool.signalNonEmptyWorkerQueue(); |
451 |
> |
pool.signalWork(); |
452 |
|
else if (s >= mask) |
453 |
|
growQueue(); |
454 |
|
} |
456 |
|
/** |
457 |
|
* Tries to take a task from the base of the queue, failing if |
458 |
|
* either empty or contended. |
459 |
< |
* @return a task, or null if none or contended. |
459 |
> |
* |
460 |
> |
* @return a task, or null if none or contended |
461 |
|
*/ |
462 |
< |
private ForkJoinTask<?> deqTask() { |
315 |
< |
ForkJoinTask<?>[] q; |
462 |
> |
final ForkJoinTask<?> deqTask() { |
463 |
|
ForkJoinTask<?> t; |
464 |
+ |
ForkJoinTask<?>[] q; |
465 |
|
int i; |
466 |
|
int b; |
467 |
|
if (sp != (b = base) && |
468 |
|
(q = queue) != null && // must read q after b |
469 |
|
(t = q[i = (q.length - 1) & b]) != null && |
470 |
< |
_unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
470 |
> |
casSlotNull(q, i, t)) { |
471 |
|
base = b + 1; |
472 |
|
return t; |
473 |
|
} |
475 |
|
} |
476 |
|
|
477 |
|
/** |
478 |
< |
* Returns a popped task, or null if empty. Called only by |
479 |
< |
* current thread. |
478 |
> |
* Tries to take a task from the base of own queue, activating if |
479 |
> |
* necessary, failing only if empty. Called only by current thread. |
480 |
> |
* |
481 |
> |
* @return a task, or null if none |
482 |
> |
*/ |
483 |
> |
final ForkJoinTask<?> locallyDeqTask() { |
484 |
> |
int b; |
485 |
> |
while (sp != (b = base)) { |
486 |
> |
if (tryActivate()) { |
487 |
> |
ForkJoinTask<?>[] q = queue; |
488 |
> |
int i = (q.length - 1) & b; |
489 |
> |
ForkJoinTask<?> t = q[i]; |
490 |
> |
if (t != null && casSlotNull(q, i, t)) { |
491 |
> |
base = b + 1; |
492 |
> |
return t; |
493 |
> |
} |
494 |
> |
} |
495 |
> |
} |
496 |
> |
return null; |
497 |
> |
} |
498 |
> |
|
499 |
> |
/** |
500 |
> |
* Returns a popped task, or null if empty. Ensures active status |
501 |
> |
* if non-null. Called only by current thread. |
502 |
|
*/ |
503 |
|
final ForkJoinTask<?> popTask() { |
334 |
– |
ForkJoinTask<?> t; |
335 |
– |
int i; |
336 |
– |
ForkJoinTask<?>[] q = queue; |
337 |
– |
int mask = q.length - 1; |
504 |
|
int s = sp; |
505 |
< |
if (s != base && |
506 |
< |
(t = q[i = (s - 1) & mask]) != null && |
507 |
< |
_unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) { |
508 |
< |
_unsafe.putOrderedInt(this, spOffset, s - 1); |
509 |
< |
return t; |
505 |
> |
while (s != base) { |
506 |
> |
if (tryActivate()) { |
507 |
> |
ForkJoinTask<?>[] q = queue; |
508 |
> |
int mask = q.length - 1; |
509 |
> |
int i = (s - 1) & mask; |
510 |
> |
ForkJoinTask<?> t = q[i]; |
511 |
> |
if (t == null || !casSlotNull(q, i, t)) |
512 |
> |
break; |
513 |
> |
storeSp(s - 1); |
514 |
> |
return t; |
515 |
> |
} |
516 |
|
} |
517 |
|
return null; |
518 |
|
} |
520 |
|
/** |
521 |
|
* Specialized version of popTask to pop only if |
522 |
|
* topmost element is the given task. Called only |
523 |
< |
* by current thread. |
524 |
< |
* @param t the task. Caller must ensure nonnull |
523 |
> |
* by current thread while active. |
524 |
> |
* |
525 |
> |
* @param t the task. Caller must ensure non-null. |
526 |
|
*/ |
527 |
|
final boolean unpushTask(ForkJoinTask<?> t) { |
528 |
|
ForkJoinTask<?>[] q = queue; |
529 |
|
int mask = q.length - 1; |
530 |
|
int s = sp - 1; |
531 |
< |
if (_unsafe.compareAndSwapObject(q, ((s & mask) << qShift) + qBase, |
532 |
< |
t, null)) { |
360 |
< |
_unsafe.putOrderedInt(this, spOffset, s); |
531 |
> |
if (casSlotNull(q, s & mask, t)) { |
532 |
> |
storeSp(s); |
533 |
|
return true; |
534 |
|
} |
535 |
|
return false; |
536 |
|
} |
537 |
|
|
538 |
|
/** |
539 |
< |
* Returns next task to pop. |
539 |
> |
* Returns next task or null if empty or contended |
540 |
|
*/ |
541 |
< |
private ForkJoinTask<?> peekTask() { |
541 |
> |
final ForkJoinTask<?> peekTask() { |
542 |
|
ForkJoinTask<?>[] q = queue; |
543 |
< |
return q == null? null : q[(sp - 1) & (q.length - 1)]; |
543 |
> |
if (q == null) |
544 |
> |
return null; |
545 |
> |
int mask = q.length - 1; |
546 |
> |
int i = locallyFifo ? base : (sp - 1); |
547 |
> |
return q[i & mask]; |
548 |
|
} |
549 |
|
|
550 |
|
/** |
571 |
|
t = null; |
572 |
|
setSlot(newQ, b & newMask, t); |
573 |
|
} while (++b != bf); |
574 |
< |
pool.signalIdleWorkers(false); |
399 |
< |
} |
400 |
< |
|
401 |
< |
// Runstate management |
402 |
< |
|
403 |
< |
final boolean isShutdown() { return runState >= SHUTDOWN; } |
404 |
< |
final boolean isTerminating() { return runState >= TERMINATING; } |
405 |
< |
final boolean isTerminated() { return runState == TERMINATED; } |
406 |
< |
final boolean shutdown() { return transitionRunStateTo(SHUTDOWN); } |
407 |
< |
final boolean shutdownNow() { return transitionRunStateTo(TERMINATING); } |
408 |
< |
|
409 |
< |
/** |
410 |
< |
* Transition to at least the given state. Return true if not |
411 |
< |
* already at least given state. |
412 |
< |
*/ |
413 |
< |
private boolean transitionRunStateTo(int state) { |
414 |
< |
for (;;) { |
415 |
< |
int s = runState; |
416 |
< |
if (s >= state) |
417 |
< |
return false; |
418 |
< |
if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state)) |
419 |
< |
return true; |
420 |
< |
} |
421 |
< |
} |
422 |
< |
|
423 |
< |
/** |
424 |
< |
* Ensure status is active and if necessary adjust pool active count |
425 |
< |
*/ |
426 |
< |
final void activate() { |
427 |
< |
if (!active) { |
428 |
< |
active = true; |
429 |
< |
pool.incrementActiveCount(); |
430 |
< |
} |
574 |
> |
pool.signalWork(); |
575 |
|
} |
576 |
|
|
577 |
|
/** |
578 |
< |
* Ensure status is inactive and if necessary adjust pool active count |
578 |
> |
* Tries to steal a task from another worker. Starts at a random |
579 |
> |
* index of workers array, and probes workers until finding one |
580 |
> |
* with non-empty queue or finding that all are empty. It |
581 |
> |
* randomly selects the first n probes. If these are empty, it |
582 |
> |
* resorts to a full circular traversal, which is necessary to |
583 |
> |
* accurately set active status by caller. Also restarts if pool |
584 |
> |
* events occurred since last scan, which forces refresh of |
585 |
> |
* workers array, in case barrier was associated with resize. |
586 |
> |
* |
587 |
> |
* This method must be both fast and quiet -- usually avoiding |
588 |
> |
* memory accesses that could disrupt cache sharing etc other than |
589 |
> |
* those needed to check for and take tasks. This accounts for, |
590 |
> |
* among other things, updating random seed in place without |
591 |
> |
* storing it until exit. |
592 |
> |
* |
593 |
> |
* @return a task, or null if none found |
594 |
|
*/ |
595 |
< |
final void inactivate() { |
596 |
< |
if (active) { |
597 |
< |
active = false; |
598 |
< |
pool.decrementActiveCount(); |
599 |
< |
} |
595 |
> |
private ForkJoinTask<?> scan() { |
596 |
> |
ForkJoinTask<?> t = null; |
597 |
> |
int r = seed; // extract once to keep scan quiet |
598 |
> |
ForkJoinWorkerThread[] ws; // refreshed on outer loop |
599 |
> |
int mask; // must be power 2 minus 1 and > 0 |
600 |
> |
outer:do { |
601 |
> |
if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) { |
602 |
> |
int idx = r; |
603 |
> |
int probes = ~mask; // use random index while negative |
604 |
> |
for (;;) { |
605 |
> |
r = xorShift(r); // update random seed |
606 |
> |
ForkJoinWorkerThread v = ws[mask & idx]; |
607 |
> |
if (v == null || v.sp == v.base) { |
608 |
> |
if (probes <= mask) |
609 |
> |
idx = (probes++ < 0) ? r : (idx + 1); |
610 |
> |
else |
611 |
> |
break; |
612 |
> |
} |
613 |
> |
else if (!tryActivate() || (t = v.deqTask()) == null) |
614 |
> |
continue outer; // restart on contention |
615 |
> |
else |
616 |
> |
break outer; |
617 |
> |
} |
618 |
> |
} |
619 |
> |
} while (pool.hasNewSyncEvent(this)); // retry on pool events |
620 |
> |
seed = r; |
621 |
> |
return t; |
622 |
|
} |
623 |
|
|
443 |
– |
// Lifecycle methods |
444 |
– |
|
624 |
|
/** |
625 |
< |
* Initializes internal state after construction but before |
626 |
< |
* processing any tasks. If you override this method, you must |
627 |
< |
* invoke super.onStart() at the beginning of the method. |
449 |
< |
* Initialization requires care: Most fields must have legal |
450 |
< |
* default values, to ensure that attempted accesses from other |
451 |
< |
* threads work correctly even before this thread starts |
452 |
< |
* processing tasks. |
625 |
> |
* Gets and removes a local or stolen task. |
626 |
> |
* |
627 |
> |
* @return a task, if available |
628 |
|
*/ |
629 |
< |
protected void onStart() { |
630 |
< |
juRandomSeed = randomSeedGenerator.nextLong(); |
631 |
< |
do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero |
632 |
< |
if (queue == null) |
633 |
< |
queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY]; |
459 |
< |
|
460 |
< |
// Heuristically allow one initial thread to warm up; others wait |
461 |
< |
if (poolIndex < pool.getParallelism() - 1) { |
462 |
< |
eventCount = pool.sync(this, 0); |
463 |
< |
activate(); |
464 |
< |
} |
629 |
> |
final ForkJoinTask<?> pollTask() { |
630 |
> |
ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask(); |
631 |
> |
if (t == null && (t = scan()) != null) |
632 |
> |
++stealCount; |
633 |
> |
return t; |
634 |
|
} |
635 |
|
|
636 |
|
/** |
637 |
< |
* Perform cleanup associated with termination of this worker |
469 |
< |
* thread. If you override this method, you must invoke |
470 |
< |
* super.onTermination at the end of the overridden method. |
637 |
> |
* Gets a local task. |
638 |
|
* |
639 |
< |
* @param exception the exception causing this thread to abort due |
473 |
< |
* to an unrecoverable error, or null if completed normally. |
639 |
> |
* @return a task, if available |
640 |
|
*/ |
641 |
< |
protected void onTermination(Throwable exception) { |
642 |
< |
try { |
477 |
< |
clearLocalTasks(); |
478 |
< |
inactivate(); |
479 |
< |
cancelTasks(); |
480 |
< |
} finally { |
481 |
< |
terminate(exception); |
482 |
< |
} |
641 |
> |
final ForkJoinTask<?> pollLocalTask() { |
642 |
> |
return locallyFifo ? locallyDeqTask() : popTask(); |
643 |
|
} |
644 |
|
|
645 |
|
/** |
646 |
< |
* Notify pool of termination and, if exception is nonnull, |
647 |
< |
* rethrow it to trigger this thread's uncaughtExceptionHandler |
646 |
> |
* Returns a pool submission, if one exists, activating first. |
647 |
> |
* |
648 |
> |
* @return a submission, if available |
649 |
|
*/ |
650 |
< |
private void terminate(Throwable exception) { |
651 |
< |
transitionRunStateTo(TERMINATED); |
652 |
< |
try { |
653 |
< |
pool.workerTerminated(this); |
654 |
< |
} finally { |
655 |
< |
if (exception != null) |
495 |
< |
ForkJoinTask.rethrowException(exception); |
650 |
> |
private ForkJoinTask<?> pollSubmission() { |
651 |
> |
ForkJoinPool p = pool; |
652 |
> |
while (p.hasQueuedSubmissions()) { |
653 |
> |
ForkJoinTask<?> t; |
654 |
> |
if (tryActivate() && (t = p.pollSubmission()) != null) |
655 |
> |
return t; |
656 |
|
} |
657 |
+ |
return null; |
658 |
|
} |
659 |
|
|
660 |
< |
/** |
500 |
< |
* Run local tasks on exit from main. |
501 |
< |
*/ |
502 |
< |
private void clearLocalTasks() { |
503 |
< |
while (base != sp && !pool.isTerminating()) { |
504 |
< |
ForkJoinTask<?> t = popTask(); |
505 |
< |
if (t != null) { |
506 |
< |
activate(); // ensure active status |
507 |
< |
t.quietlyExec(); |
508 |
< |
} |
509 |
< |
} |
510 |
< |
} |
660 |
> |
// Methods accessed only by Pool |
661 |
|
|
662 |
|
/** |
663 |
|
* Removes and cancels all tasks in queue. Can be called from any |
664 |
|
* thread. |
665 |
|
*/ |
666 |
|
final void cancelTasks() { |
667 |
< |
while (base != sp) { |
668 |
< |
ForkJoinTask<?> t = deqTask(); |
669 |
< |
if (t != null) |
520 |
< |
t.cancelIgnoreExceptions(); |
521 |
< |
} |
522 |
< |
} |
523 |
< |
|
524 |
< |
/** |
525 |
< |
* This method is required to be public, but should never be |
526 |
< |
* called explicitly. It performs the main run loop to execute |
527 |
< |
* ForkJoinTasks. |
528 |
< |
*/ |
529 |
< |
public void run() { |
530 |
< |
Throwable exception = null; |
531 |
< |
try { |
532 |
< |
onStart(); |
533 |
< |
while (!isShutdown()) |
534 |
< |
step(); |
535 |
< |
} catch (Throwable ex) { |
536 |
< |
exception = ex; |
537 |
< |
} finally { |
538 |
< |
onTermination(exception); |
539 |
< |
} |
667 |
> |
ForkJoinTask<?> t; |
668 |
> |
while (base != sp && (t = deqTask()) != null) |
669 |
> |
t.cancelIgnoringExceptions(); |
670 |
|
} |
671 |
|
|
672 |
|
/** |
673 |
< |
* Main top-level action. |
673 |
> |
* Drains tasks to given collection c. |
674 |
> |
* |
675 |
> |
* @return the number of tasks drained |
676 |
|
*/ |
677 |
< |
private void step() { |
678 |
< |
ForkJoinTask<?> t = sp != base? popTask() : null; |
679 |
< |
if (t != null || (t = scan(null, true)) != null) { |
680 |
< |
activate(); |
681 |
< |
t.quietlyExec(); |
682 |
< |
} |
551 |
< |
else { |
552 |
< |
inactivate(); |
553 |
< |
eventCount = pool.sync(this, eventCount); |
677 |
> |
final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) { |
678 |
> |
int n = 0; |
679 |
> |
ForkJoinTask<?> t; |
680 |
> |
while (base != sp && (t = deqTask()) != null) { |
681 |
> |
c.add(t); |
682 |
> |
++n; |
683 |
|
} |
684 |
+ |
return n; |
685 |
|
} |
686 |
|
|
557 |
– |
// scanning for and stealing tasks |
558 |
– |
|
687 |
|
/** |
688 |
< |
* Computes next value for random victim probe. Scans don't |
689 |
< |
* require a very high quality generator, but also not a crummy |
562 |
< |
* one. Marsaglia xor-shift is cheap and works well. |
563 |
< |
* |
564 |
< |
* This is currently unused, and manually inlined |
688 |
> |
* Gets and clears steal count for accumulation by pool. Called |
689 |
> |
* only when known to be idle (in pool.sync and termination). |
690 |
|
*/ |
691 |
< |
private static int xorShift(int r) { |
692 |
< |
r ^= r << 1; |
693 |
< |
r ^= r >>> 3; |
694 |
< |
r ^= r << 10; |
570 |
< |
return r; |
691 |
> |
final int getAndClearStealCount() { |
692 |
> |
int sc = stealCount; |
693 |
> |
stealCount = 0; |
694 |
> |
return sc; |
695 |
|
} |
696 |
|
|
697 |
|
/** |
698 |
< |
* Tries to steal a task from another worker and/or, if enabled, |
699 |
< |
* submission queue. Starts at a random index of workers array, |
576 |
< |
* and probes workers until finding one with non-empty queue or |
577 |
< |
* finding that all are empty. It randomly selects the first n-1 |
578 |
< |
* probes. If these are empty, it resorts to full circular |
579 |
< |
* traversal, which is necessary to accurately set active status |
580 |
< |
* by caller. Also restarts if pool barrier has tripped since last |
581 |
< |
* scan, which forces refresh of workers array, in case barrier |
582 |
< |
* was associated with resize. |
698 |
> |
* Returns {@code true} if at least one worker in the given array |
699 |
> |
* appears to have at least one queued task. |
700 |
|
* |
701 |
< |
* This method must be both fast and quiet -- usually avoiding |
585 |
< |
* memory accesses that could disrupt cache sharing etc other than |
586 |
< |
* those needed to check for and take tasks. This accounts for, |
587 |
< |
* among other things, updating random seed in place without |
588 |
< |
* storing it until exit. (Note that we only need to store it if |
589 |
< |
* we found a task; otherwise it doesn't matter if we start at the |
590 |
< |
* same place next time.) |
591 |
< |
* |
592 |
< |
* @param joinMe if non null; exit early if done |
593 |
< |
* @param checkSubmissions true if OK to take submissions |
594 |
< |
* @return a task, or null if none found |
701 |
> |
* @param ws array of workers |
702 |
|
*/ |
703 |
< |
private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe, |
704 |
< |
boolean checkSubmissions) { |
705 |
< |
ForkJoinPool p = pool; |
706 |
< |
if (p == null) // Never null, but avoids |
707 |
< |
return null; // implicit nullchecks below |
708 |
< |
int r = randomVictimSeed; // extract once to keep scan quiet |
709 |
< |
restart: // outer loop refreshes ws array |
710 |
< |
while (joinMe == null || joinMe.status >= 0) { |
604 |
< |
int mask; |
605 |
< |
ForkJoinWorkerThread[] ws = p.workers; |
606 |
< |
if (ws != null && (mask = ws.length - 1) > 0) { |
607 |
< |
int probes = -mask; // use random index while negative |
608 |
< |
int idx = r; |
609 |
< |
for (;;) { |
610 |
< |
ForkJoinWorkerThread v; |
611 |
< |
// inlined xorshift to update seed |
612 |
< |
r ^= r << 1; r ^= r >>> 3; r ^= r << 10; |
613 |
< |
if ((v = ws[mask & idx]) != null && v.sp != v.base) { |
614 |
< |
ForkJoinTask<?> t; |
615 |
< |
activate(); |
616 |
< |
if ((joinMe == null || joinMe.status >= 0) && |
617 |
< |
(t = v.deqTask()) != null) { |
618 |
< |
randomVictimSeed = r; |
619 |
< |
++stealCount; |
620 |
< |
return t; |
621 |
< |
} |
622 |
< |
continue restart; // restart on contention |
623 |
< |
} |
624 |
< |
if ((probes >> 1) <= mask) // n-1 random then circular |
625 |
< |
idx = (probes++ < 0)? r : (idx + 1); |
626 |
< |
else |
627 |
< |
break; |
703 |
> |
static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) { |
704 |
> |
if (ws != null) { |
705 |
> |
int len = ws.length; |
706 |
> |
for (int j = 0; j < 2; ++j) { // need two passes for clean sweep |
707 |
> |
for (int i = 0; i < len; ++i) { |
708 |
> |
ForkJoinWorkerThread w = ws[i]; |
709 |
> |
if (w != null && w.sp != w.base) |
710 |
> |
return true; |
711 |
|
} |
712 |
|
} |
630 |
– |
if (checkSubmissions && p.hasQueuedSubmissions()) { |
631 |
– |
activate(); |
632 |
– |
ForkJoinTask<?> t = p.pollSubmission(); |
633 |
– |
if (t != null) |
634 |
– |
return t; |
635 |
– |
} |
636 |
– |
else { |
637 |
– |
long ec = eventCount; // restart on pool event |
638 |
– |
if ((eventCount = p.getEventCount()) == ec) |
639 |
– |
break; |
640 |
– |
} |
641 |
– |
} |
642 |
– |
return null; |
643 |
– |
} |
644 |
– |
|
645 |
– |
/** |
646 |
– |
* Callback from pool.sync to rescan before blocking. If a |
647 |
– |
* task is found, it is pushed so it can be executed upon return. |
648 |
– |
* @return true if found and pushed a task |
649 |
– |
*/ |
650 |
– |
final boolean prescan() { |
651 |
– |
ForkJoinTask<?> t = scan(null, true); |
652 |
– |
if (t != null) { |
653 |
– |
pushTask(t); |
654 |
– |
return true; |
655 |
– |
} |
656 |
– |
else { |
657 |
– |
inactivate(); |
658 |
– |
return false; |
659 |
– |
} |
660 |
– |
} |
661 |
– |
|
662 |
– |
/** |
663 |
– |
* Implements ForkJoinTask.helpJoin |
664 |
– |
*/ |
665 |
– |
final int helpJoinTask(ForkJoinTask<?> joinMe) { |
666 |
– |
ForkJoinTask<?> t = null; |
667 |
– |
int s; |
668 |
– |
while ((s = joinMe.status) >= 0) { |
669 |
– |
if (t == null) { |
670 |
– |
if ((t = scan(joinMe, false)) == null) // block if no work |
671 |
– |
return joinMe.awaitDone(this, false); |
672 |
– |
// else recheck status before exec |
673 |
– |
} |
674 |
– |
else { |
675 |
– |
t.quietlyExec(); |
676 |
– |
t = null; |
677 |
– |
} |
713 |
|
} |
714 |
< |
if (t != null) // unsteal |
680 |
< |
pushTask(t); |
681 |
< |
return s; |
714 |
> |
return false; |
715 |
|
} |
716 |
|
|
717 |
< |
// Support for public static and/or ForkJoinTask methods |
717 |
> |
// Support methods for ForkJoinTask |
718 |
|
|
719 |
|
/** |
720 |
|
* Returns an estimate of the number of tasks in the queue. |
721 |
|
*/ |
722 |
|
final int getQueueSize() { |
723 |
< |
int b = base; |
724 |
< |
int n = sp - b; |
692 |
< |
return n <= 0? 0 : n; // suppress momentarily negative values |
693 |
< |
} |
694 |
< |
|
695 |
< |
/** |
696 |
< |
* Runs one popped task, if available |
697 |
< |
* @return true if ran a task |
698 |
< |
*/ |
699 |
< |
private boolean runLocalTask() { |
700 |
< |
ForkJoinTask<?> t = popTask(); |
701 |
< |
if (t == null) |
702 |
< |
return false; |
703 |
< |
t.quietlyExec(); |
704 |
< |
return true; |
705 |
< |
} |
706 |
< |
|
707 |
< |
/** |
708 |
< |
* Pops or steals a task |
709 |
< |
* @return task, or null if none available |
710 |
< |
*/ |
711 |
< |
private ForkJoinTask<?> getLocalOrStolenTask() { |
712 |
< |
ForkJoinTask<?> t = popTask(); |
713 |
< |
return t != null? t : scan(null, false); |
714 |
< |
} |
715 |
< |
|
716 |
< |
/** |
717 |
< |
* Runs a popped or stolen task, if available |
718 |
< |
* @return true if ran a task |
719 |
< |
*/ |
720 |
< |
private boolean runLocalOrStolenTask() { |
721 |
< |
ForkJoinTask<?> t = getLocalOrStolenTask(); |
722 |
< |
if (t == null) |
723 |
< |
return false; |
724 |
< |
t.quietlyExec(); |
725 |
< |
return true; |
726 |
< |
} |
727 |
< |
|
728 |
< |
/** |
729 |
< |
* Runs tasks until pool isQuiescent |
730 |
< |
*/ |
731 |
< |
final void helpQuiescePool() { |
732 |
< |
activate(); |
733 |
< |
for (;;) { |
734 |
< |
if (!runLocalOrStolenTask()) { |
735 |
< |
inactivate(); |
736 |
< |
if (pool.isQuiescent()) { |
737 |
< |
activate(); // re-activate on exit |
738 |
< |
break; |
739 |
< |
} |
740 |
< |
} |
741 |
< |
} |
723 |
> |
// suppress momentarily negative values |
724 |
> |
return Math.max(0, sp - base); |
725 |
|
} |
726 |
|
|
727 |
|
/** |
729 |
|
* function of number of idle workers. |
730 |
|
*/ |
731 |
|
final int getEstimatedSurplusTaskCount() { |
732 |
+ |
// The halving approximates weighting idle vs non-idle workers |
733 |
|
return (sp - base) - (pool.getIdleThreadCount() >>> 1); |
734 |
|
} |
735 |
|
|
752 |
– |
// Public methods on current thread |
753 |
– |
|
754 |
– |
/** |
755 |
– |
* Returns the pool hosting the current task execution. |
756 |
– |
* @return the pool |
757 |
– |
*/ |
758 |
– |
public static ForkJoinPool getPool() { |
759 |
– |
return ((ForkJoinWorkerThread)(Thread.currentThread())).pool; |
760 |
– |
} |
761 |
– |
|
762 |
– |
/** |
763 |
– |
* Returns the index number of the current worker thread in its |
764 |
– |
* pool. The returned value ranges from zero to the maximum |
765 |
– |
* number of threads (minus one) that have ever been created in |
766 |
– |
* the pool. This method may be useful for applications that |
767 |
– |
* track status or collect results per-worker rather than |
768 |
– |
* per-task. |
769 |
– |
* @return the index number. |
770 |
– |
*/ |
771 |
– |
public static int getPoolIndex() { |
772 |
– |
return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex; |
773 |
– |
} |
774 |
– |
|
775 |
– |
/** |
776 |
– |
* Returns an estimate of the number of tasks waiting to be run by |
777 |
– |
* the current worker thread. This value may be useful for |
778 |
– |
* heuristic decisions about whether to fork other tasks. |
779 |
– |
* @return the number of tasks |
780 |
– |
*/ |
781 |
– |
public static int getLocalQueueSize() { |
782 |
– |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
783 |
– |
getQueueSize(); |
784 |
– |
} |
785 |
– |
|
736 |
|
/** |
737 |
< |
* Returns, but does not remove or execute, the next task locally |
788 |
< |
* queued for execution by the current worker thread. There is no |
789 |
< |
* guarantee that this task will be the next one actually returned |
790 |
< |
* or executed from other polling or execution methods. |
791 |
< |
* @return the next task or null if none |
737 |
> |
* Scans, returning early if joinMe done. |
738 |
|
*/ |
739 |
< |
public static ForkJoinTask<?> peekLocalTask() { |
740 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask(); |
741 |
< |
} |
742 |
< |
|
743 |
< |
/** |
744 |
< |
* Removes and returns, without executing, the next task queued |
745 |
< |
* for execution in the current worker thread's local queue. |
800 |
< |
* @return the next task to execute, or null if none |
801 |
< |
*/ |
802 |
< |
public static ForkJoinTask<?> pollLocalTask() { |
803 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask(); |
804 |
< |
} |
805 |
< |
|
806 |
< |
/** |
807 |
< |
* Execute the next task locally queued by the current worker, if |
808 |
< |
* one is available. |
809 |
< |
* @return true if a task was run; a false return indicates |
810 |
< |
* that no task was available. |
811 |
< |
*/ |
812 |
< |
public static boolean executeLocalTask() { |
813 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
814 |
< |
runLocalTask(); |
739 |
> |
final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) { |
740 |
> |
ForkJoinTask<?> t = pollTask(); |
741 |
> |
if (t != null && joinMe.status < 0 && sp == base) { |
742 |
> |
pushTask(t); // unsteal if done and this task would be stealable |
743 |
> |
t = null; |
744 |
> |
} |
745 |
> |
return t; |
746 |
|
} |
747 |
|
|
748 |
|
/** |
749 |
< |
* Removes and returns, without executing, the next task queued |
819 |
< |
* for execution in the current worker thread's local queue or if |
820 |
< |
* none, a task stolen from another worker, if one is available. |
821 |
< |
* A null return does not necessarily imply that all tasks are |
822 |
< |
* completed, only that there are currently none available. |
823 |
< |
* @return the next task to execute, or null if none |
749 |
> |
* Runs tasks until {@code pool.isQuiescent()}. |
750 |
|
*/ |
751 |
< |
public static ForkJoinTask<?> pollTask() { |
826 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
827 |
< |
getLocalOrStolenTask(); |
828 |
< |
} |
829 |
< |
|
830 |
< |
/** |
831 |
< |
* Helps this program complete by processing a local or stolen |
832 |
< |
* task, if one is available. This method may be useful when |
833 |
< |
* several tasks are forked, and only one of them must be joined, |
834 |
< |
* as in: |
835 |
< |
* |
836 |
< |
* <pre> |
837 |
< |
* while (!t1.isDone() && !t2.isDone()) |
838 |
< |
* ForkJoinWorkerThread.executeTask(); |
839 |
< |
* </pre> |
840 |
< |
* |
841 |
< |
* @return true if a task was run; a false return indicates |
842 |
< |
* that no task was available. |
843 |
< |
*/ |
844 |
< |
public static boolean executeTask() { |
845 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
846 |
< |
runLocalOrStolenTask(); |
847 |
< |
} |
848 |
< |
|
849 |
< |
// Per-worker exported random numbers |
850 |
< |
|
851 |
< |
// Same constants as java.util.Random |
852 |
< |
final static long JURandomMultiplier = 0x5DEECE66DL; |
853 |
< |
final static long JURandomAddend = 0xBL; |
854 |
< |
final static long JURandomMask = (1L << 48) - 1; |
855 |
< |
|
856 |
< |
private final int nextJURandom(int bits) { |
857 |
< |
long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) & |
858 |
< |
JURandomMask; |
859 |
< |
juRandomSeed = next; |
860 |
< |
return (int)(next >>> (48 - bits)); |
861 |
< |
} |
862 |
< |
|
863 |
< |
private final int nextJURandomInt(int n) { |
864 |
< |
if (n <= 0) |
865 |
< |
throw new IllegalArgumentException("n must be positive"); |
866 |
< |
int bits = nextJURandom(31); |
867 |
< |
if ((n & -n) == n) |
868 |
< |
return (int)((n * (long)bits) >> 31); |
869 |
< |
|
751 |
> |
final void helpQuiescePool() { |
752 |
|
for (;;) { |
753 |
< |
int val = bits % n; |
754 |
< |
if (bits - val + (n-1) >= 0) |
755 |
< |
return val; |
756 |
< |
bits = nextJURandom(31); |
757 |
< |
} |
876 |
< |
} |
877 |
< |
|
878 |
< |
private final long nextJURandomLong() { |
879 |
< |
return ((long)(nextJURandom(32)) << 32) + nextJURandom(32); |
880 |
< |
} |
881 |
< |
|
882 |
< |
private final long nextJURandomLong(long n) { |
883 |
< |
if (n <= 0) |
884 |
< |
throw new IllegalArgumentException("n must be positive"); |
885 |
< |
long offset = 0; |
886 |
< |
while (n >= Integer.MAX_VALUE) { // randomly pick half range |
887 |
< |
int bits = nextJURandom(2); // 2nd bit for odd vs even split |
888 |
< |
long half = n >>> 1; |
889 |
< |
long nextn = ((bits & 2) == 0)? half : n - half; |
890 |
< |
if ((bits & 1) == 0) |
891 |
< |
offset += n - nextn; |
892 |
< |
n = nextn; |
753 |
> |
ForkJoinTask<?> t = pollTask(); |
754 |
> |
if (t != null) |
755 |
> |
t.quietlyExec(); |
756 |
> |
else if (tryInactivate() && pool.isQuiescent()) |
757 |
> |
break; |
758 |
|
} |
759 |
< |
return offset + nextJURandomInt((int)n); |
759 |
> |
do {} while (!tryActivate()); // re-activate on exit |
760 |
|
} |
761 |
|
|
762 |
< |
private final double nextJURandomDouble() { |
898 |
< |
return (((long)(nextJURandom(26)) << 27) + nextJURandom(27)) |
899 |
< |
/ (double)(1L << 53); |
900 |
< |
} |
762 |
> |
// Unsafe mechanics |
763 |
|
|
764 |
< |
/** |
765 |
< |
* Returns a random integer using a per-worker random |
766 |
< |
* number generator with the same properties as |
767 |
< |
* {@link java.util.Random#nextInt} |
768 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
769 |
< |
* value from this worker's random number generator's sequence |
770 |
< |
*/ |
909 |
< |
public static int nextRandomInt() { |
910 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
911 |
< |
nextJURandom(32); |
912 |
< |
} |
913 |
< |
|
914 |
< |
/** |
915 |
< |
* Returns a random integer using a per-worker random |
916 |
< |
* number generator with the same properties as |
917 |
< |
* {@link java.util.Random#nextInt(int)} |
918 |
< |
* @param n the bound on the random number to be returned. Must be |
919 |
< |
* positive. |
920 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
921 |
< |
* value between {@code 0} (inclusive) and {@code n} (exclusive) |
922 |
< |
* from this worker's random number generator's sequence |
923 |
< |
* @throws IllegalArgumentException if n is not positive |
924 |
< |
*/ |
925 |
< |
public static int nextRandomInt(int n) { |
926 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
927 |
< |
nextJURandomInt(n); |
928 |
< |
} |
764 |
> |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
765 |
> |
private static final long spOffset = |
766 |
> |
objectFieldOffset("sp", ForkJoinWorkerThread.class); |
767 |
> |
private static final long runStateOffset = |
768 |
> |
objectFieldOffset("runState", ForkJoinWorkerThread.class); |
769 |
> |
private static final long qBase; |
770 |
> |
private static final int qShift; |
771 |
|
|
772 |
< |
/** |
773 |
< |
* Returns a random long using a per-worker random |
774 |
< |
* number generator with the same properties as |
775 |
< |
* {@link java.util.Random#nextLong} |
776 |
< |
* @return the next pseudorandom, uniformly distributed {@code long} |
777 |
< |
* value from this worker's random number generator's sequence |
936 |
< |
*/ |
937 |
< |
public static long nextRandomLong() { |
938 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
939 |
< |
nextJURandomLong(); |
772 |
> |
static { |
773 |
> |
qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class); |
774 |
> |
int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class); |
775 |
> |
if ((s & (s-1)) != 0) |
776 |
> |
throw new Error("data type scale not a power of two"); |
777 |
> |
qShift = 31 - Integer.numberOfLeadingZeros(s); |
778 |
|
} |
779 |
|
|
780 |
< |
/** |
781 |
< |
* Returns a random integer using a per-worker random |
782 |
< |
* number generator with the same properties as |
783 |
< |
* {@link java.util.Random#nextInt(int)} |
784 |
< |
* @param n the bound on the random number to be returned. Must be |
785 |
< |
* positive. |
786 |
< |
* @return the next pseudorandom, uniformly distributed {@code int} |
787 |
< |
* value between {@code 0} (inclusive) and {@code n} (exclusive) |
788 |
< |
* from this worker's random number generator's sequence |
951 |
< |
* @throws IllegalArgumentException if n is not positive |
952 |
< |
*/ |
953 |
< |
public static long nextRandomLong(long n) { |
954 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
955 |
< |
nextJURandomLong(n); |
780 |
> |
private static long objectFieldOffset(String field, Class<?> klazz) { |
781 |
> |
try { |
782 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
783 |
> |
} catch (NoSuchFieldException e) { |
784 |
> |
// Convert Exception to corresponding Error |
785 |
> |
NoSuchFieldError error = new NoSuchFieldError(field); |
786 |
> |
error.initCause(e); |
787 |
> |
throw error; |
788 |
> |
} |
789 |
|
} |
790 |
|
|
791 |
|
/** |
792 |
< |
* Returns a random double using a per-worker random |
793 |
< |
* number generator with the same properties as |
794 |
< |
* {@link java.util.Random#nextDouble} |
795 |
< |
* @return the next pseudorandom, uniformly distributed {@code double} |
796 |
< |
* value between {@code 0.0} and {@code 1.0} from this |
964 |
< |
* worker's random number generator's sequence |
792 |
> |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
793 |
> |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
794 |
> |
* into a jdk. |
795 |
> |
* |
796 |
> |
* @return a sun.misc.Unsafe |
797 |
|
*/ |
798 |
< |
public static double nextRandomDouble() { |
967 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
968 |
< |
nextJURandomDouble(); |
969 |
< |
} |
970 |
< |
|
971 |
< |
// Temporary Unsafe mechanics for preliminary release |
972 |
< |
|
973 |
< |
static final Unsafe _unsafe; |
974 |
< |
static final long baseOffset; |
975 |
< |
static final long spOffset; |
976 |
< |
static final long qBase; |
977 |
< |
static final int qShift; |
978 |
< |
static final long runStateOffset; |
979 |
< |
static { |
798 |
> |
private static sun.misc.Unsafe getUnsafe() { |
799 |
|
try { |
800 |
< |
if (ForkJoinWorkerThread.class.getClassLoader() != null) { |
801 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
802 |
< |
f.setAccessible(true); |
803 |
< |
_unsafe = (Unsafe)f.get(null); |
800 |
> |
return sun.misc.Unsafe.getUnsafe(); |
801 |
> |
} catch (SecurityException se) { |
802 |
> |
try { |
803 |
> |
return java.security.AccessController.doPrivileged |
804 |
> |
(new java.security |
805 |
> |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
806 |
> |
public sun.misc.Unsafe run() throws Exception { |
807 |
> |
java.lang.reflect.Field f = sun.misc |
808 |
> |
.Unsafe.class.getDeclaredField("theUnsafe"); |
809 |
> |
f.setAccessible(true); |
810 |
> |
return (sun.misc.Unsafe) f.get(null); |
811 |
> |
}}); |
812 |
> |
} catch (java.security.PrivilegedActionException e) { |
813 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
814 |
> |
e.getCause()); |
815 |
|
} |
986 |
– |
else |
987 |
– |
_unsafe = Unsafe.getUnsafe(); |
988 |
– |
baseOffset = _unsafe.objectFieldOffset |
989 |
– |
(ForkJoinWorkerThread.class.getDeclaredField("base")); |
990 |
– |
spOffset = _unsafe.objectFieldOffset |
991 |
– |
(ForkJoinWorkerThread.class.getDeclaredField("sp")); |
992 |
– |
runStateOffset = _unsafe.objectFieldOffset |
993 |
– |
(ForkJoinWorkerThread.class.getDeclaredField("runState")); |
994 |
– |
qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class); |
995 |
– |
int s = _unsafe.arrayIndexScale(ForkJoinTask[].class); |
996 |
– |
if ((s & (s-1)) != 0) |
997 |
– |
throw new Error("data type scale not a power of two"); |
998 |
– |
qShift = 31 - Integer.numberOfLeadingZeros(s); |
999 |
– |
} catch (Exception e) { |
1000 |
– |
throw new RuntimeException("Could not initialize intrinsics", e); |
816 |
|
} |
817 |
|
} |
818 |
|
} |