ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.19
Committed: Tue Aug 17 18:31:59 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.18: +55 -43 lines
Log Message:
Reduce resources during periods without use

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.tryAwaitJoin).
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 * The wakeup interval (in nanoseconds) for the oldest worker
166 * suspended as spare. On each wakeup not signalled by a
167 * resumption, it may ask the pool to reduce the number of spares.
168 */
169 private static final long TRIM_RATE_NANOS =
170 5L * 1000L * 1000L * 1000L; // 5sec
171
172 /**
173 * Capacity of work-stealing queue array upon initialization.
174 * Must be a power of two. Initial size must be at least 4, but is
175 * padded to minimize cache effects.
176 */
177 private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
178
179 /**
180 * Maximum work-stealing queue array size. Must be less than or
181 * equal to 1 << 28 to ensure lack of index wraparound. (This
182 * is less than usual bounds, because we need leftshift by 3
183 * to be in int range).
184 */
185 private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
186
187 /**
188 * The pool this thread works in. Accessed directly by ForkJoinTask.
189 */
190 final ForkJoinPool pool;
191
192 /**
193 * The work-stealing queue array. Size must be a power of two.
194 * Initialized in onStart, to improve memory locality.
195 */
196 private ForkJoinTask<?>[] queue;
197
198 /**
199 * Index (mod queue.length) of least valid queue slot, which is
200 * always the next position to steal from if nonempty.
201 */
202 private volatile int base;
203
204 /**
205 * Index (mod queue.length) of next queue slot to push to or pop
206 * from. It is written only by owner thread, and accessed by other
207 * threads only after reading (volatile) base. Both sp and base
208 * are allowed to wrap around on overflow, but (sp - base) still
209 * estimates size.
210 */
211 private int sp;
212
213 /**
214 * The index of most recent stealer, used as a hint to avoid
215 * traversal in method helpJoinTask. This is only a hint because a
216 * worker might have had multiple steals and this only holds one
217 * of them (usually the most current). Declared non-volatile,
218 * relying on other prevailing sync to keep reasonably current.
219 */
220 private int stealHint;
221
222 /**
223 * Run state of this worker. In addition to the usual run levels,
224 * tracks if this worker is suspended as a spare, and if it was
225 * killed (trimmed) while suspended. However, "active" status is
226 * maintained separately and modified only in conjunction with
227 * CASes of the pool's runState (which are currently sadly manually
228 * inlined for performance.)
229 */
230 private volatile int runState;
231
232 private static final int TERMINATING = 0x01;
233 private static final int TERMINATED = 0x02;
234 private static final int SUSPENDED = 0x04; // inactive spare
235 private static final int TRIMMED = 0x08; // killed while suspended
236
237 /**
238 * Number of steals, transferred and reset in pool callbacks pool
239 * when idle Accessed directly by pool.
240 */
241 int stealCount;
242
243 /**
244 * Seed for random number generator for choosing steal victims.
245 * Uses Marsaglia xorshift. Must be initialized as nonzero.
246 */
247 private int seed;
248
249 /**
250 * Activity status. When true, this worker is considered active.
251 * Accessed directly by pool. Must be false upon construction.
252 */
253 boolean active;
254
255 /**
256 * True if use local fifo, not default lifo, for local polling.
257 * Shadows value from ForkJoinPool.
258 */
259 private final boolean locallyFifo;
260
261 /**
262 * Index of this worker in pool array. Set once by pool before
263 * running, and accessed directly by pool to locate this worker in
264 * its workers array.
265 */
266 int poolIndex;
267
268 /**
269 * The last pool event waited for. Accessed only by pool in
270 * callback methods invoked within this thread.
271 */
272 int lastEventCount;
273
274 /**
275 * Encoded index and event count of next event waiter. Used only
276 * by ForkJoinPool for managing event waiters.
277 */
278 volatile long nextWaiter;
279
280 /**
281 * Number of times this thread suspended as spare
282 */
283 int spareCount;
284
285 /**
286 * Encoded index and count of next spare waiter. Used only
287 * by ForkJoinPool for managing spares.
288 */
289 volatile int nextSpare;
290
291 /**
292 * The task currently being joined, set only when actively trying
293 * to helpStealer. Written only by current thread, but read by
294 * others.
295 */
296 private volatile ForkJoinTask<?> currentJoin;
297
298 /**
299 * The task most recently stolen from another worker (or
300 * submission queue). Not volatile because always read/written in
301 * presence of related volatiles in those cases where it matters.
302 */
303 private ForkJoinTask<?> currentSteal;
304
305 /**
306 * Creates a ForkJoinWorkerThread operating in the given pool.
307 *
308 * @param pool the pool this thread works in
309 * @throws NullPointerException if pool is null
310 */
311 protected ForkJoinWorkerThread(ForkJoinPool pool) {
312 this.pool = pool;
313 this.locallyFifo = pool.locallyFifo;
314 setDaemon(true);
315 // To avoid exposing construction details to subclasses,
316 // remaining initialization is in start() and onStart()
317 }
318
319 /**
320 * Performs additional initialization and starts this thread
321 */
322 final void start(int poolIndex, UncaughtExceptionHandler ueh) {
323 this.poolIndex = poolIndex;
324 if (ueh != null)
325 setUncaughtExceptionHandler(ueh);
326 start();
327 }
328
329 // Public/protected methods
330
331 /**
332 * Returns the pool hosting this thread.
333 *
334 * @return the pool
335 */
336 public ForkJoinPool getPool() {
337 return pool;
338 }
339
340 /**
341 * Returns the index number of this thread in its pool. The
342 * returned value ranges from zero to the maximum number of
343 * threads (minus one) that have ever been created in the pool.
344 * This method may be useful for applications that track status or
345 * collect results per-worker rather than per-task.
346 *
347 * @return the index number
348 */
349 public int getPoolIndex() {
350 return poolIndex;
351 }
352
353 /**
354 * Initializes internal state after construction but before
355 * processing any tasks. If you override this method, you must
356 * invoke super.onStart() at the beginning of the method.
357 * Initialization requires care: Most fields must have legal
358 * default values, to ensure that attempted accesses from other
359 * threads work correctly even before this thread starts
360 * processing tasks.
361 */
362 protected void onStart() {
363 int rs = seedGenerator.nextInt();
364 seed = rs == 0? 1 : rs; // seed must be nonzero
365
366 // Allocate name string and arrays in this thread
367 String pid = Integer.toString(pool.getPoolNumber());
368 String wid = Integer.toString(poolIndex);
369 setName("ForkJoinPool-" + pid + "-worker-" + wid);
370
371 queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
372 }
373
374 /**
375 * Performs cleanup associated with termination of this worker
376 * thread. If you override this method, you must invoke
377 * {@code super.onTermination} at the end of the overridden method.
378 *
379 * @param exception the exception causing this thread to abort due
380 * to an unrecoverable error, or {@code null} if completed normally
381 */
382 protected void onTermination(Throwable exception) {
383 try {
384 ForkJoinPool p = pool;
385 if (active) {
386 int a; // inline p.tryDecrementActiveCount
387 active = false;
388 do {} while(!UNSAFE.compareAndSwapInt
389 (p, poolRunStateOffset, a = p.runState, a - 1));
390 }
391 cancelTasks();
392 setTerminated();
393 p.workerTerminated(this);
394 } catch (Throwable ex) { // Shouldn't ever happen
395 if (exception == null) // but if so, at least rethrown
396 exception = ex;
397 } finally {
398 if (exception != null)
399 UNSAFE.throwException(exception);
400 }
401 }
402
403 /**
404 * This method is required to be public, but should never be
405 * called explicitly. It performs the main run loop to execute
406 * ForkJoinTasks.
407 */
408 public void run() {
409 Throwable exception = null;
410 try {
411 onStart();
412 mainLoop();
413 } catch (Throwable ex) {
414 exception = ex;
415 } finally {
416 onTermination(exception);
417 }
418 }
419
420 // helpers for run()
421
422 /**
423 * Find and execute tasks and check status while running
424 */
425 private void mainLoop() {
426 int misses = 0; // track consecutive times failed to find work; max 2
427 ForkJoinPool p = pool;
428 for (;;) {
429 p.preStep(this, misses);
430 if (runState != 0)
431 break;
432 misses = ((tryExecSteal() || tryExecSubmission()) ? 0 :
433 (misses < 2 ? misses + 1 : 2));
434 }
435 }
436
437 /**
438 * Try to steal a task and execute it
439 *
440 * @return true if ran a task
441 */
442 private boolean tryExecSteal() {
443 ForkJoinTask<?> t;
444 if ((t = scan()) != null) {
445 t.quietlyExec();
446 currentSteal = null;
447 if (sp != base)
448 execLocalTasks();
449 return true;
450 }
451 return false;
452 }
453
454 /**
455 * If a submission exists, try to activate and run it;
456 *
457 * @return true if ran a task
458 */
459 private boolean tryExecSubmission() {
460 ForkJoinPool p = pool;
461 while (p.hasQueuedSubmissions()) {
462 ForkJoinTask<?> t; int a;
463 if (active || // ugly/hacky: inline p.tryIncrementActiveCount
464 (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
465 a = p.runState, a + 1))) {
466 if ((t = p.pollSubmission()) != null) {
467 currentSteal = t;
468 t.quietlyExec();
469 currentSteal = null;
470 if (sp != base)
471 execLocalTasks();
472 return true;
473 }
474 }
475 }
476 return false;
477 }
478
479 /**
480 * Runs local tasks until queue is empty or shut down. Call only
481 * while active.
482 */
483 private void execLocalTasks() {
484 while (runState == 0) {
485 ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
486 if (t != null)
487 t.quietlyExec();
488 else if (sp == base)
489 break;
490 }
491 }
492
493 /*
494 * Intrinsics-based atomic writes for queue slots. These are
495 * basically the same as methods in AtomicObjectArray, but
496 * specialized for (1) ForkJoinTask elements (2) requirement that
497 * nullness and bounds checks have already been performed by
498 * callers and (3) effective offsets are known not to overflow
499 * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
500 * need corresponding version for reads: plain array reads are OK
501 * because they protected by other volatile reads and are
502 * confirmed by CASes.
503 *
504 * Most uses don't actually call these methods, but instead contain
505 * inlined forms that enable more predictable optimization. We
506 * don't define the version of write used in pushTask at all, but
507 * instead inline there a store-fenced array slot write.
508 */
509
510 /**
511 * CASes slot i of array q from t to null. Caller must ensure q is
512 * non-null and index is in range.
513 */
514 private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
515 ForkJoinTask<?> t) {
516 return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
517 }
518
519 /**
520 * Performs a volatile write of the given task at given slot of
521 * array q. Caller must ensure q is non-null and index is in
522 * range. This method is used only during resets and backouts.
523 */
524 private static final void writeSlot(ForkJoinTask<?>[] q, int i,
525 ForkJoinTask<?> t) {
526 UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
527 }
528
529 // queue methods
530
531 /**
532 * Pushes a task. Call only from this thread.
533 *
534 * @param t the task. Caller must ensure non-null.
535 */
536 final void pushTask(ForkJoinTask<?> t) {
537 ForkJoinTask<?>[] q = queue;
538 int mask = q.length - 1; // implicit assert q != null
539 int s = sp++; // ok to increment sp before slot write
540 UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
541 if ((s -= base) == 0)
542 pool.signalWork(); // was empty
543 else if (s == mask)
544 growQueue(); // is full
545 }
546
547 /**
548 * Tries to take a task from the base of the queue, failing if
549 * empty or contended. Note: Specializations of this code appear
550 * in locallyDeqTask and elsewhere.
551 *
552 * @return a task, or null if none or contended
553 */
554 final ForkJoinTask<?> deqTask() {
555 ForkJoinTask<?> t;
556 ForkJoinTask<?>[] q;
557 int b, i;
558 if (sp != (b = base) &&
559 (q = queue) != null && // must read q after b
560 (t = q[i = (q.length - 1) & b]) != null && base == b &&
561 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
562 base = b + 1;
563 return t;
564 }
565 return null;
566 }
567
568 /**
569 * Tries to take a task from the base of own queue. Assumes active
570 * status. Called only by current thread.
571 *
572 * @return a task, or null if none
573 */
574 final ForkJoinTask<?> locallyDeqTask() {
575 ForkJoinTask<?>[] q = queue;
576 if (q != null) {
577 ForkJoinTask<?> t;
578 int b, i;
579 while (sp != (b = base)) {
580 if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
581 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
582 t, null)) {
583 base = b + 1;
584 return t;
585 }
586 }
587 }
588 return null;
589 }
590
591 /**
592 * Returns a popped task, or null if empty. Assumes active status.
593 * Called only by current thread.
594 */
595 private ForkJoinTask<?> popTask() {
596 ForkJoinTask<?>[] q = queue;
597 if (q != null) {
598 int s;
599 while ((s = sp) != base) {
600 int i = (q.length - 1) & --s;
601 long u = (i << qShift) + qBase; // raw offset
602 ForkJoinTask<?> t = q[i];
603 if (t == null) // lost to stealer
604 break;
605 if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
606 sp = s; // putOrderedInt may encourage more timely write
607 // UNSAFE.putOrderedInt(this, spOffset, s);
608 return t;
609 }
610 }
611 }
612 return null;
613 }
614
615 /**
616 * Specialized version of popTask to pop only if topmost element
617 * is the given task. Called only by current thread while
618 * active.
619 *
620 * @param t the task. Caller must ensure non-null.
621 */
622 final boolean unpushTask(ForkJoinTask<?> t) {
623 int s;
624 ForkJoinTask<?>[] q = queue;
625 if ((s = sp) != base && q != null &&
626 UNSAFE.compareAndSwapObject
627 (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
628 sp = s;
629 // UNSAFE.putOrderedInt(this, spOffset, s);
630 return true;
631 }
632 return false;
633 }
634
635 /**
636 * Returns next task or null if empty or contended
637 */
638 final ForkJoinTask<?> peekTask() {
639 ForkJoinTask<?>[] q = queue;
640 if (q == null)
641 return null;
642 int mask = q.length - 1;
643 int i = locallyFifo ? base : (sp - 1);
644 return q[i & mask];
645 }
646
647 /**
648 * Doubles queue array size. Transfers elements by emulating
649 * steals (deqs) from old array and placing, oldest first, into
650 * new array.
651 */
652 private void growQueue() {
653 ForkJoinTask<?>[] oldQ = queue;
654 int oldSize = oldQ.length;
655 int newSize = oldSize << 1;
656 if (newSize > MAXIMUM_QUEUE_CAPACITY)
657 throw new RejectedExecutionException("Queue capacity exceeded");
658 ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
659
660 int b = base;
661 int bf = b + oldSize;
662 int oldMask = oldSize - 1;
663 int newMask = newSize - 1;
664 do {
665 int oldIndex = b & oldMask;
666 ForkJoinTask<?> t = oldQ[oldIndex];
667 if (t != null && !casSlotNull(oldQ, oldIndex, t))
668 t = null;
669 writeSlot(newQ, b & newMask, t);
670 } while (++b != bf);
671 pool.signalWork();
672 }
673
674 /**
675 * Computes next value for random victim probe in scan(). Scans
676 * don't require a very high quality generator, but also not a
677 * crummy one. Marsaglia xor-shift is cheap and works well enough.
678 * Note: This is manually inlined in scan()
679 */
680 private static final int xorShift(int r) {
681 r ^= r << 13;
682 r ^= r >>> 17;
683 return r ^ (r << 5);
684 }
685
686 /**
687 * Tries to steal a task from another worker. Starts at a random
688 * index of workers array, and probes workers until finding one
689 * with non-empty queue or finding that all are empty. It
690 * randomly selects the first n probes. If these are empty, it
691 * resorts to a circular sweep, which is necessary to accurately
692 * set active status. (The circular sweep uses steps of
693 * approximately half the array size plus 1, to avoid bias
694 * stemming from leftmost packing of the array in ForkJoinPool.)
695 *
696 * This method must be both fast and quiet -- usually avoiding
697 * memory accesses that could disrupt cache sharing etc other than
698 * those needed to check for and take tasks (or to activate if not
699 * already active). This accounts for, among other things,
700 * updating random seed in place without storing it until exit.
701 *
702 * @return a task, or null if none found
703 */
704 private ForkJoinTask<?> scan() {
705 ForkJoinPool p = pool;
706 ForkJoinWorkerThread[] ws; // worker array
707 int n; // upper bound of #workers
708 if ((ws = p.workers) != null && (n = ws.length) > 1) {
709 boolean canSteal = active; // shadow active status
710 int r = seed; // extract seed once
711 int mask = n - 1;
712 int j = -n; // loop counter
713 int k = r; // worker index, random if j < 0
714 for (;;) {
715 ForkJoinWorkerThread v = ws[k & mask];
716 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
717 if (v != null && v.base != v.sp) {
718 ForkJoinTask<?>[] q; int b, a;
719 if ((canSteal || // Ugly/hacky: inline
720 (canSteal = active = // p.tryIncrementActiveCount
721 UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
722 a = p.runState, a + 1))) &&
723 (q = v.queue) != null && (b = v.base) != v.sp) {
724 int i = (q.length - 1) & b;
725 long u = (i << qShift) + qBase; // raw offset
726 ForkJoinTask<?> t = q[i];
727 if (v.base == b && t != null &&
728 UNSAFE.compareAndSwapObject(q, u, t, null)) {
729 int pid = poolIndex;
730 currentSteal = t;
731 v.stealHint = pid;
732 v.base = b + 1;
733 seed = r;
734 ++stealCount;
735 return t;
736 }
737 }
738 j = -n;
739 k = r; // restart on contention
740 }
741 else if (++j <= 0)
742 k = r;
743 else if (j <= n)
744 k += (n >>> 1) | 1;
745 else
746 break;
747 }
748 }
749 return null;
750 }
751
752 // Run State management
753
754 // status check methods used mainly by ForkJoinPool
755 final boolean isRunning() { return runState == 0; }
756 final boolean isTerminating() { return (runState & TERMINATING) != 0; }
757 final boolean isTerminated() { return (runState & TERMINATED) != 0; }
758 final boolean isSuspended() { return (runState & SUSPENDED) != 0; }
759 final boolean isTrimmed() { return (runState & TRIMMED) != 0; }
760
761 /**
762 * Sets state to TERMINATING. Does NOT unpark or interrupt
763 * to wake up if currently blocked.
764 */
765 final void shutdown() {
766 for (;;) {
767 int s = runState;
768 if ((s & (TERMINATING|TERMINATED)) != 0)
769 break;
770 if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
771 if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
772 (s & ~SUSPENDED) |
773 (TRIMMED|TERMINATING)))
774 break;
775 }
776 else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
777 s | TERMINATING))
778 break;
779 }
780 }
781
782 /**
783 * Sets state to TERMINATED. Called only by onTermination()
784 */
785 private void setTerminated() {
786 int s;
787 do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
788 s = runState,
789 s | (TERMINATING|TERMINATED)));
790 }
791
792 /**
793 * If suspended, tries to set status to unsuspended.
794 *
795 * @return true if successful
796 */
797 final boolean tryUnsuspend() {
798 int s;
799 while (((s = runState) & SUSPENDED) != 0) {
800 if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
801 s & ~SUSPENDED))
802 return true;
803 }
804 return false;
805 }
806
807 /**
808 * Sets suspended status and blocks as spare until resumed
809 * or shutdown.
810 */
811 final void suspendAsSpare() {
812 for (;;) { // set suspended unless terminating
813 int s = runState;
814 if ((s & TERMINATING) != 0) { // must kill
815 if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
816 s | (TRIMMED | TERMINATING)))
817 return;
818 }
819 else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
820 s | SUSPENDED))
821 break;
822 }
823 ForkJoinPool p = pool;
824 p.pushSpare(this);
825 lastEventCount = 0; // reset upon resume
826 while ((runState & SUSPENDED) != 0) {
827 if (p.tryAccumulateStealCount(this)) {
828 boolean untimed = nextSpare != 0;
829 long startTime = untimed? 0 : System.nanoTime();
830 interrupted(); // clear/ignore interrupts
831 if ((runState & SUSPENDED) == 0)
832 break;
833 if (untimed) // untimed
834 LockSupport.park(this);
835 else {
836 LockSupport.parkNanos(this, TRIM_RATE_NANOS);
837 if ((runState & SUSPENDED) == 0)
838 break;
839 if (System.nanoTime() - startTime >= TRIM_RATE_NANOS)
840 p.tryShutdownSpare();
841 }
842 }
843 }
844 }
845
846 // Misc support methods for ForkJoinPool
847
848 /**
849 * Returns an estimate of the number of tasks in the queue. Also
850 * used by ForkJoinTask.
851 */
852 final int getQueueSize() {
853 int n; // external calls must read base first
854 return (n = -base + sp) <= 0 ? 0 : n;
855 }
856
857 /**
858 * Removes and cancels all tasks in queue. Can be called from any
859 * thread.
860 */
861 final void cancelTasks() {
862 ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
863 if (cj != null) {
864 currentJoin = null;
865 cj.cancelIgnoringExceptions();
866 try {
867 this.interrupt(); // awaken wait
868 } catch (SecurityException ignore) {
869 }
870 }
871 ForkJoinTask<?> cs = currentSteal;
872 if (cs != null) {
873 currentSteal = null;
874 cs.cancelIgnoringExceptions();
875 }
876 while (base != sp) {
877 ForkJoinTask<?> t = deqTask();
878 if (t != null)
879 t.cancelIgnoringExceptions();
880 }
881 }
882
883 /**
884 * Drains tasks to given collection c.
885 *
886 * @return the number of tasks drained
887 */
888 final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
889 int n = 0;
890 while (base != sp) {
891 ForkJoinTask<?> t = deqTask();
892 if (t != null) {
893 c.add(t);
894 ++n;
895 }
896 }
897 return n;
898 }
899
900 // Support methods for ForkJoinTask
901
902 /**
903 * Gets and removes a local task.
904 *
905 * @return a task, if available
906 */
907 final ForkJoinTask<?> pollLocalTask() {
908 ForkJoinPool p = pool;
909 while (sp != base) {
910 int a; // inline p.tryIncrementActiveCount
911 if (active ||
912 (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
913 a = p.runState, a + 1)))
914 return locallyFifo? locallyDeqTask() : popTask();
915 }
916 return null;
917 }
918
919 /**
920 * Gets and removes a local or stolen task.
921 *
922 * @return a task, if available
923 */
924 final ForkJoinTask<?> pollTask() {
925 ForkJoinTask<?> t = pollLocalTask();
926 if (t == null) {
927 t = scan();
928 currentSteal = null; // cannot retain/track/help
929 }
930 return t;
931 }
932
933 /**
934 * Possibly runs some tasks and/or blocks, until task is done.
935 *
936 * @param joinMe the task to join
937 */
938 final void joinTask(ForkJoinTask<?> joinMe) {
939 // currentJoin only written by this thread; only need ordered store
940 ForkJoinTask<?> prevJoin = currentJoin;
941 UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
942 if (sp != base)
943 localHelpJoinTask(joinMe);
944 if (joinMe.status >= 0)
945 pool.awaitJoin(joinMe, this);
946 UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
947 }
948
949 /**
950 * Run tasks in local queue until given task is done.
951 *
952 * @param joinMe the task to join
953 */
954 private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
955 int s;
956 ForkJoinTask<?>[] q;
957 while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
958 int i = (q.length - 1) & --s;
959 long u = (i << qShift) + qBase; // raw offset
960 ForkJoinTask<?> t = q[i];
961 if (t == null) // lost to a stealer
962 break;
963 if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
964 /*
965 * This recheck (and similarly in helpJoinTask)
966 * handles cases where joinMe is independently
967 * cancelled or forced even though there is other work
968 * available. Back out of the pop by putting t back
969 * into slot before we commit by writing sp.
970 */
971 if (joinMe.status < 0) {
972 UNSAFE.putObjectVolatile(q, u, t);
973 break;
974 }
975 sp = s;
976 // UNSAFE.putOrderedInt(this, spOffset, s);
977 t.quietlyExec();
978 }
979 }
980 }
981
982 /**
983 * Tries to locate and help perform tasks for a stealer of the
984 * given task, or in turn one of its stealers. Traces
985 * currentSteal->currentJoin links looking for a thread working on
986 * a descendant of the given task and with a non-empty queue to
987 * steal back and execute tasks from.
988 *
989 * The implementation is very branchy to cope with the potential
990 * inconsistencies or loops encountering chains that are stale,
991 * unknown, or of length greater than MAX_HELP_DEPTH links. All
992 * of these cases are dealt with by just returning back to the
993 * caller, who is expected to retry if other join mechanisms also
994 * don't work out.
995 *
996 * @param joinMe the task to join
997 */
998 final void helpJoinTask(ForkJoinTask<?> joinMe) {
999 ForkJoinWorkerThread[] ws = pool.workers;
1000 int n; // need at least 2 workers
1001 if (ws != null && (n = ws.length) > 1 && joinMe.status >= 0) {
1002 ForkJoinTask<?> task = joinMe; // base of chain
1003 ForkJoinWorkerThread thread = this; // thread with stolen task
1004 for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1005 // Try to find v, the stealer of task, by first using hint
1006 ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1007 if (v == null || v.currentSteal != task) {
1008 for (int j = 0; ; ++j) { // search array
1009 if (j < n) {
1010 if ((v = ws[j]) != null) {
1011 if (task.status < 0)
1012 return; // stale or done
1013 if (v.currentSteal == task) {
1014 thread.stealHint = j;
1015 break; // save hint for next time
1016 }
1017 }
1018 }
1019 else
1020 return; // no stealer
1021 }
1022 }
1023 // Try to help v, using specialized form of deqTask
1024 int b;
1025 ForkJoinTask<?>[] q;
1026 while ((b = v.base) != v.sp && (q = v.queue) != null) {
1027 int i = (q.length - 1) & b;
1028 long u = (i << qShift) + qBase;
1029 ForkJoinTask<?> t = q[i];
1030 if (task.status < 0)
1031 return; // stale or done
1032 if (v.base == b) {
1033 if (t == null)
1034 return; // producer stalled
1035 if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
1036 if (joinMe.status < 0) {
1037 UNSAFE.putObjectVolatile(q, u, t);
1038 return; // back out on cancel
1039 }
1040 int pid = poolIndex;
1041 ForkJoinTask<?> prevSteal = currentSteal;
1042 currentSteal = t;
1043 v.stealHint = pid;
1044 v.base = b + 1;
1045 t.quietlyExec();
1046 currentSteal = prevSteal;
1047 }
1048 }
1049 if (joinMe.status < 0)
1050 return;
1051 }
1052 // Try to descend to find v's stealer
1053 ForkJoinTask<?> next = v.currentJoin;
1054 if (task.status < 0 || next == null || next == task ||
1055 joinMe.status < 0)
1056 return;
1057 task = next;
1058 thread = v;
1059 }
1060 }
1061 }
1062
1063 /**
1064 * Returns an estimate of the number of tasks, offset by a
1065 * function of number of idle workers.
1066 *
1067 * This method provides a cheap heuristic guide for task
1068 * partitioning when programmers, frameworks, tools, or languages
1069 * have little or no idea about task granularity. In essence by
1070 * offering this method, we ask users only about tradeoffs in
1071 * overhead vs expected throughput and its variance, rather than
1072 * how finely to partition tasks.
1073 *
1074 * In a steady state strict (tree-structured) computation, each
1075 * thread makes available for stealing enough tasks for other
1076 * threads to remain active. Inductively, if all threads play by
1077 * the same rules, each thread should make available only a
1078 * constant number of tasks.
1079 *
1080 * The minimum useful constant is just 1. But using a value of 1
1081 * would require immediate replenishment upon each steal to
1082 * maintain enough tasks, which is infeasible. Further,
1083 * partitionings/granularities of offered tasks should minimize
1084 * steal rates, which in general means that threads nearer the top
1085 * of computation tree should generate more than those nearer the
1086 * bottom. In perfect steady state, each thread is at
1087 * approximately the same level of computation tree. However,
1088 * producing extra tasks amortizes the uncertainty of progress and
1089 * diffusion assumptions.
1090 *
1091 * So, users will want to use values larger, but not much larger
1092 * than 1 to both smooth over transient shortages and hedge
1093 * against uneven progress; as traded off against the cost of
1094 * extra task overhead. We leave the user to pick a threshold
1095 * value to compare with the results of this call to guide
1096 * decisions, but recommend values such as 3.
1097 *
1098 * When all threads are active, it is on average OK to estimate
1099 * surplus strictly locally. In steady-state, if one thread is
1100 * maintaining say 2 surplus tasks, then so are others. So we can
1101 * just use estimated queue length (although note that (sp - base)
1102 * can be an overestimate because of stealers lagging increments
1103 * of base). However, this strategy alone leads to serious
1104 * mis-estimates in some non-steady-state conditions (ramp-up,
1105 * ramp-down, other stalls). We can detect many of these by
1106 * further considering the number of "idle" threads, that are
1107 * known to have zero queued tasks, so compensate by a factor of
1108 * (#idle/#active) threads.
1109 */
1110 final int getEstimatedSurplusTaskCount() {
1111 return sp - base - pool.idlePerActive();
1112 }
1113
1114 /**
1115 * Runs tasks until {@code pool.isQuiescent()}.
1116 */
1117 final void helpQuiescePool() {
1118 for (;;) {
1119 ForkJoinTask<?> t = pollLocalTask();
1120 if (t != null || (t = scan()) != null) {
1121 t.quietlyExec();
1122 currentSteal = null;
1123 }
1124 else {
1125 ForkJoinPool p = pool;
1126 int a; // to inline CASes
1127 if (active) {
1128 if (!UNSAFE.compareAndSwapInt
1129 (p, poolRunStateOffset, a = p.runState, a - 1))
1130 continue; // retry later
1131 active = false; // inactivate
1132 }
1133 if (p.isQuiescent()) {
1134 active = true; // re-activate
1135 do {} while(!UNSAFE.compareAndSwapInt
1136 (p, poolRunStateOffset, a = p.runState, a+1));
1137 return;
1138 }
1139 }
1140 }
1141 }
1142
1143 // Unsafe mechanics
1144
1145 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1146 private static final long spOffset =
1147 objectFieldOffset("sp", ForkJoinWorkerThread.class);
1148 private static final long runStateOffset =
1149 objectFieldOffset("runState", ForkJoinWorkerThread.class);
1150 private static final long currentJoinOffset =
1151 objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1152 private static final long currentStealOffset =
1153 objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1154 private static final long qBase =
1155 UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1156 private static final long poolRunStateOffset = // to inline CAS
1157 objectFieldOffset("runState", ForkJoinPool.class);
1158
1159 private static final int qShift;
1160
1161 static {
1162 int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
1163 if ((s & (s-1)) != 0)
1164 throw new Error("data type scale not a power of two");
1165 qShift = 31 - Integer.numberOfLeadingZeros(s);
1166 }
1167
1168 private static long objectFieldOffset(String field, Class<?> klazz) {
1169 try {
1170 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1171 } catch (NoSuchFieldException e) {
1172 // Convert Exception to corresponding Error
1173 NoSuchFieldError error = new NoSuchFieldError(field);
1174 error.initCause(e);
1175 throw error;
1176 }
1177 }
1178 }