ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.24
Committed: Thu Sep 2 11:31:22 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.23: +5 -4 lines
Log Message:
Incorporate review suggestions

File Contents

# User Rev Content
1 jsr166 1.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 dl 1.14 import java.util.Random;
10 jsr166 1.1 import java.util.Collection;
11 dl 1.14 import java.util.concurrent.locks.LockSupport;
12 jsr166 1.1
13     /**
14     * A thread managed by a {@link ForkJoinPool}. This class is
15     * subclassable solely for the sake of adding functionality -- there
16 jsr166 1.7 * 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 jsr166 1.1 *
23     * @since 1.7
24     * @author Doug Lea
25     */
26     public class ForkJoinWorkerThread extends Thread {
27     /*
28 dl 1.14 * Overview:
29 jsr166 1.1 *
30 dl 1.14 * 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 jsr166 1.1 *
78 jsr166 1.6 * 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 dl 1.17 * When a worker would otherwise be blocked waiting to join a
85     * task, it first tries a form of linear helping: Each worker
86 dl 1.18 * 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 dl 1.17 * 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 dl 1.18 * 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 dl 1.20 * ForkJoinPool.awaitJoin).
112 dl 1.17 *
113 dl 1.18 * Efficient implementation of these algorithms currently relies
114     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
115 jsr166 1.1 * correct orderings, reads and writes of variable base require
116 dl 1.14 * 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 dl 1.18 * 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 jsr166 1.9 *
133 jsr166 1.8 * 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 jsr166 1.1 * contention effects across multiple queues (especially in the
138     * presence of GC cardmarking). Also, to improve thread-locality,
139 dl 1.14 * 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 jsr166 1.1 */
145    
146     /**
147 dl 1.14 * 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 dl 1.18 * 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 dl 1.14 */
162 dl 1.18 private static final int MAX_HELP_DEPTH = 8;
163    
164     /**
165 jsr166 1.1 * Capacity of work-stealing queue array upon initialization.
166 dl 1.17 * Must be a power of two. Initial size must be at least 4, but is
167 jsr166 1.1 * 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 dl 1.24 * 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 jsr166 1.1 */
177 dl 1.24 private static final int MAXIMUM_QUEUE_CAPACITY;
178 jsr166 1.1
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 dl 1.14 * Initialized in onStart, to improve memory locality.
187 jsr166 1.1 */
188     private ForkJoinTask<?>[] queue;
189    
190     /**
191 dl 1.14 * 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 jsr166 1.1 * Index (mod queue.length) of next queue slot to push to or pop
198 dl 1.14 * 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 jsr166 1.1
205     /**
206 dl 1.18 * 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 dl 1.14 * 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 dl 1.19 * maintained separately and modified only in conjunction with
219 dl 1.20 * 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 jsr166 1.1 */
223 dl 1.20 volatile int runState;
224 dl 1.14
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 jsr166 1.1
230     /**
231 dl 1.21 * Number of steals. Directly accessed (and reset) by
232     * pool.tryAccumulateStealCount when idle.
233 jsr166 1.1 */
234 dl 1.14 int stealCount;
235 jsr166 1.1
236     /**
237     * Seed for random number generator for choosing steal victims.
238 dl 1.14 * Uses Marsaglia xorshift. Must be initialized as nonzero.
239 jsr166 1.1 */
240     private int seed;
241    
242     /**
243 dl 1.14 * 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 dl 1.18 * Shadows value from ForkJoinPool.
251 jsr166 1.1 */
252 dl 1.17 private final boolean locallyFifo;
253 dl 1.18
254 jsr166 1.1 /**
255     * Index of this worker in pool array. Set once by pool before
256 dl 1.14 * running, and accessed directly by pool to locate this worker in
257     * its workers array.
258 jsr166 1.1 */
259     int poolIndex;
260    
261     /**
262 dl 1.14 * The last pool event waited for. Accessed only by pool in
263     * callback methods invoked within this thread.
264 jsr166 1.1 */
265 dl 1.14 int lastEventCount;
266 jsr166 1.1
267     /**
268 dl 1.20 * Encoded index and event count of next event waiter. Accessed
269     * only by ForkJoinPool for managing event waiters.
270 jsr166 1.1 */
271 dl 1.14 volatile long nextWaiter;
272 jsr166 1.1
273     /**
274 dl 1.20 * Number of times this thread suspended as spare. Accessed only
275     * by pool.
276 dl 1.18 */
277     int spareCount;
278    
279     /**
280 dl 1.20 * Encoded index and count of next spare waiter. Accessed only
281 dl 1.18 * by ForkJoinPool for managing spares.
282     */
283     volatile int nextSpare;
284    
285     /**
286     * The task currently being joined, set only when actively trying
287 dl 1.21 * to help other stealers in helpJoinTask. Written only by current
288     * thread, but read by others.
289 dl 1.18 */
290     private volatile ForkJoinTask<?> currentJoin;
291    
292     /**
293     * The task most recently stolen from another worker (or
294 dl 1.20 * submission queue). Written only by current thread, but read by
295     * others.
296 dl 1.18 */
297 dl 1.20 private volatile ForkJoinTask<?> currentSteal;
298 dl 1.18
299     /**
300 jsr166 1.1 * 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 dl 1.17 this.locallyFifo = pool.locallyFifo;
308 dl 1.18 setDaemon(true);
309 dl 1.14 // To avoid exposing construction details to subclasses,
310     // remaining initialization is in start() and onStart()
311 jsr166 1.1 }
312    
313 dl 1.14 /**
314     * Performs additional initialization and starts this thread
315     */
316 dl 1.17 final void start(int poolIndex, UncaughtExceptionHandler ueh) {
317 dl 1.14 this.poolIndex = poolIndex;
318     if (ueh != null)
319     setUncaughtExceptionHandler(ueh);
320     start();
321     }
322    
323     // Public/protected methods
324 jsr166 1.1
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 dl 1.14 * Initializes internal state after construction but before
349     * processing any tasks. If you override this method, you must
350 dl 1.21 * invoke @code{super.onStart()} at the beginning of the method.
351 dl 1.14 * 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 jsr166 1.1 */
356 dl 1.14 protected void onStart() {
357     int rs = seedGenerator.nextInt();
358     seed = rs == 0? 1 : rs; // seed must be nonzero
359 jsr166 1.1
360 dl 1.17 // Allocate name string and arrays in this thread
361 dl 1.14 String pid = Integer.toString(pool.getPoolNumber());
362     String wid = Integer.toString(poolIndex);
363     setName("ForkJoinPool-" + pid + "-worker-" + wid);
364 jsr166 1.1
365 dl 1.14 queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
366     }
367 jsr166 1.1
368     /**
369 dl 1.14 * 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 jsr166 1.4 *
373 dl 1.14 * @param exception the exception causing this thread to abort due
374     * to an unrecoverable error, or {@code null} if completed normally
375 jsr166 1.1 */
376 dl 1.14 protected void onTermination(Throwable exception) {
377     try {
378 dl 1.19 ForkJoinPool p = pool;
379     if (active) {
380     int a; // inline p.tryDecrementActiveCount
381     active = false;
382 jsr166 1.22 do {} while (!UNSAFE.compareAndSwapInt
383     (p, poolRunStateOffset, a = p.runState, a - 1));
384 dl 1.19 }
385 dl 1.14 cancelTasks();
386     setTerminated();
387 dl 1.19 p.workerTerminated(this);
388 dl 1.14 } 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 jsr166 1.1 }
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 dl 1.14 // helpers for run()
415    
416 jsr166 1.1 /**
417 dl 1.14 * Find and execute tasks and check status while running
418 jsr166 1.1 */
419     private void mainLoop() {
420 dl 1.20 boolean ran = false; // true if ran a task on last step
421 dl 1.14 ForkJoinPool p = pool;
422     for (;;) {
423 dl 1.20 p.preStep(this, ran);
424 dl 1.14 if (runState != 0)
425 dl 1.18 break;
426 dl 1.20 ran = tryExecSteal() || tryExecSubmission();
427 jsr166 1.1 }
428     }
429    
430     /**
431 dl 1.18 * Try to steal a task and execute it
432     *
433     * @return true if ran a task
434 jsr166 1.1 */
435 dl 1.18 private boolean tryExecSteal() {
436     ForkJoinTask<?> t;
437 dl 1.20 if ((t = scan()) != null) {
438 dl 1.18 t.quietlyExec();
439 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, null);
440 dl 1.18 if (sp != base)
441     execLocalTasks();
442     return true;
443 dl 1.14 }
444 dl 1.18 return false;
445 jsr166 1.1 }
446    
447     /**
448 dl 1.21 * If a submission exists, try to activate and run it.
449 jsr166 1.1 *
450 dl 1.18 * @return true if ran a task
451 jsr166 1.1 */
452 dl 1.18 private boolean tryExecSubmission() {
453 dl 1.14 ForkJoinPool p = pool;
454 dl 1.21 // 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 dl 1.14 while (p.hasQueuedSubmissions()) {
458 dl 1.19 ForkJoinTask<?> t; int a;
459 dl 1.20 if (active || // inline p.tryIncrementActiveCount
460 dl 1.19 (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
461     a = p.runState, a + 1))) {
462 dl 1.18 if ((t = p.pollSubmission()) != null) {
463 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, t);
464 dl 1.18 t.quietlyExec();
465 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, null);
466 dl 1.18 if (sp != base)
467     execLocalTasks();
468     return true;
469     }
470 jsr166 1.1 }
471     }
472 dl 1.18 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 jsr166 1.23 ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
482 dl 1.18 if (t != null)
483     t.quietlyExec();
484     else if (sp == base)
485     break;
486     }
487 jsr166 1.1 }
488    
489 dl 1.14 /*
490     * Intrinsics-based atomic writes for queue slots. These are
491     * basically the same as methods in AtomicObjectArray, 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 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 jsr166 1.1 */
505    
506     /**
507 dl 1.14 * CASes slot i of array q from t to null. Caller must ensure q is
508     * non-null and index is in range.
509 jsr166 1.1 */
510 dl 1.14 private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
511     ForkJoinTask<?> t) {
512     return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
513 jsr166 1.1 }
514    
515     /**
516 dl 1.14 * 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 jsr166 1.1 */
520 dl 1.14 private static final void writeSlot(ForkJoinTask<?>[] q, int i,
521     ForkJoinTask<?> t) {
522     UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
523 jsr166 1.1 }
524    
525 dl 1.14 // queue methods
526 jsr166 1.1
527     /**
528 dl 1.14 * Pushes a task. Call only from this thread.
529 jsr166 1.1 *
530     * @param t the task. Caller must ensure non-null.
531     */
532     final void pushTask(ForkJoinTask<?> t) {
533     ForkJoinTask<?>[] q = queue;
534 dl 1.14 int mask = q.length - 1; // implicit assert q != null
535 dl 1.17 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 jsr166 1.1 }
542    
543     /**
544     * Tries to take a task from the base of the queue, failing if
545 dl 1.14 * empty or contended. Note: Specializations of this code appear
546 dl 1.17 * in locallyDeqTask and elsewhere.
547 jsr166 1.1 *
548     * @return a task, or null if none or contended
549     */
550     final ForkJoinTask<?> deqTask() {
551     ForkJoinTask<?> t;
552     ForkJoinTask<?>[] q;
553 dl 1.14 int b, i;
554 dl 1.18 if (sp != (b = base) &&
555 jsr166 1.1 (q = queue) != null && // must read q after b
556 dl 1.17 (t = q[i = (q.length - 1) & b]) != null && base == b &&
557 dl 1.14 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
558 jsr166 1.1 base = b + 1;
559     return t;
560     }
561     return null;
562     }
563    
564     /**
565 dl 1.14 * Tries to take a task from the base of own queue. Assumes active
566     * status. Called only by current thread.
567 jsr166 1.6 *
568     * @return a task, or null if none
569     */
570     final ForkJoinTask<?> locallyDeqTask() {
571 dl 1.14 ForkJoinTask<?>[] q = queue;
572     if (q != null) {
573     ForkJoinTask<?> t;
574     int b, i;
575     while (sp != (b = base)) {
576 dl 1.17 if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
577 dl 1.14 UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
578     t, null)) {
579 jsr166 1.6 base = b + 1;
580     return t;
581     }
582     }
583     }
584     return null;
585     }
586    
587     /**
588 dl 1.14 * Returns a popped task, or null if empty. Assumes active status.
589 dl 1.18 * Called only by current thread.
590 jsr166 1.1 */
591 dl 1.18 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 jsr166 1.1 }
607     }
608     return null;
609     }
610    
611     /**
612 dl 1.16 * Specialized version of popTask to pop only if topmost element
613     * is the given task. Called only by current thread while
614     * active.
615 jsr166 1.1 *
616     * @param t the task. Caller must ensure non-null.
617     */
618     final boolean unpushTask(ForkJoinTask<?> t) {
619 dl 1.14 int s;
620 dl 1.18 ForkJoinTask<?>[] q = queue;
621     if ((s = sp) != base && q != null &&
622 dl 1.16 UNSAFE.compareAndSwapObject
623     (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
624 dl 1.20 sp = s; // putOrderedInt may encourage more timely write
625 dl 1.18 // UNSAFE.putOrderedInt(this, spOffset, s);
626 jsr166 1.1 return true;
627     }
628     return false;
629     }
630    
631     /**
632 jsr166 1.6 * Returns next task or null if empty or contended
633 jsr166 1.1 */
634     final ForkJoinTask<?> peekTask() {
635     ForkJoinTask<?>[] q = queue;
636     if (q == null)
637     return null;
638     int mask = q.length - 1;
639     int i = locallyFifo ? base : (sp - 1);
640     return q[i & mask];
641     }
642    
643     /**
644     * Doubles queue array size. Transfers elements by emulating
645     * steals (deqs) from old array and placing, oldest first, into
646     * new array.
647     */
648     private void growQueue() {
649     ForkJoinTask<?>[] oldQ = queue;
650     int oldSize = oldQ.length;
651     int newSize = oldSize << 1;
652     if (newSize > MAXIMUM_QUEUE_CAPACITY)
653     throw new RejectedExecutionException("Queue capacity exceeded");
654     ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
655    
656     int b = base;
657     int bf = b + oldSize;
658     int oldMask = oldSize - 1;
659     int newMask = newSize - 1;
660     do {
661     int oldIndex = b & oldMask;
662     ForkJoinTask<?> t = oldQ[oldIndex];
663     if (t != null && !casSlotNull(oldQ, oldIndex, t))
664     t = null;
665 dl 1.14 writeSlot(newQ, b & newMask, t);
666 jsr166 1.1 } while (++b != bf);
667     pool.signalWork();
668     }
669    
670     /**
671 dl 1.14 * Computes next value for random victim probe in scan(). Scans
672     * don't require a very high quality generator, but also not a
673     * crummy one. Marsaglia xor-shift is cheap and works well enough.
674     * Note: This is manually inlined in scan()
675     */
676     private static final int xorShift(int r) {
677     r ^= r << 13;
678     r ^= r >>> 17;
679     return r ^ (r << 5);
680     }
681    
682     /**
683 jsr166 1.1 * Tries to steal a task from another worker. Starts at a random
684     * index of workers array, and probes workers until finding one
685     * with non-empty queue or finding that all are empty. It
686     * randomly selects the first n probes. If these are empty, it
687 dl 1.14 * resorts to a circular sweep, which is necessary to accurately
688     * set active status. (The circular sweep uses steps of
689     * approximately half the array size plus 1, to avoid bias
690     * stemming from leftmost packing of the array in ForkJoinPool.)
691 jsr166 1.1 *
692     * This method must be both fast and quiet -- usually avoiding
693     * memory accesses that could disrupt cache sharing etc other than
694 dl 1.14 * those needed to check for and take tasks (or to activate if not
695     * already active). This accounts for, among other things,
696     * updating random seed in place without storing it until exit.
697 jsr166 1.1 *
698     * @return a task, or null if none found
699     */
700     private ForkJoinTask<?> scan() {
701 dl 1.14 ForkJoinPool p = pool;
702 dl 1.16 ForkJoinWorkerThread[] ws; // worker array
703     int n; // upper bound of #workers
704     if ((ws = p.workers) != null && (n = ws.length) > 1) {
705     boolean canSteal = active; // shadow active status
706     int r = seed; // extract seed once
707     int mask = n - 1;
708     int j = -n; // loop counter
709     int k = r; // worker index, random if j < 0
710     for (;;) {
711     ForkJoinWorkerThread v = ws[k & mask];
712     r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
713 dl 1.20 ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a;
714     if (v != null && (b = v.base) != v.sp &&
715     (q = v.queue) != null) {
716     int i = (q.length - 1) & b;
717     long u = (i << qShift) + qBase; // raw offset
718     int pid = poolIndex;
719     if ((t = q[i]) != null) {
720     if (!canSteal && // inline p.tryIncrementActiveCount
721     UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
722     a = p.runState, a + 1))
723     canSteal = active = true;
724     if (canSteal && v.base == b++ &&
725 dl 1.18 UNSAFE.compareAndSwapObject(q, u, t, null)) {
726 dl 1.20 v.base = b;
727 dl 1.18 v.stealHint = pid;
728 dl 1.20 UNSAFE.putOrderedObject(this,
729     currentStealOffset, t);
730 dl 1.18 seed = r;
731     ++stealCount;
732     return t;
733 dl 1.17 }
734 jsr166 1.1 }
735 dl 1.16 j = -n;
736     k = r; // restart on contention
737 jsr166 1.1 }
738 dl 1.16 else if (++j <= 0)
739     k = r;
740     else if (j <= n)
741     k += (n >>> 1) | 1;
742     else
743     break;
744 jsr166 1.1 }
745 dl 1.14 }
746     return null;
747 jsr166 1.1 }
748    
749 dl 1.14 // Run State management
750    
751     // status check methods used mainly by ForkJoinPool
752 dl 1.18 final boolean isRunning() { return runState == 0; }
753 dl 1.14 final boolean isTerminating() { return (runState & TERMINATING) != 0; }
754     final boolean isTerminated() { return (runState & TERMINATED) != 0; }
755     final boolean isSuspended() { return (runState & SUSPENDED) != 0; }
756     final boolean isTrimmed() { return (runState & TRIMMED) != 0; }
757    
758 jsr166 1.1 /**
759 dl 1.19 * Sets state to TERMINATING. Does NOT unpark or interrupt
760 dl 1.20 * to wake up if currently blocked. Callers must do so if desired.
761 dl 1.14 */
762 dl 1.19 final void shutdown() {
763 dl 1.14 for (;;) {
764     int s = runState;
765 dl 1.18 if ((s & (TERMINATING|TERMINATED)) != 0)
766     break;
767 dl 1.14 if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
768     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
769     (s & ~SUSPENDED) |
770 dl 1.18 (TRIMMED|TERMINATING)))
771 dl 1.14 break;
772     }
773     else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
774     s | TERMINATING))
775     break;
776     }
777     }
778    
779     /**
780 dl 1.18 * Sets state to TERMINATED. Called only by onTermination()
781 dl 1.14 */
782     private void setTerminated() {
783     int s;
784     do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
785     s = runState,
786     s | (TERMINATING|TERMINATED)));
787     }
788    
789     /**
790 dl 1.19 * If suspended, tries to set status to unsuspended.
791 dl 1.20 * Does NOT wake up if blocked.
792 jsr166 1.1 *
793 dl 1.14 * @return true if successful
794 jsr166 1.1 */
795 dl 1.14 final boolean tryUnsuspend() {
796 dl 1.18 int s;
797     while (((s = runState) & SUSPENDED) != 0) {
798     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
799     s & ~SUSPENDED))
800     return true;
801     }
802 dl 1.17 return false;
803 jsr166 1.1 }
804    
805     /**
806 dl 1.18 * Sets suspended status and blocks as spare until resumed
807     * or shutdown.
808 jsr166 1.1 */
809 dl 1.19 final void suspendAsSpare() {
810 dl 1.18 for (;;) { // set suspended unless terminating
811 dl 1.14 int s = runState;
812     if ((s & TERMINATING) != 0) { // must kill
813     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
814     s | (TRIMMED | TERMINATING)))
815 dl 1.19 return;
816 dl 1.14 }
817     else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
818     s | SUSPENDED))
819     break;
820     }
821 dl 1.18 ForkJoinPool p = pool;
822     p.pushSpare(this);
823 dl 1.14 while ((runState & SUSPENDED) != 0) {
824 dl 1.19 if (p.tryAccumulateStealCount(this)) {
825     interrupted(); // clear/ignore interrupts
826 dl 1.18 if ((runState & SUSPENDED) == 0)
827     break;
828 dl 1.20 LockSupport.park(this);
829 dl 1.14 }
830 jsr166 1.1 }
831 dl 1.14 }
832    
833     // Misc support methods for ForkJoinPool
834    
835     /**
836     * Returns an estimate of the number of tasks in the queue. Also
837     * used by ForkJoinTask.
838     */
839     final int getQueueSize() {
840 dl 1.18 int n; // external calls must read base first
841     return (n = -base + sp) <= 0 ? 0 : n;
842 jsr166 1.1 }
843    
844 dl 1.14 /**
845 jsr166 1.1 * Removes and cancels all tasks in queue. Can be called from any
846     * thread.
847     */
848     final void cancelTasks() {
849 dl 1.18 ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
850     if (cj != null) {
851     currentJoin = null;
852     cj.cancelIgnoringExceptions();
853     try {
854     this.interrupt(); // awaken wait
855     } catch (SecurityException ignore) {
856     }
857     }
858     ForkJoinTask<?> cs = currentSteal;
859     if (cs != null) {
860     currentSteal = null;
861     cs.cancelIgnoringExceptions();
862     }
863 dl 1.14 while (base != sp) {
864     ForkJoinTask<?> t = deqTask();
865     if (t != null)
866     t.cancelIgnoringExceptions();
867     }
868 jsr166 1.1 }
869    
870     /**
871     * Drains tasks to given collection c.
872     *
873     * @return the number of tasks drained
874     */
875 jsr166 1.5 final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
876 jsr166 1.1 int n = 0;
877 dl 1.14 while (base != sp) {
878     ForkJoinTask<?> t = deqTask();
879     if (t != null) {
880     c.add(t);
881     ++n;
882     }
883 jsr166 1.1 }
884     return n;
885     }
886    
887 dl 1.14 // Support methods for ForkJoinTask
888    
889 jsr166 1.1 /**
890 dl 1.18 * Gets and removes a local task.
891     *
892     * @return a task, if available
893     */
894     final ForkJoinTask<?> pollLocalTask() {
895 dl 1.19 ForkJoinPool p = pool;
896 dl 1.18 while (sp != base) {
897 dl 1.19 int a; // inline p.tryIncrementActiveCount
898     if (active ||
899     (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
900     a = p.runState, a + 1)))
901 jsr166 1.23 return locallyFifo ? locallyDeqTask() : popTask();
902 dl 1.18 }
903     return null;
904     }
905    
906     /**
907     * Gets and removes a local or stolen task.
908     *
909     * @return a task, if available
910     */
911     final ForkJoinTask<?> pollTask() {
912     ForkJoinTask<?> t = pollLocalTask();
913     if (t == null) {
914     t = scan();
915 dl 1.20 // cannot retain/track/help steal
916     UNSAFE.putOrderedObject(this, currentStealOffset, null);
917 dl 1.18 }
918     return t;
919     }
920    
921     /**
922 dl 1.17 * Possibly runs some tasks and/or blocks, until task is done.
923     *
924     * @param joinMe the task to join
925     */
926     final void joinTask(ForkJoinTask<?> joinMe) {
927 dl 1.18 // currentJoin only written by this thread; only need ordered store
928     ForkJoinTask<?> prevJoin = currentJoin;
929     UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
930     if (sp != base)
931     localHelpJoinTask(joinMe);
932     if (joinMe.status >= 0)
933     pool.awaitJoin(joinMe, this);
934     UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
935     }
936    
937     /**
938     * Run tasks in local queue until given task is done.
939     *
940     * @param joinMe the task to join
941     */
942     private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
943     int s;
944     ForkJoinTask<?>[] q;
945     while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
946 dl 1.17 int i = (q.length - 1) & --s;
947     long u = (i << qShift) + qBase; // raw offset
948 dl 1.18 ForkJoinTask<?> t = q[i];
949     if (t == null) // lost to a stealer
950     break;
951     if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
952 dl 1.17 /*
953 dl 1.18 * This recheck (and similarly in helpJoinTask)
954 dl 1.17 * handles cases where joinMe is independently
955     * cancelled or forced even though there is other work
956     * available. Back out of the pop by putting t back
957 dl 1.18 * into slot before we commit by writing sp.
958 dl 1.17 */
959     if (joinMe.status < 0) {
960     UNSAFE.putObjectVolatile(q, u, t);
961     break;
962     }
963     sp = s;
964 dl 1.18 // UNSAFE.putOrderedInt(this, spOffset, s);
965     t.quietlyExec();
966 dl 1.17 }
967     }
968     }
969    
970     /**
971 dl 1.20 * Unless terminating, tries to locate and help perform tasks for
972     * a stealer of the given task, or in turn one of its stealers.
973     * Traces currentSteal->currentJoin links looking for a thread
974     * working on a descendant of the given task and with a non-empty
975     * queue to steal back and execute tasks from.
976 dl 1.18 *
977 dl 1.20 * The implementation is very branchy to cope with potential
978 dl 1.18 * inconsistencies or loops encountering chains that are stale,
979     * unknown, or of length greater than MAX_HELP_DEPTH links. All
980     * of these cases are dealt with by just returning back to the
981     * caller, who is expected to retry if other join mechanisms also
982     * don't work out.
983 dl 1.17 *
984     * @param joinMe the task to join
985     */
986 dl 1.18 final void helpJoinTask(ForkJoinTask<?> joinMe) {
987 dl 1.20 ForkJoinWorkerThread[] ws;
988     int n;
989     if (joinMe.status < 0) // already done
990     return;
991     if ((runState & TERMINATING) != 0) { // cancel if shutting down
992     joinMe.cancelIgnoringExceptions();
993     return;
994     }
995     if ((ws = pool.workers) == null || (n = ws.length) <= 1)
996     return; // need at least 2 workers
997    
998     ForkJoinTask<?> task = joinMe; // base of chain
999     ForkJoinWorkerThread thread = this; // thread with stolen task
1000     for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1001     // Try to find v, the stealer of task, by first using hint
1002     ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1003     if (v == null || v.currentSteal != task) {
1004     for (int j = 0; ; ++j) { // search array
1005     if (j < n) {
1006     ForkJoinTask<?> vs;
1007     if ((v = ws[j]) != null &&
1008     (vs = v.currentSteal) != null) {
1009     if (joinMe.status < 0 || task.status < 0)
1010     return; // stale or done
1011     if (vs == task) {
1012     thread.stealHint = j;
1013     break; // save hint for next time
1014 dl 1.18 }
1015     }
1016 dl 1.17 }
1017 dl 1.20 else
1018     return; // no stealer
1019 dl 1.17 }
1020 dl 1.20 }
1021     for (;;) { // Try to help v, using specialized form of deqTask
1022     if (joinMe.status < 0)
1023     return;
1024     int b = v.base;
1025     ForkJoinTask<?>[] q = v.queue;
1026     if (b == v.sp || q == null)
1027     break;
1028     int i = (q.length - 1) & b;
1029     long u = (i << qShift) + qBase;
1030     ForkJoinTask<?> t = q[i];
1031     int pid = poolIndex;
1032     ForkJoinTask<?> ps = currentSteal;
1033     if (task.status < 0)
1034     return; // stale or done
1035     if (t != null && v.base == b++ &&
1036     UNSAFE.compareAndSwapObject(q, u, t, null)) {
1037     if (joinMe.status < 0) {
1038     UNSAFE.putObjectVolatile(q, u, t);
1039     return; // back out on cancel
1040 dl 1.17 }
1041 dl 1.20 v.base = b;
1042     v.stealHint = pid;
1043     UNSAFE.putOrderedObject(this, currentStealOffset, t);
1044     t.quietlyExec();
1045     UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1046 dl 1.17 }
1047     }
1048 dl 1.20 // Try to descend to find v's stealer
1049     ForkJoinTask<?> next = v.currentJoin;
1050     if (task.status < 0 || next == null || next == task ||
1051     joinMe.status < 0)
1052     return;
1053     task = next;
1054     thread = v;
1055 dl 1.17 }
1056     }
1057    
1058     /**
1059 dl 1.21 * Implements ForJoinTask.getSurplusQueuedTaskCount().
1060 dl 1.14 * Returns an estimate of the number of tasks, offset by a
1061     * function of number of idle workers.
1062     *
1063     * This method provides a cheap heuristic guide for task
1064     * partitioning when programmers, frameworks, tools, or languages
1065     * have little or no idea about task granularity. In essence by
1066     * offering this method, we ask users only about tradeoffs in
1067     * overhead vs expected throughput and its variance, rather than
1068     * how finely to partition tasks.
1069     *
1070     * In a steady state strict (tree-structured) computation, each
1071     * thread makes available for stealing enough tasks for other
1072     * threads to remain active. Inductively, if all threads play by
1073     * the same rules, each thread should make available only a
1074     * constant number of tasks.
1075     *
1076     * The minimum useful constant is just 1. But using a value of 1
1077     * would require immediate replenishment upon each steal to
1078     * maintain enough tasks, which is infeasible. Further,
1079     * partitionings/granularities of offered tasks should minimize
1080     * steal rates, which in general means that threads nearer the top
1081     * of computation tree should generate more than those nearer the
1082     * bottom. In perfect steady state, each thread is at
1083     * approximately the same level of computation tree. However,
1084     * producing extra tasks amortizes the uncertainty of progress and
1085     * diffusion assumptions.
1086     *
1087     * So, users will want to use values larger, but not much larger
1088     * than 1 to both smooth over transient shortages and hedge
1089     * against uneven progress; as traded off against the cost of
1090     * extra task overhead. We leave the user to pick a threshold
1091     * value to compare with the results of this call to guide
1092     * decisions, but recommend values such as 3.
1093     *
1094     * When all threads are active, it is on average OK to estimate
1095     * surplus strictly locally. In steady-state, if one thread is
1096     * maintaining say 2 surplus tasks, then so are others. So we can
1097     * just use estimated queue length (although note that (sp - base)
1098     * can be an overestimate because of stealers lagging increments
1099     * of base). However, this strategy alone leads to serious
1100     * mis-estimates in some non-steady-state conditions (ramp-up,
1101     * ramp-down, other stalls). We can detect many of these by
1102     * further considering the number of "idle" threads, that are
1103     * known to have zero queued tasks, so compensate by a factor of
1104     * (#idle/#active) threads.
1105 jsr166 1.1 */
1106 dl 1.14 final int getEstimatedSurplusTaskCount() {
1107     return sp - base - pool.idlePerActive();
1108 jsr166 1.1 }
1109    
1110     /**
1111     * Runs tasks until {@code pool.isQuiescent()}.
1112     */
1113     final void helpQuiescePool() {
1114 dl 1.20 ForkJoinTask<?> ps = currentSteal; // to restore below
1115 jsr166 1.1 for (;;) {
1116 dl 1.14 ForkJoinTask<?> t = pollLocalTask();
1117 dl 1.20 if (t != null || (t = scan()) != null)
1118 dl 1.18 t.quietlyExec();
1119 dl 1.14 else {
1120     ForkJoinPool p = pool;
1121 dl 1.19 int a; // to inline CASes
1122 dl 1.14 if (active) {
1123 dl 1.19 if (!UNSAFE.compareAndSwapInt
1124     (p, poolRunStateOffset, a = p.runState, a - 1))
1125 dl 1.18 continue; // retry later
1126 dl 1.14 active = false; // inactivate
1127 dl 1.20 UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1128 dl 1.14 }
1129     if (p.isQuiescent()) {
1130     active = true; // re-activate
1131 jsr166 1.22 do {} while (!UNSAFE.compareAndSwapInt
1132     (p, poolRunStateOffset, a = p.runState, a+1));
1133 dl 1.14 return;
1134     }
1135     }
1136 jsr166 1.1 }
1137     }
1138    
1139     // Unsafe mechanics
1140    
1141     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1142 dl 1.18 private static final long spOffset =
1143     objectFieldOffset("sp", ForkJoinWorkerThread.class);
1144 jsr166 1.2 private static final long runStateOffset =
1145 jsr166 1.3 objectFieldOffset("runState", ForkJoinWorkerThread.class);
1146 dl 1.18 private static final long currentJoinOffset =
1147     objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1148     private static final long currentStealOffset =
1149     objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1150 dl 1.14 private static final long qBase =
1151     UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1152 dl 1.19 private static final long poolRunStateOffset = // to inline CAS
1153     objectFieldOffset("runState", ForkJoinPool.class);
1154 dl 1.18
1155 jsr166 1.2 private static final int qShift;
1156 jsr166 1.1
1157     static {
1158     int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
1159     if ((s & (s-1)) != 0)
1160     throw new Error("data type scale not a power of two");
1161     qShift = 31 - Integer.numberOfLeadingZeros(s);
1162 dl 1.24 MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift);
1163 jsr166 1.1 }
1164 jsr166 1.3
1165     private static long objectFieldOffset(String field, Class<?> klazz) {
1166     try {
1167     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1168     } catch (NoSuchFieldException e) {
1169     // Convert Exception to corresponding Error
1170     NoSuchFieldError error = new NoSuchFieldError(field);
1171     error.initCause(e);
1172     throw error;
1173     }
1174     }
1175 jsr166 1.1 }