ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
Revision: 1.11
Committed: Tue Jul 21 00:15:14 2009 UTC (14 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.10: +30 -19 lines
Log Message:
j.u.c. coding standards

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     import java.util.*;
9     import java.util.concurrent.*;
10     import java.util.concurrent.atomic.*;
11     import java.util.concurrent.locks.*;
12     import sun.misc.Unsafe;
13     import java.lang.reflect.*;
14    
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     * are no overridable methods dealing with scheduling or
19     * execution. However, you can override initialization and termination
20 dl 1.7 * methods surrounding the main task processing loop. If you do
21     * create such a subclass, you will also need to supply a custom
22 dl 1.2 * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
23 jsr166 1.6 *
24 dl 1.1 */
25     public class ForkJoinWorkerThread extends Thread {
26     /*
27     * Algorithm overview:
28     *
29     * 1. Work-Stealing: Work-stealing queues are special forms of
30     * Deques that support only three of the four possible
31     * end-operations -- push, pop, and deq (aka steal), and only do
32     * so under the constraints that push and pop are called only from
33     * the owning thread, while deq may be called from other threads.
34     * (If you are unfamiliar with them, you probably want to read
35     * Herlihy and Shavit's book "The Art of Multiprocessor
36     * programming", chapter 16 describing these in more detail before
37     * proceeding.) The main work-stealing queue design is roughly
38     * similar to "Dynamic Circular Work-Stealing Deque" by David
39     * Chase and Yossi Lev, SPAA 2005
40     * (http://research.sun.com/scalable/pubs/index.html). The main
41     * difference ultimately stems from gc requirements that we null
42     * out taken slots as soon as we can, to maintain as small a
43     * footprint as possible even in programs generating huge numbers
44     * of tasks. To accomplish this, we shift the CAS arbitrating pop
45     * vs deq (steal) from being on the indices ("base" and "sp") to
46     * the slots themselves (mainly via method "casSlotNull()"). So,
47 jsr166 1.10 * both a successful pop and deq mainly entail CAS'ing a non-null
48 dl 1.1 * slot to null. Because we rely on CASes of references, we do
49     * not need tag bits on base or sp. They are simple ints as used
50     * in any circular array-based queue (see for example ArrayDeque).
51     * Updates to the indices must still be ordered in a way that
52     * guarantees that (sp - base) > 0 means the queue is empty, but
53     * otherwise may err on the side of possibly making the queue
54     * appear nonempty when a push, pop, or deq have not fully
55     * committed. Note that this means that the deq operation,
56     * considered individually, is not wait-free. One thief cannot
57     * successfully continue until another in-progress one (or, if
58     * previously empty, a push) completes. However, in the
59 jsr166 1.9 * aggregate, we ensure at least probabilistic non-blockingness. If
60 dl 1.1 * an attempted steal fails, a thief always chooses a different
61     * random victim target to try next. So, in order for one thief to
62     * progress, it suffices for any in-progress deq or new push on
63     * any empty queue to complete. One reason this works well here is
64     * that apparently-nonempty often means soon-to-be-stealable,
65     * which gives threads a chance to activate if necessary before
66     * stealing (see below).
67     *
68     * Efficient implementation of this approach currently relies on
69     * an uncomfortable amount of "Unsafe" mechanics. To maintain
70     * correct orderings, reads and writes of variable base require
71     * volatile ordering. Variable sp does not require volatile write
72     * but needs cheaper store-ordering on writes. Because they are
73     * protected by volatile base reads, reads of the queue array and
74     * its slots do not need volatile load semantics, but writes (in
75     * push) require store order and CASes (in pop and deq) require
76     * (volatile) CAS semantics. Since these combinations aren't
77     * supported using ordinary volatiles, the only way to accomplish
78 jsr166 1.9 * these efficiently is to use direct Unsafe calls. (Using external
79 dl 1.1 * AtomicIntegers and AtomicReferenceArrays for the indices and
80     * array is significantly slower because of memory locality and
81     * indirection effects.) Further, performance on most platforms is
82     * very sensitive to placement and sizing of the (resizable) queue
83     * array. Even though these queues don't usually become all that
84     * big, the initial size must be large enough to counteract cache
85     * contention effects across multiple queues (especially in the
86     * presence of GC cardmarking). Also, to improve thread-locality,
87     * queues are currently initialized immediately after the thread
88     * gets the initial signal to start processing tasks. However,
89     * all queue-related methods except pushTask are written in a way
90     * that allows them to instead be lazily allocated and/or disposed
91     * of when empty. All together, these low-level implementation
92     * choices produce as much as a factor of 4 performance
93     * improvement compared to naive implementations, and enable the
94     * processing of billions of tasks per second, sometimes at the
95     * expense of ugliness.
96     *
97     * 2. Run control: The primary run control is based on a global
98     * counter (activeCount) held by the pool. It uses an algorithm
99     * similar to that in Herlihy and Shavit section 17.6 to cause
100     * threads to eventually block when all threads declare they are
101     * inactive. (See variable "scans".) For this to work, threads
102     * must be declared active when executing tasks, and before
103     * stealing a task. They must be inactive before blocking on the
104     * Pool Barrier (awaiting a new submission or other Pool
105     * event). In between, there is some free play which we take
106     * advantage of to avoid contention and rapid flickering of the
107     * global activeCount: If inactive, we activate only if a victim
108     * queue appears to be nonempty (see above). Similarly, a thread
109     * tries to inactivate only after a full scan of other threads.
110     * The net effect is that contention on activeCount is rarely a
111     * measurable performance issue. (There are also a few other cases
112     * where we scan for work rather than retry/block upon
113     * contention.)
114     *
115     * 3. Selection control. We maintain policy of always choosing to
116     * run local tasks rather than stealing, and always trying to
117     * steal tasks before trying to run a new submission. All steals
118     * are currently performed in randomly-chosen deq-order. It may be
119     * worthwhile to bias these with locality / anti-locality
120     * information, but doing this well probably requires more
121     * lower-level information from JVMs than currently provided.
122     */
123    
124     /**
125     * Capacity of work-stealing queue array upon initialization.
126     * Must be a power of two. Initial size must be at least 2, but is
127     * padded to minimize cache effects.
128     */
129     private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
130    
131     /**
132     * Maximum work-stealing queue array size. Must be less than or
133 dl 1.5 * equal to 1 << 28 to ensure lack of index wraparound. (This
134     * is less than usual bounds, because we need leftshift by 3
135     * to be in int range).
136 dl 1.1 */
137 dl 1.5 private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
138 dl 1.1
139     /**
140 dl 1.5 * The pool this thread works in. Accessed directly by ForkJoinTask
141 dl 1.1 */
142 dl 1.5 final ForkJoinPool pool;
143 dl 1.1
144     /**
145     * The work-stealing queue array. Size must be a power of two.
146 dl 1.5 * Initialized when thread starts, to improve memory locality.
147 dl 1.1 */
148     private ForkJoinTask<?>[] queue;
149    
150     /**
151     * Index (mod queue.length) of next queue slot to push to or pop
152     * from. It is written only by owner thread, via ordered store.
153     * Both sp and base are allowed to wrap around on overflow, but
154     * (sp - base) still estimates size.
155     */
156     private volatile int sp;
157    
158     /**
159     * Index (mod queue.length) of least valid queue slot, which is
160     * always the next position to steal from if nonempty.
161     */
162     private volatile int base;
163    
164     /**
165 dl 1.5 * Activity status. When true, this worker is considered active.
166     * Must be false upon construction. It must be true when executing
167     * tasks, and BEFORE stealing a task. It must be false before
168     * calling pool.sync
169 dl 1.1 */
170 dl 1.5 private boolean active;
171 dl 1.1
172     /**
173     * Run state of this worker. Supports simple versions of the usual
174     * shutdown/shutdownNow control.
175     */
176     private volatile int runState;
177    
178     /**
179 dl 1.5 * Seed for random number generator for choosing steal victims.
180     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
181 dl 1.1 */
182 dl 1.5 private int seed;
183 dl 1.1
184     /**
185     * Number of steals, transferred to pool when idle
186     */
187     private int stealCount;
188    
189     /**
190 dl 1.5 * Index of this worker in pool array. Set once by pool before
191     * running, and accessed directly by pool during cleanup etc
192 dl 1.1 */
193 dl 1.5 int poolIndex;
194 dl 1.1
195     /**
196 dl 1.5 * The last barrier event waited for. Accessed in pool callback
197     * methods, but only by current thread.
198 dl 1.1 */
199 dl 1.5 long lastEventCount;
200 dl 1.1
201     /**
202 dl 1.7 * True if use local fifo, not default lifo, for local polling
203     */
204     private boolean locallyFifo;
205    
206     /**
207 dl 1.1 * Creates a ForkJoinWorkerThread operating in the given pool.
208 jsr166 1.11 *
209 dl 1.1 * @param pool the pool this thread works in
210     * @throws NullPointerException if pool is null
211     */
212     protected ForkJoinWorkerThread(ForkJoinPool pool) {
213     if (pool == null) throw new NullPointerException();
214     this.pool = pool;
215 dl 1.5 // Note: poolIndex is set by pool during construction
216     // Remaining initialization is deferred to onStart
217 dl 1.1 }
218    
219 jsr166 1.6 // Public access methods
220 dl 1.2
221     /**
222 jsr166 1.11 * Returns the pool hosting this thread.
223     *
224 dl 1.2 * @return the pool
225     */
226 dl 1.4 public ForkJoinPool getPool() {
227     return pool;
228 dl 1.2 }
229    
230     /**
231 dl 1.4 * Returns the index number of this thread in its pool. The
232     * returned value ranges from zero to the maximum number of
233     * threads (minus one) that have ever been created in the pool.
234     * This method may be useful for applications that track status or
235 dl 1.5 * collect results per-worker rather than per-task.
236 jsr166 1.11 *
237     * @return the index number
238 dl 1.2 */
239 dl 1.4 public int getPoolIndex() {
240     return poolIndex;
241 dl 1.2 }
242    
243 dl 1.7 /**
244     * Establishes local first-in-first-out scheduling mode for forked
245 jsr166 1.8 * tasks that are never joined.
246 jsr166 1.11 *
247 dl 1.7 * @param async if true, use locally FIFO scheduling
248     */
249     void setAsyncMode(boolean async) {
250     locallyFifo = async;
251     }
252 dl 1.5
253     // Runstate management
254    
255     // Runstate values. Order matters
256     private static final int RUNNING = 0;
257     private static final int SHUTDOWN = 1;
258     private static final int TERMINATING = 2;
259     private static final int TERMINATED = 3;
260    
261     final boolean isShutdown() { return runState >= SHUTDOWN; }
262     final boolean isTerminating() { return runState >= TERMINATING; }
263     final boolean isTerminated() { return runState == TERMINATED; }
264     final boolean shutdown() { return transitionRunStateTo(SHUTDOWN); }
265     final boolean shutdownNow() { return transitionRunStateTo(TERMINATING); }
266    
267     /**
268 jsr166 1.11 * Transitions to at least the given state. Returns true if not
269     * already at least at given state.
270 dl 1.5 */
271     private boolean transitionRunStateTo(int state) {
272     for (;;) {
273     int s = runState;
274     if (s >= state)
275     return false;
276     if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
277     return true;
278     }
279     }
280    
281     /**
282 jsr166 1.11 * Tries to set status to active; fails on contention.
283 dl 1.5 */
284     private boolean tryActivate() {
285     if (!active) {
286     if (!pool.tryIncrementActiveCount())
287     return false;
288     active = true;
289     }
290     return true;
291     }
292    
293     /**
294 jsr166 1.11 * Tries to set status to active; fails on contention.
295 dl 1.5 */
296     private boolean tryInactivate() {
297     if (active) {
298     if (!pool.tryDecrementActiveCount())
299     return false;
300     active = false;
301     }
302     return true;
303     }
304    
305     /**
306 jsr166 1.11 * Computes next value for random victim probe. Scans don't
307 dl 1.5 * require a very high quality generator, but also not a crummy
308 jsr166 1.11 * one. Marsaglia xor-shift is cheap and works well.
309 dl 1.5 */
310     private static int xorShift(int r) {
311     r ^= r << 1;
312     r ^= r >>> 3;
313     r ^= r << 10;
314     return r;
315     }
316    
317     // Lifecycle methods
318 dl 1.1
319     /**
320 dl 1.5 * This method is required to be public, but should never be
321     * called explicitly. It performs the main run loop to execute
322     * ForkJoinTasks.
323 dl 1.1 */
324 dl 1.5 public void run() {
325     Throwable exception = null;
326     try {
327     onStart();
328     pool.sync(this); // await first pool event
329     mainLoop();
330     } catch (Throwable ex) {
331     exception = ex;
332     } finally {
333     onTermination(exception);
334     }
335 dl 1.1 }
336    
337     /**
338 jsr166 1.11 * Executes tasks until shut down.
339 dl 1.1 */
340 dl 1.5 private void mainLoop() {
341     while (!isShutdown()) {
342     ForkJoinTask<?> t = pollTask();
343 jsr166 1.6 if (t != null || (t = pollSubmission()) != null)
344 dl 1.5 t.quietlyExec();
345     else if (tryInactivate())
346     pool.sync(this);
347     }
348 dl 1.1 }
349    
350 dl 1.5 /**
351     * 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     */
359     protected void onStart() {
360     // Allocate while starting to improve chances of thread-local
361     // isolation
362     queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
363     // Initial value of seed need not be especially random but
364     // should differ across workers and must be nonzero
365     int p = poolIndex + 1;
366     seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
367     }
368 dl 1.1
369     /**
370 jsr166 1.11 * Performs cleanup associated with termination of this worker
371 dl 1.5 * thread. If you override this method, you must invoke
372     * super.onTermination at the end of the overridden method.
373     *
374     * @param exception the exception causing this thread to abort due
375 jsr166 1.11 * to an unrecoverable error, or null if completed normally
376 dl 1.1 */
377 dl 1.5 protected void onTermination(Throwable exception) {
378     // Execute remaining local tasks unless aborting or terminating
379     while (exception == null && !pool.isTerminating() && base != sp) {
380     try {
381     ForkJoinTask<?> t = popTask();
382     if (t != null)
383     t.quietlyExec();
384     } catch(Throwable ex) {
385     exception = ex;
386     }
387     }
388     // Cancel other tasks, transition status, notify pool, and
389     // propagate exception to uncaught exception handler
390     try {
391     do;while (!tryInactivate()); // ensure inactive
392 jsr166 1.6 cancelTasks();
393 dl 1.5 runState = TERMINATED;
394     pool.workerTerminated(this);
395     } catch (Throwable ex) { // Shouldn't ever happen
396     if (exception == null) // but if so, at least rethrown
397     exception = ex;
398     } finally {
399     if (exception != null)
400     ForkJoinTask.rethrowException(exception);
401     }
402 dl 1.1 }
403    
404 jsr166 1.6 // Intrinsics-based support for queue operations.
405 dl 1.5
406 dl 1.1 /**
407 jsr166 1.10 * Adds in store-order the given task at given slot of q to null.
408     * Caller must ensure q is non-null and index is in range.
409 dl 1.1 */
410     private static void setSlot(ForkJoinTask<?>[] q, int i,
411     ForkJoinTask<?> t){
412     _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
413     }
414    
415     /**
416 jsr166 1.10 * CAS given slot of q to null. Caller must ensure q is non-null
417 dl 1.1 * and index is in range.
418     */
419     private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
420     ForkJoinTask<?> t) {
421     return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
422     }
423    
424 dl 1.5 /**
425     * Sets sp in store-order.
426     */
427     private void storeSp(int s) {
428     _unsafe.putOrderedInt(this, spOffset, s);
429     }
430    
431 dl 1.1 // Main queue methods
432    
433     /**
434     * Pushes a task. Called only by current thread.
435 jsr166 1.11 *
436 jsr166 1.10 * @param t the task. Caller must ensure non-null.
437 dl 1.1 */
438     final void pushTask(ForkJoinTask<?> t) {
439     ForkJoinTask<?>[] q = queue;
440     int mask = q.length - 1;
441     int s = sp;
442 dl 1.5 setSlot(q, s & mask, t);
443     storeSp(++s);
444 dl 1.1 if ((s -= base) == 1)
445 dl 1.5 pool.signalWork();
446 dl 1.1 else if (s >= mask)
447     growQueue();
448     }
449    
450     /**
451     * Tries to take a task from the base of the queue, failing if
452     * either empty or contended.
453 jsr166 1.11 *
454     * @return a task, or null if none or contended
455 dl 1.1 */
456 dl 1.7 final ForkJoinTask<?> deqTask() {
457 dl 1.5 ForkJoinTask<?> t;
458 dl 1.1 ForkJoinTask<?>[] q;
459     int i;
460     int b;
461     if (sp != (b = base) &&
462     (q = queue) != null && // must read q after b
463     (t = q[i = (q.length - 1) & b]) != null &&
464 dl 1.5 casSlotNull(q, i, t)) {
465 dl 1.1 base = b + 1;
466     return t;
467     }
468     return null;
469     }
470    
471     /**
472 dl 1.5 * Returns a popped task, or null if empty. Ensures active status
473 jsr166 1.10 * if non-null. Called only by current thread.
474 dl 1.1 */
475     final ForkJoinTask<?> popTask() {
476     int s = sp;
477 dl 1.5 while (s != base) {
478     if (tryActivate()) {
479     ForkJoinTask<?>[] q = queue;
480     int mask = q.length - 1;
481     int i = (s - 1) & mask;
482     ForkJoinTask<?> t = q[i];
483     if (t == null || !casSlotNull(q, i, t))
484     break;
485     storeSp(s - 1);
486     return t;
487     }
488 dl 1.1 }
489     return null;
490     }
491    
492     /**
493     * Specialized version of popTask to pop only if
494     * topmost element is the given task. Called only
495 dl 1.5 * by current thread while active.
496 jsr166 1.11 *
497     * @param t the task. Caller must ensure non-null.
498 dl 1.1 */
499     final boolean unpushTask(ForkJoinTask<?> t) {
500     ForkJoinTask<?>[] q = queue;
501     int mask = q.length - 1;
502     int s = sp - 1;
503 dl 1.5 if (casSlotNull(q, s & mask, t)) {
504     storeSp(s);
505 dl 1.1 return true;
506     }
507     return false;
508     }
509    
510     /**
511 dl 1.7 * Returns next task.
512 dl 1.1 */
513 dl 1.2 final ForkJoinTask<?> peekTask() {
514 dl 1.1 ForkJoinTask<?>[] q = queue;
515 dl 1.7 if (q == null)
516     return null;
517     int mask = q.length - 1;
518     int i = locallyFifo? base : (sp - 1);
519     return q[i & mask];
520 dl 1.1 }
521    
522     /**
523     * Doubles queue array size. Transfers elements by emulating
524     * steals (deqs) from old array and placing, oldest first, into
525     * new array.
526     */
527     private void growQueue() {
528     ForkJoinTask<?>[] oldQ = queue;
529     int oldSize = oldQ.length;
530     int newSize = oldSize << 1;
531     if (newSize > MAXIMUM_QUEUE_CAPACITY)
532     throw new RejectedExecutionException("Queue capacity exceeded");
533     ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
534    
535     int b = base;
536     int bf = b + oldSize;
537     int oldMask = oldSize - 1;
538     int newMask = newSize - 1;
539     do {
540     int oldIndex = b & oldMask;
541     ForkJoinTask<?> t = oldQ[oldIndex];
542     if (t != null && !casSlotNull(oldQ, oldIndex, t))
543     t = null;
544     setSlot(newQ, b & newMask, t);
545     } while (++b != bf);
546 dl 1.5 pool.signalWork();
547 dl 1.1 }
548    
549     /**
550 dl 1.5 * Tries to steal a task from another worker. Starts at a random
551     * index of workers array, and probes workers until finding one
552     * with non-empty queue or finding that all are empty. It
553     * randomly selects the first n probes. If these are empty, it
554     * resorts to a full circular traversal, which is necessary to
555     * accurately set active status by caller. Also restarts if pool
556     * events occurred since last scan, which forces refresh of
557     * workers array, in case barrier was associated with resize.
558 dl 1.1 *
559     * This method must be both fast and quiet -- usually avoiding
560     * memory accesses that could disrupt cache sharing etc other than
561     * those needed to check for and take tasks. This accounts for,
562     * among other things, updating random seed in place without
563 dl 1.5 * storing it until exit.
564 dl 1.1 *
565     * @return a task, or null if none found
566     */
567 dl 1.5 private ForkJoinTask<?> scan() {
568     ForkJoinTask<?> t = null;
569     int r = seed; // extract once to keep scan quiet
570     ForkJoinWorkerThread[] ws; // refreshed on outer loop
571     int mask; // must be power 2 minus 1 and > 0
572     outer:do {
573     if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
574 dl 1.1 int idx = r;
575 dl 1.5 int probes = ~mask; // use random index while negative
576 dl 1.1 for (;;) {
577 dl 1.5 r = xorShift(r); // update random seed
578     ForkJoinWorkerThread v = ws[mask & idx];
579     if (v == null || v.sp == v.base) {
580     if (probes <= mask)
581     idx = (probes++ < 0)? r : (idx + 1);
582     else
583     break;
584 dl 1.1 }
585 dl 1.5 else if (!tryActivate() || (t = v.deqTask()) == null)
586     continue outer; // restart on contention
587 dl 1.1 else
588 dl 1.5 break outer;
589 dl 1.1 }
590     }
591 dl 1.5 } while (pool.hasNewSyncEvent(this)); // retry on pool events
592     seed = r;
593     return t;
594 dl 1.1 }
595    
596     /**
597 jsr166 1.11 * Gets and removes a local or stolen task.
598     *
599 dl 1.5 * @return a task, if available
600     */
601     final ForkJoinTask<?> pollTask() {
602 dl 1.7 ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
603 dl 1.5 if (t == null && (t = scan()) != null)
604     ++stealCount;
605     return t;
606 dl 1.1 }
607    
608     /**
609 jsr166 1.11 * Gets a local task.
610     *
611 dl 1.7 * @return a task, if available
612     */
613     final ForkJoinTask<?> pollLocalTask() {
614     return locallyFifo? deqTask() : popTask();
615     }
616    
617     /**
618 dl 1.5 * Returns a pool submission, if one exists, activating first.
619 jsr166 1.11 *
620 dl 1.5 * @return a submission, if available
621 dl 1.1 */
622 dl 1.5 private ForkJoinTask<?> pollSubmission() {
623     ForkJoinPool p = pool;
624     while (p.hasQueuedSubmissions()) {
625     ForkJoinTask<?> t;
626     if (tryActivate() && (t = p.pollSubmission()) != null)
627     return t;
628 dl 1.1 }
629 dl 1.5 return null;
630 dl 1.1 }
631 dl 1.5
632     // Methods accessed only by Pool
633    
634 dl 1.1 /**
635 dl 1.5 * Removes and cancels all tasks in queue. Can be called from any
636     * thread.
637 dl 1.1 */
638 dl 1.5 final void cancelTasks() {
639 dl 1.3 ForkJoinTask<?> t;
640 dl 1.5 while (base != sp && (t = deqTask()) != null)
641     t.cancelIgnoringExceptions();
642 dl 1.1 }
643    
644     /**
645 jsr166 1.11 * Drains tasks to given collection c.
646     *
647 dl 1.7 * @return the number of tasks drained
648     */
649     final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
650     int n = 0;
651     ForkJoinTask<?> t;
652     while (base != sp && (t = deqTask()) != null) {
653     c.add(t);
654     ++n;
655     }
656     return n;
657     }
658    
659     /**
660 jsr166 1.11 * Gets and clears steal count for accumulation by pool. Called
661 dl 1.5 * only when known to be idle (in pool.sync and termination).
662 dl 1.1 */
663 dl 1.5 final int getAndClearStealCount() {
664     int sc = stealCount;
665     stealCount = 0;
666     return sc;
667     }
668    
669     /**
670     * Returns true if at least one worker in the given array appears
671     * to have at least one queued task.
672     * @param ws array of workers
673     */
674     static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
675     if (ws != null) {
676     int len = ws.length;
677     for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
678     for (int i = 0; i < len; ++i) {
679     ForkJoinWorkerThread w = ws[i];
680     if (w != null && w.sp != w.base)
681     return true;
682 dl 1.1 }
683     }
684     }
685 dl 1.5 return false;
686 dl 1.1 }
687    
688 dl 1.5 // Support methods for ForkJoinTask
689    
690 dl 1.1 /**
691 dl 1.2 * Returns an estimate of the number of tasks in the queue.
692     */
693     final int getQueueSize() {
694 dl 1.3 int n = sp - base;
695 dl 1.5 return n < 0? 0 : n; // suppress momentarily negative values
696 dl 1.2 }
697    
698     /**
699 dl 1.1 * Returns an estimate of the number of tasks, offset by a
700     * function of number of idle workers.
701     */
702     final int getEstimatedSurplusTaskCount() {
703 dl 1.3 // The halving approximates weighting idle vs non-idle workers
704 dl 1.1 return (sp - base) - (pool.getIdleThreadCount() >>> 1);
705     }
706    
707     /**
708 jsr166 1.11 * Scans, returning early if joinMe done
709 dl 1.1 */
710 dl 1.5 final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
711     ForkJoinTask<?> t = pollTask();
712     if (t != null && joinMe.status < 0 && sp == base) {
713     pushTask(t); // unsteal if done and this task would be stealable
714     t = null;
715     }
716     return t;
717 dl 1.1 }
718 jsr166 1.6
719 dl 1.1 /**
720 jsr166 1.11 * Runs tasks until pool isQuiescent.
721 dl 1.1 */
722 dl 1.5 final void helpQuiescePool() {
723     for (;;) {
724     ForkJoinTask<?> t = pollTask();
725 jsr166 1.6 if (t != null)
726 dl 1.5 t.quietlyExec();
727     else if (tryInactivate() && pool.isQuiescent())
728     break;
729     }
730     do;while (!tryActivate()); // re-activate on exit
731 dl 1.1 }
732    
733     // Temporary Unsafe mechanics for preliminary release
734 jsr166 1.6 private static Unsafe getUnsafe() throws Throwable {
735     try {
736     return Unsafe.getUnsafe();
737     } catch (SecurityException se) {
738     try {
739     return java.security.AccessController.doPrivileged
740     (new java.security.PrivilegedExceptionAction<Unsafe>() {
741     public Unsafe run() throws Exception {
742     return getUnsafePrivileged();
743     }});
744     } catch (java.security.PrivilegedActionException e) {
745     throw e.getCause();
746     }
747     }
748     }
749    
750     private static Unsafe getUnsafePrivileged()
751     throws NoSuchFieldException, IllegalAccessException {
752     Field f = Unsafe.class.getDeclaredField("theUnsafe");
753     f.setAccessible(true);
754     return (Unsafe) f.get(null);
755     }
756    
757     private static long fieldOffset(String fieldName)
758     throws NoSuchFieldException {
759     return _unsafe.objectFieldOffset
760     (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
761     }
762 dl 1.1
763     static final Unsafe _unsafe;
764     static final long baseOffset;
765     static final long spOffset;
766 dl 1.5 static final long runStateOffset;
767 dl 1.1 static final long qBase;
768     static final int qShift;
769     static {
770     try {
771 jsr166 1.6 _unsafe = getUnsafe();
772     baseOffset = fieldOffset("base");
773     spOffset = fieldOffset("sp");
774     runStateOffset = fieldOffset("runState");
775 dl 1.1 qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
776     int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
777     if ((s & (s-1)) != 0)
778     throw new Error("data type scale not a power of two");
779     qShift = 31 - Integer.numberOfLeadingZeros(s);
780 jsr166 1.6 } catch (Throwable e) {
781 dl 1.1 throw new RuntimeException("Could not initialize intrinsics", e);
782     }
783     }
784     }