ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinWorkerThread.java
Revision: 1.18
Committed: Wed Aug 11 18:45:45 2010 UTC (13 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.17: +349 -273 lines
Log Message:
Sync with jsr166y

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