ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.16 by jsr166, Thu Jul 23 23:07:57 2009 UTC vs.
Revision 1.71 by dl, Wed Nov 14 17:20:38 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines