ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
Revision: 1.32
Committed: Sun Apr 18 12:51:18 2010 UTC (14 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.31: +42 -29 lines
Log Message:
Split paths for helpJoin, observing maxPoolSize

File Contents

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