ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.31
Committed: Mon Sep 20 20:42:37 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.30: +1 -1 lines
Log Message:
whitespace

File Contents

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