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.8 by jsr166, Mon Jul 20 21:45:06 2009 UTC vs.
Revision 1.43 by jsr166, Wed Sep 1 20:12:39 2010 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
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.*;
10 >
11 > import java.util.Random;
12 > import java.util.Collection;
13 > import java.util.concurrent.locks.LockSupport;
14  
15   /**
16   * 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 < * methods surrounding the main task processing loop.  If you do
21 < * create such a subclass, you will also need to supply a custom
22 < * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
18 > * 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 > * ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code
23 > * ForkJoinPool}.
24   *
25 + * @since 1.7
26 + * @author Doug Lea
27   */
28   public class ForkJoinWorkerThread extends Thread {
29      /*
30 <     * Algorithm overview:
30 >     * Overview:
31 >     *
32 >     * 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 <     * 1. Work-Stealing: Work-stealing queues are special forms of
41 <     * Deques that support only three of the four possible
42 <     * end-operations -- push, pop, and deq (aka steal), and only do
43 <     * so under the constraints that push and pop are called only from
44 <     * the owning thread, while deq may be called from other threads.
45 <     * (If you are unfamiliar with them, you probably want to read
46 <     * Herlihy and Shavit's book "The Art of Multiprocessor
47 <     * programming", chapter 16 describing these in more detail before
48 <     * proceeding.)  The main work-stealing queue design is roughly
49 <     * similar to "Dynamic Circular Work-Stealing Deque" by David
50 <     * Chase and Yossi Lev, SPAA 2005
51 <     * (http://research.sun.com/scalable/pubs/index.html).  The main
52 <     * difference ultimately stems from gc requirements that we null
53 <     * out taken slots as soon as we can, to maintain as small a
54 <     * footprint as possible even in programs generating huge numbers
55 <     * of tasks. To accomplish this, we shift the CAS arbitrating pop
56 <     * vs deq (steal) from being on the indices ("base" and "sp") to
57 <     * the slots themselves (mainly via method "casSlotNull()"). So,
58 <     * both a successful pop and deq mainly entail CAS'ing a nonnull
59 <     * slot to null.  Because we rely on CASes of references, we do
60 <     * not need tag bits on base or sp.  They are simple ints as used
61 <     * in any circular array-based queue (see for example ArrayDeque).
62 <     * Updates to the indices must still be ordered in a way that
63 <     * guarantees that (sp - base) > 0 means the queue is empty, but
64 <     * otherwise may err on the side of possibly making the queue
65 <     * appear nonempty when a push, pop, or deq have not fully
66 <     * committed. Note that this means that the deq operation,
67 <     * considered individually, is not wait-free. One thief cannot
68 <     * successfully continue until another in-progress one (or, if
69 <     * previously empty, a push) completes.  However, in the
70 <     * aggregate, we ensure at least probablistic non-blockingness. If
71 <     * an attempted steal fails, a thief always chooses a different
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 activate if necessary before
78 <     * stealing (see below).
77 >     * which gives threads a chance to set activation status if
78 >     * necessary before stealing.
79 >     *
80 >     * 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 >     * When a worker would otherwise be blocked waiting to join a
87 >     * task, it first tries a form of linear helping: Each worker
88 >     * records (in field currentSteal) the most recent task it stole
89 >     * from some other worker. Plus, it records (in field currentJoin)
90 >     * the task it is currently actively joining. Method joinTask uses
91 >     * these markers to try to find a worker to help (i.e., steal back
92 >     * a task from and execute it) that could hasten completion of the
93 >     * actively joined task. In essence, the joiner executes a task
94 >     * that would be on its own local deque had the to-be-joined task
95 >     * not been stolen. This may be seen as a conservative variant of
96 >     * the approach in Wagner & Calder "Leapfrogging: a portable
97 >     * technique for implementing efficient futures" SIGPLAN Notices,
98 >     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
99 >     * in that: (1) We only maintain dependency links across workers
100 >     * upon steals, rather than use per-task bookkeeping.  This may
101 >     * require a linear scan of workers array to locate stealers, but
102 >     * usually doesn't because stealers leave hints (that may become
103 >     * stale/wrong) of where to locate them. This isolates cost to
104 >     * when it is needed, rather than adding to per-task overhead.
105 >     * (2) It is "shallow", ignoring nesting and potentially cyclic
106 >     * mutual steals.  (3) It is intentionally racy: field currentJoin
107 >     * is updated only while actively joining, which means that we
108 >     * miss links in the chain during long-lived tasks, GC stalls etc
109 >     * (which is OK since blocking in such cases is usually a good
110 >     * idea).  (4) We bound the number of attempts to find work (see
111 >     * MAX_HELP_DEPTH) and fall back to suspending the worker and if
112 >     * necessary replacing it with a spare (see
113 >     * ForkJoinPool.awaitJoin).
114       *
115 <     * Efficient implementation of this approach currently relies on
116 <     * an uncomfortable amount of "Unsafe" mechanics. To maintain
115 >     * Efficient implementation of these algorithms currently relies
116 >     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
117       * correct orderings, reads and writes of variable base require
118 <     * volatile ordering.  Variable sp does not require volatile write
119 <     * but needs cheaper store-ordering on writes.  Because they are
120 <     * protected by volatile base reads, reads of the queue array and
121 <     * its slots do not need volatile load semantics, but writes (in
122 <     * push) require store order and CASes (in pop and deq) require
123 <     * (volatile) CAS semantics. Since these combinations aren't
124 <     * supported using ordinary volatiles, the only way to accomplish
125 <     * these effciently is to use direct Unsafe calls. (Using external
126 <     * AtomicIntegers and AtomicReferenceArrays for the indices and
127 <     * array is significantly slower because of memory locality and
128 <     * indirection effects.) Further, performance on most platforms is
129 <     * very sensitive to placement and sizing of the (resizable) queue
130 <     * array.  Even though these queues don't usually become all that
131 <     * big, the initial size must be large enough to counteract cache
118 >     * volatile ordering.  Variable sp does not require volatile
119 >     * writes but still needs store-ordering, which we accomplish by
120 >     * pre-incrementing sp before filling the slot with an ordered
121 >     * store.  (Pre-incrementing also enables backouts used in
122 >     * joinTask.)  Because they are protected by volatile base reads,
123 >     * reads of the queue array and its slots by other threads do not
124 >     * need volatile load semantics, but writes (in push) require
125 >     * store order and CASes (in pop and deq) require (volatile) CAS
126 >     * semantics.  (Michael, Saraswat, and Vechev's algorithm has
127 >     * similar properties, but without support for nulling slots.)
128 >     * Since these combinations aren't supported using ordinary
129 >     * volatiles, the only way to accomplish these efficiently is to
130 >     * use direct Unsafe calls. (Using external AtomicIntegers and
131 >     * AtomicReferenceArrays for the indices and array is
132 >     * significantly slower because of memory locality and indirection
133 >     * effects.)
134 >     *
135 >     * Further, performance on most platforms is very sensitive to
136 >     * placement and sizing of the (resizable) queue array.  Even
137 >     * though these queues don't usually become all that big, the
138 >     * initial size must be large enough to counteract cache
139       * contention effects across multiple queues (especially in the
140       * presence of GC cardmarking). Also, to improve thread-locality,
141 <     * queues are currently initialized immediately after the thread
142 <     * gets the initial signal to start processing tasks.  However,
143 <     * all queue-related methods except pushTask are written in a way
144 <     * that allows them to instead be lazily allocated and/or disposed
145 <     * 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.
141 >     * queues are initialized after starting.  All together, these
142 >     * low-level implementation choices produce as much as a factor of
143 >     * 4 performance improvement compared to naive implementations,
144 >     * and enable the processing of billions of tasks per second,
145 >     * sometimes at the expense of ugliness.
146       */
147  
148      /**
149 +     * Generator for initial random seeds for random victim
150 +     * selection. This is used only to create initial seeds. Random
151 +     * steals use a cheaper xorshift generator per steal attempt. We
152 +     * expect only rare contention on seedGenerator, so just use a
153 +     * plain Random.
154 +     */
155 +    private static final Random seedGenerator = new Random();
156 +
157 +    /**
158 +     * The maximum stolen->joining link depth allowed in helpJoinTask.
159 +     * Depths for legitimate chains are unbounded, but we use a fixed
160 +     * constant to avoid (otherwise unchecked) cycles and bound
161 +     * staleness of traversal parameters at the expense of sometimes
162 +     * blocking when we could be helping.
163 +     */
164 +    private static final int MAX_HELP_DEPTH = 8;
165 +
166 +    /**
167       * Capacity of work-stealing queue array upon initialization.
168 <     * Must be a power of two. Initial size must be at least 2, but is
168 >     * Must be a power of two. Initial size must be at least 4, but is
169       * padded to minimize cache effects.
170       */
171      private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
# Line 137 | Line 179 | public class ForkJoinWorkerThread extend
179      private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
180  
181      /**
182 <     * The pool this thread works in. Accessed directly by ForkJoinTask
182 >     * The pool this thread works in. Accessed directly by ForkJoinTask.
183       */
184      final ForkJoinPool pool;
185  
186      /**
187       * The work-stealing queue array. Size must be a power of two.
188 <     * Initialized when thread starts, to improve memory locality.
188 >     * Initialized in onStart, to improve memory locality.
189       */
190      private ForkJoinTask<?>[] queue;
191  
192      /**
193 +     * Index (mod queue.length) of least valid queue slot, which is
194 +     * always the next position to steal from if nonempty.
195 +     */
196 +    private volatile int base;
197 +
198 +    /**
199       * Index (mod queue.length) of next queue slot to push to or pop
200 <     * from. It is written only by owner thread, via ordered store.
201 <     * Both sp and base are allowed to wrap around on overflow, but
202 <     * (sp - base) still estimates size.
200 >     * from. It is written only by owner thread, and accessed by other
201 >     * threads only after reading (volatile) base.  Both sp and base
202 >     * are allowed to wrap around on overflow, but (sp - base) still
203 >     * estimates size.
204       */
205 <    private volatile int sp;
205 >    private int sp;
206  
207      /**
208 <     * Index (mod queue.length) of least valid queue slot, which is
209 <     * always the next position to steal from if nonempty.
208 >     * The index of most recent stealer, used as a hint to avoid
209 >     * traversal in method helpJoinTask. This is only a hint because a
210 >     * worker might have had multiple steals and this only holds one
211 >     * of them (usually the most current). Declared non-volatile,
212 >     * relying on other prevailing sync to keep reasonably current.
213       */
214 <    private volatile int base;
214 >    private int stealHint;
215  
216      /**
217 <     * Activity status. When true, this worker is considered active.
218 <     * Must be false upon construction. It must be true when executing
219 <     * tasks, and BEFORE stealing a task. It must be false before
220 <     * calling pool.sync
217 >     * Run state of this worker. In addition to the usual run levels,
218 >     * tracks if this worker is suspended as a spare, and if it was
219 >     * killed (trimmed) while suspended. However, "active" status is
220 >     * maintained separately and modified only in conjunction with
221 >     * CASes of the pool's runState (which are currently sadly
222 >     * manually inlined for performance.)  Accessed directly by pool
223 >     * to simplify checks for normal (zero) status.
224       */
225 <    private boolean active;
225 >    volatile int runState;
226 >
227 >    private static final int TERMINATING = 0x01;
228 >    private static final int TERMINATED  = 0x02;
229 >    private static final int SUSPENDED   = 0x04; // inactive spare
230 >    private static final int TRIMMED     = 0x08; // killed while suspended
231  
232      /**
233 <     * Run state of this worker. Supports simple versions of the usual
234 <     * shutdown/shutdownNow control.
233 >     * Number of steals, transferred and reset in pool callbacks pool
234 >     * when idle Accessed directly by pool.
235       */
236 <    private volatile int runState;
236 >    int stealCount;
237  
238      /**
239       * Seed for random number generator for choosing steal victims.
240 <     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
240 >     * Uses Marsaglia xorshift. Must be initialized as nonzero.
241       */
242      private int seed;
243  
244      /**
245 <     * Number of steals, transferred to pool when idle
245 >     * Activity status. When true, this worker is considered active.
246 >     * Accessed directly by pool.  Must be false upon construction.
247       */
248 <    private int stealCount;
248 >    boolean active;
249 >
250 >    /**
251 >     * True if use local fifo, not default lifo, for local polling.
252 >     * Shadows value from ForkJoinPool.
253 >     */
254 >    private final boolean locallyFifo;
255  
256      /**
257       * Index of this worker in pool array. Set once by pool before
258 <     * running, and accessed directly by pool during cleanup etc
258 >     * running, and accessed directly by pool to locate this worker in
259 >     * its workers array.
260       */
261      int poolIndex;
262  
263      /**
264 <     * The last barrier event waited for. Accessed in pool callback
265 <     * methods, but only by current thread.
264 >     * The last pool event waited for. Accessed only by pool in
265 >     * callback methods invoked within this thread.
266 >     */
267 >    int lastEventCount;
268 >
269 >    /**
270 >     * Encoded index and event count of next event waiter. Accessed
271 >     * only by ForkJoinPool for managing event waiters.
272 >     */
273 >    volatile long nextWaiter;
274 >
275 >    /**
276 >     * Number of times this thread suspended as spare. Accessed only
277 >     * by pool.
278       */
279 <    long lastEventCount;
279 >    int spareCount;
280  
281      /**
282 <     * True if use local fifo, not default lifo, for local polling
282 >     * Encoded index and count of next spare waiter. Accessed only
283 >     * by ForkJoinPool for managing spares.
284       */
285 <    private boolean locallyFifo;
285 >    volatile int nextSpare;
286 >
287 >    /**
288 >     * The task currently being joined, set only when actively trying
289 >     * to helpStealer. Written only by current thread, but read by
290 >     * others.
291 >     */
292 >    private volatile ForkJoinTask<?> currentJoin;
293 >
294 >    /**
295 >     * The task most recently stolen from another worker (or
296 >     * submission queue).  Written only by current thread, but read by
297 >     * others.
298 >     */
299 >    private volatile ForkJoinTask<?> currentSteal;
300  
301      /**
302       * Creates a ForkJoinWorkerThread operating in the given pool.
303 +     *
304       * @param pool the pool this thread works in
305       * @throws NullPointerException if pool is null
306       */
307      protected ForkJoinWorkerThread(ForkJoinPool pool) {
212        if (pool == null) throw new NullPointerException();
308          this.pool = pool;
309 <        // Note: poolIndex is set by pool during construction
310 <        // Remaining initialization is deferred to onStart
309 >        this.locallyFifo = pool.locallyFifo;
310 >        setDaemon(true);
311 >        // To avoid exposing construction details to subclasses,
312 >        // remaining initialization is in start() and onStart()
313      }
314  
315 <    // Public access methods
315 >    /**
316 >     * Performs additional initialization and starts this thread
317 >     */
318 >    final void start(int poolIndex, UncaughtExceptionHandler ueh) {
319 >        this.poolIndex = poolIndex;
320 >        if (ueh != null)
321 >            setUncaughtExceptionHandler(ueh);
322 >        start();
323 >    }
324 >
325 >    // Public/protected methods
326  
327      /**
328 <     * Returns the pool hosting this thread
328 >     * Returns the pool hosting this thread.
329 >     *
330       * @return the pool
331       */
332      public ForkJoinPool getPool() {
# Line 231 | Line 339 | public class ForkJoinWorkerThread extend
339       * threads (minus one) that have ever been created in the pool.
340       * This method may be useful for applications that track status or
341       * collect results per-worker rather than per-task.
342 <     * @return the index number.
342 >     *
343 >     * @return the index number
344       */
345      public int getPoolIndex() {
346          return poolIndex;
347      }
348  
349      /**
350 <     * Establishes local first-in-first-out scheduling mode for forked
351 <     * tasks that are never joined.
352 <     * @param async if true, use locally FIFO scheduling
350 >     * Initializes internal state after construction but before
351 >     * processing any tasks. If you override this method, you must
352 >     * invoke super.onStart() at the beginning of the method.
353 >     * Initialization requires care: Most fields must have legal
354 >     * default values, to ensure that attempted accesses from other
355 >     * threads work correctly even before this thread starts
356 >     * processing tasks.
357       */
358 <    void setAsyncMode(boolean async) {
359 <        locallyFifo = async;
360 <    }
248 <
249 <    // Runstate management
250 <
251 <    // Runstate values. Order matters
252 <    private static final int RUNNING     = 0;
253 <    private static final int SHUTDOWN    = 1;
254 <    private static final int TERMINATING = 2;
255 <    private static final int TERMINATED  = 3;
256 <
257 <    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
258 <    final boolean isTerminating() { return runState >= TERMINATING;  }
259 <    final boolean isTerminated()  { return runState == TERMINATED; }
260 <    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
261 <    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
358 >    protected void onStart() {
359 >        int rs = seedGenerator.nextInt();
360 >        seed = rs == 0? 1 : rs; // seed must be nonzero
361  
362 <    /**
363 <     * Transition to at least the given state. Return true if not
364 <     * already at least given state.
365 <     */
267 <    private boolean transitionRunStateTo(int state) {
268 <        for (;;) {
269 <            int s = runState;
270 <            if (s >= state)
271 <                return false;
272 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
273 <                return true;
274 <        }
275 <    }
362 >        // Allocate name string and arrays in this thread
363 >        String pid = Integer.toString(pool.getPoolNumber());
364 >        String wid = Integer.toString(poolIndex);
365 >        setName("ForkJoinPool-" + pid + "-worker-" + wid);
366  
367 <    /**
278 <     * Try to set status to active; fail on contention
279 <     */
280 <    private boolean tryActivate() {
281 <        if (!active) {
282 <            if (!pool.tryIncrementActiveCount())
283 <                return false;
284 <            active = true;
285 <        }
286 <        return true;
367 >        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
368      }
369  
370      /**
371 <     * Try to set status to active; fail on contention
371 >     * Performs cleanup associated with termination of this worker
372 >     * thread.  If you override this method, you must invoke
373 >     * {@code super.onTermination} at the end of the overridden method.
374 >     *
375 >     * @param exception the exception causing this thread to abort due
376 >     * to an unrecoverable error, or {@code null} if completed normally
377       */
378 <    private boolean tryInactivate() {
379 <        if (active) {
380 <            if (!pool.tryDecrementActiveCount())
381 <                return false;
382 <            active = false;
378 >    protected void onTermination(Throwable exception) {
379 >        try {
380 >            ForkJoinPool p = pool;
381 >            if (active) {
382 >                int a; // inline p.tryDecrementActiveCount
383 >                active = false;
384 >                do {} while (!UNSAFE.compareAndSwapInt
385 >                             (p, poolRunStateOffset, a = p.runState, a - 1));
386 >            }
387 >            cancelTasks();
388 >            setTerminated();
389 >            p.workerTerminated(this);
390 >        } catch (Throwable ex) {        // Shouldn't ever happen
391 >            if (exception == null)      // but if so, at least rethrown
392 >                exception = ex;
393 >        } finally {
394 >            if (exception != null)
395 >                UNSAFE.throwException(exception);
396          }
298        return true;
299    }
300
301    /**
302     * Computes next value for random victim probe. Scans don't
303     * require a very high quality generator, but also not a crummy
304     * one. Marsaglia xor-shift is cheap and works well.
305     */
306    private static int xorShift(int r) {
307        r ^= r << 1;
308        r ^= r >>> 3;
309        r ^= r << 10;
310        return r;
397      }
398  
313    // Lifecycle methods
314
399      /**
400       * This method is required to be public, but should never be
401       * called explicitly. It performs the main run loop to execute
# Line 321 | Line 405 | public class ForkJoinWorkerThread extend
405          Throwable exception = null;
406          try {
407              onStart();
324            pool.sync(this); // await first pool event
408              mainLoop();
409          } catch (Throwable ex) {
410              exception = ex;
# Line 330 | Line 413 | public class ForkJoinWorkerThread extend
413          }
414      }
415  
416 +    // helpers for run()
417 +
418      /**
419 <     * Execute tasks until shut down.
419 >     * Find and execute tasks and check status while running
420       */
421      private void mainLoop() {
422 <        while (!isShutdown()) {
423 <            ForkJoinTask<?> t = pollTask();
424 <            if (t != null || (t = pollSubmission()) != null)
425 <                t.quietlyExec();
426 <            else if (tryInactivate())
427 <                pool.sync(this);
422 >        boolean ran = false; // true if ran a task on last step
423 >        ForkJoinPool p = pool;
424 >        for (;;) {
425 >            p.preStep(this, ran);
426 >            if (runState != 0)
427 >                break;
428 >            ran = tryExecSteal() || tryExecSubmission();
429          }
430      }
431  
432      /**
433 <     * Initializes internal state after construction but before
434 <     * processing any tasks. If you override this method, you must
435 <     * invoke super.onStart() at the beginning of the method.
350 <     * Initialization requires care: Most fields must have legal
351 <     * default values, to ensure that attempted accesses from other
352 <     * threads work correctly even before this thread starts
353 <     * processing tasks.
433 >     * Try to steal a task and execute it
434 >     *
435 >     * @return true if ran a task
436       */
437 <    protected void onStart() {
438 <        // Allocate while starting to improve chances of thread-local
439 <        // isolation
440 <        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
441 <        // Initial value of seed need not be especially random but
442 <        // should differ across workers and must be nonzero
443 <        int p = poolIndex + 1;
444 <        seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
437 >    private boolean tryExecSteal() {
438 >        ForkJoinTask<?> t;
439 >        if ((t = scan()) != null) {
440 >            t.quietlyExec();
441 >            UNSAFE.putOrderedObject(this, currentStealOffset, null);
442 >            if (sp != base)
443 >                execLocalTasks();
444 >            return true;
445 >        }
446 >        return false;
447      }
448  
449      /**
450 <     * Perform cleanup associated with termination of this worker
367 <     * thread.  If you override this method, you must invoke
368 <     * super.onTermination at the end of the overridden method.
450 >     * If a submission exists, try to activate and run it;
451       *
452 <     * @param exception the exception causing this thread to abort due
371 <     * to an unrecoverable error, or null if completed normally.
452 >     * @return true if ran a task
453       */
454 <    protected void onTermination(Throwable exception) {
455 <        // Execute remaining local tasks unless aborting or terminating
456 <        while (exception == null &&  !pool.isTerminating() && base != sp) {
457 <            try {
458 <                ForkJoinTask<?> t = popTask();
459 <                if (t != null)
454 >    private boolean tryExecSubmission() {
455 >        ForkJoinPool p = pool;
456 >        while (p.hasQueuedSubmissions()) {
457 >            ForkJoinTask<?> t; int a;
458 >            if (active || // inline p.tryIncrementActiveCount
459 >                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
460 >                                                   a = p.runState, a + 1))) {
461 >                if ((t = p.pollSubmission()) != null) {
462 >                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
463                      t.quietlyExec();
464 <            } catch(Throwable ex) {
465 <                exception = ex;
464 >                    UNSAFE.putOrderedObject(this, currentStealOffset, null);
465 >                    if (sp != base)
466 >                        execLocalTasks();
467 >                    return true;
468 >                }
469              }
470          }
471 <        // Cancel other tasks, transition status, notify pool, and
385 <        // propagate exception to uncaught exception handler
386 <        try {
387 <            do;while (!tryInactivate()); // ensure inactive
388 <            cancelTasks();
389 <            runState = TERMINATED;
390 <            pool.workerTerminated(this);
391 <        } catch (Throwable ex) {        // Shouldn't ever happen
392 <            if (exception == null)      // but if so, at least rethrown
393 <                exception = ex;
394 <        } finally {
395 <            if (exception != null)
396 <                ForkJoinTask.rethrowException(exception);
397 <        }
471 >        return false;
472      }
473  
400    // Intrinsics-based support for queue operations.
401
474      /**
475 <     * Add in store-order the given task at given slot of q to
476 <     * null. Caller must ensure q is nonnull and index is in range.
475 >     * Runs local tasks until queue is empty or shut down.  Call only
476 >     * while active.
477       */
478 <    private static void setSlot(ForkJoinTask<?>[] q, int i,
479 <                                ForkJoinTask<?> t){
480 <        _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
478 >    private void execLocalTasks() {
479 >        while (runState == 0) {
480 >            ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
481 >            if (t != null)
482 >                t.quietlyExec();
483 >            else if (sp == base)
484 >                break;
485 >        }
486      }
487  
488 +    /*
489 +     * Intrinsics-based atomic writes for queue slots. These are
490 +     * basically the same as methods in AtomicObjectArray, but
491 +     * specialized for (1) ForkJoinTask elements (2) requirement that
492 +     * nullness and bounds checks have already been performed by
493 +     * callers and (3) effective offsets are known not to overflow
494 +     * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
495 +     * need corresponding version for reads: plain array reads are OK
496 +     * because they protected by other volatile reads and are
497 +     * confirmed by CASes.
498 +     *
499 +     * Most uses don't actually call these methods, but instead contain
500 +     * inlined forms that enable more predictable optimization.  We
501 +     * don't define the version of write used in pushTask at all, but
502 +     * instead inline there a store-fenced array slot write.
503 +     */
504 +
505      /**
506 <     * CAS given slot of q to null. Caller must ensure q is nonnull
507 <     * and index is in range.
506 >     * CASes slot i of array q from t to null. Caller must ensure q is
507 >     * non-null and index is in range.
508       */
509 <    private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
510 <                                       ForkJoinTask<?> t) {
511 <        return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
509 >    private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
510 >                                             ForkJoinTask<?> t) {
511 >        return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
512      }
513  
514      /**
515 <     * Sets sp in store-order.
515 >     * Performs a volatile write of the given task at given slot of
516 >     * array q.  Caller must ensure q is non-null and index is in
517 >     * range. This method is used only during resets and backouts.
518       */
519 <    private void storeSp(int s) {
520 <        _unsafe.putOrderedInt(this, spOffset, s);
519 >    private static final void writeSlot(ForkJoinTask<?>[] q, int i,
520 >                                              ForkJoinTask<?> t) {
521 >        UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
522      }
523  
524 <    // Main queue methods
524 >    // queue methods
525  
526      /**
527 <     * Pushes a task. Called only by current thread.
528 <     * @param t the task. Caller must ensure nonnull
527 >     * Pushes a task. Call only from this thread.
528 >     *
529 >     * @param t the task. Caller must ensure non-null.
530       */
531      final void pushTask(ForkJoinTask<?> t) {
532          ForkJoinTask<?>[] q = queue;
533 <        int mask = q.length - 1;
534 <        int s = sp;
535 <        setSlot(q, s & mask, t);
536 <        storeSp(++s);
537 <        if ((s -= base) == 1)
538 <            pool.signalWork();
539 <        else if (s >= mask)
442 <            growQueue();
533 >        int mask = q.length - 1; // implicit assert q != null
534 >        int s = sp++;            // ok to increment sp before slot write
535 >        UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
536 >        if ((s -= base) == 0)
537 >            pool.signalWork();   // was empty
538 >        else if (s == mask)
539 >            growQueue();         // is full
540      }
541  
542      /**
543       * Tries to take a task from the base of the queue, failing if
544 <     * either empty or contended.
545 <     * @return a task, or null if none or contended.
544 >     * empty or contended. Note: Specializations of this code appear
545 >     * in locallyDeqTask and elsewhere.
546 >     *
547 >     * @return a task, or null if none or contended
548       */
549      final ForkJoinTask<?> deqTask() {
550          ForkJoinTask<?> t;
551          ForkJoinTask<?>[] q;
552 <        int i;
454 <        int b;
552 >        int b, i;
553          if (sp != (b = base) &&
554              (q = queue) != null && // must read q after b
555 <            (t = q[i = (q.length - 1) & b]) != null &&
556 <            casSlotNull(q, i, t)) {
555 >            (t = q[i = (q.length - 1) & b]) != null && base == b &&
556 >            UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
557              base = b + 1;
558              return t;
559          }
# Line 463 | Line 561 | public class ForkJoinWorkerThread extend
561      }
562  
563      /**
564 <     * Returns a popped task, or null if empty. Ensures active status
565 <     * if nonnull. Called only by current thread.
564 >     * Tries to take a task from the base of own queue. Assumes active
565 >     * status.  Called only by current thread.
566 >     *
567 >     * @return a task, or null if none
568 >     */
569 >    final ForkJoinTask<?> locallyDeqTask() {
570 >        ForkJoinTask<?>[] q = queue;
571 >        if (q != null) {
572 >            ForkJoinTask<?> t;
573 >            int b, i;
574 >            while (sp != (b = base)) {
575 >                if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
576 >                    UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
577 >                                                t, null)) {
578 >                    base = b + 1;
579 >                    return t;
580 >                }
581 >            }
582 >        }
583 >        return null;
584 >    }
585 >
586 >    /**
587 >     * Returns a popped task, or null if empty. Assumes active status.
588 >     * Called only by current thread.
589       */
590 <    final ForkJoinTask<?> popTask() {
591 <        int s = sp;
592 <        while (s != base) {
593 <            if (tryActivate()) {
594 <                ForkJoinTask<?>[] q = queue;
595 <                int mask = q.length - 1;
596 <                int i = (s - 1) & mask;
590 >    private ForkJoinTask<?> popTask() {
591 >        ForkJoinTask<?>[] q = queue;
592 >        if (q != null) {
593 >            int s;
594 >            while ((s = sp) != base) {
595 >                int i = (q.length - 1) & --s;
596 >                long u = (i << qShift) + qBase; // raw offset
597                  ForkJoinTask<?> t = q[i];
598 <                if (t == null || !casSlotNull(q, i, t))
598 >                if (t == null)   // lost to stealer
599                      break;
600 <                storeSp(s - 1);
601 <                return t;
600 >                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
601 >                    sp = s; // putOrderedInt may encourage more timely write
602 >                    // UNSAFE.putOrderedInt(this, spOffset, s);
603 >                    return t;
604 >                }
605              }
606          }
607          return null;
608      }
609  
610      /**
611 <     * Specialized version of popTask to pop only if
612 <     * topmost element is the given task. Called only
613 <     * by current thread while active.
614 <     * @param t the task. Caller must ensure nonnull
611 >     * Specialized version of popTask to pop only if topmost element
612 >     * is the given task. Called only by current thread while
613 >     * active.
614 >     *
615 >     * @param t the task. Caller must ensure non-null.
616       */
617      final boolean unpushTask(ForkJoinTask<?> t) {
618 +        int s;
619          ForkJoinTask<?>[] q = queue;
620 <        int mask = q.length - 1;
621 <        int s = sp - 1;
622 <        if (casSlotNull(q, s & mask, t)) {
623 <            storeSp(s);
620 >        if ((s = sp) != base && q != null &&
621 >            UNSAFE.compareAndSwapObject
622 >            (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
623 >            sp = s; // putOrderedInt may encourage more timely write
624 >            // UNSAFE.putOrderedInt(this, spOffset, s);
625              return true;
626          }
627          return false;
628      }
629  
630      /**
631 <     * Returns next task.
631 >     * Returns next task or null if empty or contended
632       */
633      final ForkJoinTask<?> peekTask() {
634          ForkJoinTask<?>[] q = queue;
635          if (q == null)
636              return null;
637          int mask = q.length - 1;
638 <        int i = locallyFifo? base : (sp - 1);
638 >        int i = locallyFifo ? base : (sp - 1);
639          return q[i & mask];
640      }
641  
# Line 534 | Line 661 | public class ForkJoinWorkerThread extend
661              ForkJoinTask<?> t = oldQ[oldIndex];
662              if (t != null && !casSlotNull(oldQ, oldIndex, t))
663                  t = null;
664 <            setSlot(newQ, b & newMask, t);
664 >            writeSlot(newQ, b & newMask, t);
665          } while (++b != bf);
666          pool.signalWork();
667      }
668  
669      /**
670 +     * Computes next value for random victim probe in scan().  Scans
671 +     * don't require a very high quality generator, but also not a
672 +     * crummy one.  Marsaglia xor-shift is cheap and works well enough.
673 +     * Note: This is manually inlined in scan()
674 +     */
675 +    private static final int xorShift(int r) {
676 +        r ^= r << 13;
677 +        r ^= r >>> 17;
678 +        return r ^ (r << 5);
679 +    }
680 +
681 +    /**
682       * Tries to steal a task from another worker. Starts at a random
683       * index of workers array, and probes workers until finding one
684       * with non-empty queue or finding that all are empty.  It
685       * randomly selects the first n probes. If these are empty, it
686 <     * resorts to a full circular traversal, which is necessary to
687 <     * accurately set active status by caller. Also restarts if pool
688 <     * events occurred since last scan, which forces refresh of
689 <     * workers array, in case barrier was associated with resize.
686 >     * resorts to a circular sweep, which is necessary to accurately
687 >     * set active status. (The circular sweep uses steps of
688 >     * approximately half the array size plus 1, to avoid bias
689 >     * stemming from leftmost packing of the array in ForkJoinPool.)
690       *
691       * This method must be both fast and quiet -- usually avoiding
692       * memory accesses that could disrupt cache sharing etc other than
693 <     * those needed to check for and take tasks. This accounts for,
694 <     * among other things, updating random seed in place without
695 <     * storing it until exit.
693 >     * those needed to check for and take tasks (or to activate if not
694 >     * already active). This accounts for, among other things,
695 >     * updating random seed in place without storing it until exit.
696       *
697       * @return a task, or null if none found
698       */
699      private ForkJoinTask<?> scan() {
700 <        ForkJoinTask<?> t = null;
701 <        int r = seed;                    // extract once to keep scan quiet
702 <        ForkJoinWorkerThread[] ws;       // refreshed on outer loop
703 <        int mask;                        // must be power 2 minus 1 and > 0
704 <        outer:do {
705 <            if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
706 <                int idx = r;
707 <                int probes = ~mask;      // use random index while negative
708 <                for (;;) {
709 <                    r = xorShift(r);     // update random seed
710 <                    ForkJoinWorkerThread v = ws[mask & idx];
711 <                    if (v == null || v.sp == v.base) {
712 <                        if (probes <= mask)
713 <                            idx = (probes++ < 0)? r : (idx + 1);
714 <                        else
715 <                            break;
700 >        ForkJoinPool p = pool;
701 >        ForkJoinWorkerThread[] ws;        // worker array
702 >        int n;                            // upper bound of #workers
703 >        if ((ws = p.workers) != null && (n = ws.length) > 1) {
704 >            boolean canSteal = active;    // shadow active status
705 >            int r = seed;                 // extract seed once
706 >            int mask = n - 1;
707 >            int j = -n;                   // loop counter
708 >            int k = r;                    // worker index, random if j < 0
709 >            for (;;) {
710 >                ForkJoinWorkerThread v = ws[k & mask];
711 >                r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
712 >                ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a;
713 >                if (v != null && (b = v.base) != v.sp &&
714 >                    (q = v.queue) != null) {
715 >                    int i = (q.length - 1) & b;
716 >                    long u = (i << qShift) + qBase; // raw offset
717 >                    int pid = poolIndex;
718 >                    if ((t = q[i]) != null) {
719 >                        if (!canSteal &&  // inline p.tryIncrementActiveCount
720 >                            UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
721 >                                                     a = p.runState, a + 1))
722 >                            canSteal = active = true;
723 >                        if (canSteal && v.base == b++ &&
724 >                            UNSAFE.compareAndSwapObject(q, u, t, null)) {
725 >                            v.base = b;
726 >                            v.stealHint = pid;
727 >                            UNSAFE.putOrderedObject(this,
728 >                                                    currentStealOffset, t);
729 >                            seed = r;
730 >                            ++stealCount;
731 >                            return t;
732 >                        }
733                      }
734 <                    else if (!tryActivate() || (t = v.deqTask()) == null)
735 <                        continue outer;  // restart on contention
580 <                    else
581 <                        break outer;
734 >                    j = -n;
735 >                    k = r;                // restart on contention
736                  }
737 +                else if (++j <= 0)
738 +                    k = r;
739 +                else if (j <= n)
740 +                    k += (n >>> 1) | 1;
741 +                else
742 +                    break;
743              }
744 <        } while (pool.hasNewSyncEvent(this)); // retry on pool events
745 <        seed = r;
586 <        return t;
744 >        }
745 >        return null;
746      }
747  
748 +    // Run State management
749 +
750 +    // status check methods used mainly by ForkJoinPool
751 +    final boolean isRunning()     { return runState == 0; }
752 +    final boolean isTerminating() { return (runState & TERMINATING) != 0; }
753 +    final boolean isTerminated()  { return (runState & TERMINATED) != 0; }
754 +    final boolean isSuspended()   { return (runState & SUSPENDED) != 0; }
755 +    final boolean isTrimmed()     { return (runState & TRIMMED) != 0; }
756 +
757      /**
758 <     * gets and removes a local or stolen a task
759 <     * @return a task, if available
758 >     * Sets state to TERMINATING. Does NOT unpark or interrupt
759 >     * to wake up if currently blocked. Callers must do so if desired.
760       */
761 <    final ForkJoinTask<?> pollTask() {
762 <        ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
763 <        if (t == null && (t = scan()) != null)
764 <            ++stealCount;
765 <        return t;
761 >    final void shutdown() {
762 >        for (;;) {
763 >            int s = runState;
764 >            if ((s & (TERMINATING|TERMINATED)) != 0)
765 >                break;
766 >            if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
767 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
768 >                                             (s & ~SUSPENDED) |
769 >                                             (TRIMMED|TERMINATING)))
770 >                    break;
771 >            }
772 >            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
773 >                                              s | TERMINATING))
774 >                break;
775 >        }
776      }
777  
778      /**
779 <     * gets a local task
602 <     * @return a task, if available
779 >     * Sets state to TERMINATED. Called only by onTermination()
780       */
781 <    final ForkJoinTask<?> pollLocalTask() {
782 <        return locallyFifo? deqTask() : popTask();
781 >    private void setTerminated() {
782 >        int s;
783 >        do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
784 >                                               s = runState,
785 >                                               s | (TERMINATING|TERMINATED)));
786      }
787  
788      /**
789 <     * Returns a pool submission, if one exists, activating first.
790 <     * @return a submission, if available
789 >     * If suspended, tries to set status to unsuspended.
790 >     * Does NOT wake up if blocked.
791 >     *
792 >     * @return true if successful
793       */
794 <    private ForkJoinTask<?> pollSubmission() {
794 >    final boolean tryUnsuspend() {
795 >        int s;
796 >        while (((s = runState) & SUSPENDED) != 0) {
797 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
798 >                                         s & ~SUSPENDED))
799 >                return true;
800 >        }
801 >        return false;
802 >    }
803 >
804 >    /**
805 >     * Sets suspended status and blocks as spare until resumed
806 >     * or shutdown.
807 >     */
808 >    final void suspendAsSpare() {
809 >        for (;;) {                  // set suspended unless terminating
810 >            int s = runState;
811 >            if ((s & TERMINATING) != 0) { // must kill
812 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
813 >                                             s | (TRIMMED | TERMINATING)))
814 >                    return;
815 >            }
816 >            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
817 >                                              s | SUSPENDED))
818 >                break;
819 >        }
820          ForkJoinPool p = pool;
821 <        while (p.hasQueuedSubmissions()) {
822 <            ForkJoinTask<?> t;
823 <            if (tryActivate() && (t = p.pollSubmission()) != null)
824 <                return t;
821 >        p.pushSpare(this);
822 >        while ((runState & SUSPENDED) != 0) {
823 >            if (p.tryAccumulateStealCount(this)) {
824 >                interrupted();          // clear/ignore interrupts
825 >                if ((runState & SUSPENDED) == 0)
826 >                    break;
827 >                LockSupport.park(this);
828 >            }
829          }
619        return null;
830      }
831  
832 <    // Methods accessed only by Pool
832 >    // Misc support methods for ForkJoinPool
833 >
834 >    /**
835 >     * Returns an estimate of the number of tasks in the queue.  Also
836 >     * used by ForkJoinTask.
837 >     */
838 >    final int getQueueSize() {
839 >        int n; // external calls must read base first
840 >        return (n = -base + sp) <= 0 ? 0 : n;
841 >    }
842  
843      /**
844       * Removes and cancels all tasks in queue.  Can be called from any
845       * thread.
846       */
847      final void cancelTasks() {
848 <        ForkJoinTask<?> t;
849 <        while (base != sp && (t = deqTask()) != null)
850 <            t.cancelIgnoringExceptions();
848 >        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
849 >        if (cj != null) {
850 >            currentJoin = null;
851 >            cj.cancelIgnoringExceptions();
852 >            try {
853 >                this.interrupt(); // awaken wait
854 >            } catch (SecurityException ignore) {
855 >            }
856 >        }
857 >        ForkJoinTask<?> cs = currentSteal;
858 >        if (cs != null) {
859 >            currentSteal = null;
860 >            cs.cancelIgnoringExceptions();
861 >        }
862 >        while (base != sp) {
863 >            ForkJoinTask<?> t = deqTask();
864 >            if (t != null)
865 >                t.cancelIgnoringExceptions();
866 >        }
867      }
868  
869      /**
870 <     * Drains tasks to given collection c
870 >     * Drains tasks to given collection c.
871 >     *
872       * @return the number of tasks drained
873       */
874 <    final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
874 >    final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
875          int n = 0;
876 <        ForkJoinTask<?> t;
877 <        while (base != sp && (t = deqTask()) != null) {
878 <            c.add(t);
879 <            ++n;
876 >        while (base != sp) {
877 >            ForkJoinTask<?> t = deqTask();
878 >            if (t != null) {
879 >                c.add(t);
880 >                ++n;
881 >            }
882          }
883          return n;
884      }
885  
886 +    // Support methods for ForkJoinTask
887 +
888      /**
889 <     * Get and clear steal count for accumulation by pool.  Called
890 <     * only when known to be idle (in pool.sync and termination).
889 >     * Gets and removes a local task.
890 >     *
891 >     * @return a task, if available
892       */
893 <    final int getAndClearStealCount() {
894 <        int sc = stealCount;
895 <        stealCount = 0;
896 <        return sc;
893 >    final ForkJoinTask<?> pollLocalTask() {
894 >        ForkJoinPool p = pool;
895 >        while (sp != base) {
896 >            int a; // inline p.tryIncrementActiveCount
897 >            if (active ||
898 >                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
899 >                                                   a = p.runState, a + 1)))
900 >                return locallyFifo? locallyDeqTask() : popTask();
901 >        }
902 >        return null;
903      }
904  
905      /**
906 <     * Returns true if at least one worker in the given array appears
907 <     * to have at least one queued task.
908 <     * @param ws array of workers
909 <     */
910 <    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
911 <        if (ws != null) {
912 <            int len = ws.length;
913 <            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
914 <                for (int i = 0; i < len; ++i) {
915 <                    ForkJoinWorkerThread w = ws[i];
669 <                    if (w != null && w.sp != w.base)
670 <                        return true;
671 <                }
672 <            }
906 >     * Gets and removes a local or stolen task.
907 >     *
908 >     * @return a task, if available
909 >     */
910 >    final ForkJoinTask<?> pollTask() {
911 >        ForkJoinTask<?> t = pollLocalTask();
912 >        if (t == null) {
913 >            t = scan();
914 >            // cannot retain/track/help steal
915 >            UNSAFE.putOrderedObject(this, currentStealOffset, null);
916          }
917 <        return false;
917 >        return t;
918      }
919  
677    // Support methods for ForkJoinTask
678
920      /**
921 <     * Returns an estimate of the number of tasks in the queue.
921 >     * Possibly runs some tasks and/or blocks, until task is done.
922 >     *
923 >     * @param joinMe the task to join
924       */
925 <    final int getQueueSize() {
926 <        int n = sp - base;
927 <        return n < 0? 0 : n; // suppress momentarily negative values
925 >    final void joinTask(ForkJoinTask<?> joinMe) {
926 >        // currentJoin only written by this thread; only need ordered store
927 >        ForkJoinTask<?> prevJoin = currentJoin;
928 >        UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
929 >        if (sp != base)
930 >            localHelpJoinTask(joinMe);
931 >        if (joinMe.status >= 0)
932 >            pool.awaitJoin(joinMe, this);
933 >        UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
934      }
935  
936      /**
937 <     * Returns an estimate of the number of tasks, offset by a
938 <     * function of number of idle workers.
937 >     * Run tasks in local queue until given task is done.
938 >     *
939 >     * @param joinMe the task to join
940       */
941 <    final int getEstimatedSurplusTaskCount() {
942 <        // The halving approximates weighting idle vs non-idle workers
943 <        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
941 >    private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
942 >        int s;
943 >        ForkJoinTask<?>[] q;
944 >        while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
945 >            int i = (q.length - 1) & --s;
946 >            long u = (i << qShift) + qBase; // raw offset
947 >            ForkJoinTask<?> t = q[i];
948 >            if (t == null)  // lost to a stealer
949 >                break;
950 >            if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
951 >                /*
952 >                 * This recheck (and similarly in helpJoinTask)
953 >                 * handles cases where joinMe is independently
954 >                 * cancelled or forced even though there is other work
955 >                 * available. Back out of the pop by putting t back
956 >                 * into slot before we commit by writing sp.
957 >                 */
958 >                if (joinMe.status < 0) {
959 >                    UNSAFE.putObjectVolatile(q, u, t);
960 >                    break;
961 >                }
962 >                sp = s;
963 >                // UNSAFE.putOrderedInt(this, spOffset, s);
964 >                t.quietlyExec();
965 >            }
966 >        }
967      }
968  
969      /**
970 <     * Scan, returning early if joinMe done
970 >     * Unless terminating, tries to locate and help perform tasks for
971 >     * a stealer of the given task, or in turn one of its stealers.
972 >     * Traces currentSteal->currentJoin links looking for a thread
973 >     * working on a descendant of the given task and with a non-empty
974 >     * queue to steal back and execute tasks from.
975 >     *
976 >     * The implementation is very branchy to cope with potential
977 >     * inconsistencies or loops encountering chains that are stale,
978 >     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
979 >     * of these cases are dealt with by just returning back to the
980 >     * caller, who is expected to retry if other join mechanisms also
981 >     * don't work out.
982 >     *
983 >     * @param joinMe the task to join
984       */
985 <    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
986 <        ForkJoinTask<?> t = pollTask();
987 <        if (t != null && joinMe.status < 0 && sp == base) {
988 <            pushTask(t); // unsteal if done and this task would be stealable
989 <            t = null;
985 >    final void helpJoinTask(ForkJoinTask<?> joinMe) {
986 >        ForkJoinWorkerThread[] ws;
987 >        int n;
988 >        if (joinMe.status < 0)                // already done
989 >            return;
990 >        if ((runState & TERMINATING) != 0) {  // cancel if shutting down
991 >            joinMe.cancelIgnoringExceptions();
992 >            return;
993          }
994 <        return t;
994 >        if ((ws = pool.workers) == null || (n = ws.length) <= 1)
995 >            return;                           // need at least 2 workers
996 >
997 >        ForkJoinTask<?> task = joinMe;        // base of chain
998 >        ForkJoinWorkerThread thread = this;   // thread with stolen task
999 >        for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1000 >            // Try to find v, the stealer of task, by first using hint
1001 >            ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1002 >            if (v == null || v.currentSteal != task) {
1003 >                for (int j = 0; ; ++j) {      // search array
1004 >                    if (j < n) {
1005 >                        ForkJoinTask<?> vs;
1006 >                        if ((v = ws[j]) != null &&
1007 >                            (vs = v.currentSteal) != null) {
1008 >                            if (joinMe.status < 0 || task.status < 0)
1009 >                                return;       // stale or done
1010 >                            if (vs == task) {
1011 >                                thread.stealHint = j;
1012 >                                break;        // save hint for next time
1013 >                            }
1014 >                        }
1015 >                    }
1016 >                    else
1017 >                        return;               // no stealer
1018 >                }
1019 >            }
1020 >            for (;;) { // Try to help v, using specialized form of deqTask
1021 >                if (joinMe.status < 0)
1022 >                    return;
1023 >                int b = v.base;
1024 >                ForkJoinTask<?>[] q = v.queue;
1025 >                if (b == v.sp || q == null)
1026 >                    break;
1027 >                int i = (q.length - 1) & b;
1028 >                long u = (i << qShift) + qBase;
1029 >                ForkJoinTask<?> t = q[i];
1030 >                int pid = poolIndex;
1031 >                ForkJoinTask<?> ps = currentSteal;
1032 >                if (task.status < 0)
1033 >                    return;                   // stale or done
1034 >                if (t != null && v.base == b++ &&
1035 >                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
1036 >                    if (joinMe.status < 0) {
1037 >                        UNSAFE.putObjectVolatile(q, u, t);
1038 >                        return;               // back out on cancel
1039 >                    }
1040 >                    v.base = b;
1041 >                    v.stealHint = pid;
1042 >                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
1043 >                    t.quietlyExec();
1044 >                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1045 >                }
1046 >            }
1047 >            // Try to descend to find v's stealer
1048 >            ForkJoinTask<?> next = v.currentJoin;
1049 >            if (task.status < 0 || next == null || next == task ||
1050 >                joinMe.status < 0)
1051 >                return;
1052 >            task = next;
1053 >            thread = v;
1054 >        }
1055 >    }
1056 >
1057 >    /**
1058 >     * Returns an estimate of the number of tasks, offset by a
1059 >     * function of number of idle workers.
1060 >     *
1061 >     * This method provides a cheap heuristic guide for task
1062 >     * partitioning when programmers, frameworks, tools, or languages
1063 >     * have little or no idea about task granularity.  In essence by
1064 >     * offering this method, we ask users only about tradeoffs in
1065 >     * overhead vs expected throughput and its variance, rather than
1066 >     * how finely to partition tasks.
1067 >     *
1068 >     * In a steady state strict (tree-structured) computation, each
1069 >     * thread makes available for stealing enough tasks for other
1070 >     * threads to remain active. Inductively, if all threads play by
1071 >     * the same rules, each thread should make available only a
1072 >     * constant number of tasks.
1073 >     *
1074 >     * The minimum useful constant is just 1. But using a value of 1
1075 >     * would require immediate replenishment upon each steal to
1076 >     * maintain enough tasks, which is infeasible.  Further,
1077 >     * partitionings/granularities of offered tasks should minimize
1078 >     * steal rates, which in general means that threads nearer the top
1079 >     * of computation tree should generate more than those nearer the
1080 >     * bottom. In perfect steady state, each thread is at
1081 >     * approximately the same level of computation tree. However,
1082 >     * producing extra tasks amortizes the uncertainty of progress and
1083 >     * diffusion assumptions.
1084 >     *
1085 >     * So, users will want to use values larger, but not much larger
1086 >     * than 1 to both smooth over transient shortages and hedge
1087 >     * against uneven progress; as traded off against the cost of
1088 >     * extra task overhead. We leave the user to pick a threshold
1089 >     * value to compare with the results of this call to guide
1090 >     * decisions, but recommend values such as 3.
1091 >     *
1092 >     * When all threads are active, it is on average OK to estimate
1093 >     * surplus strictly locally. In steady-state, if one thread is
1094 >     * maintaining say 2 surplus tasks, then so are others. So we can
1095 >     * just use estimated queue length (although note that (sp - base)
1096 >     * can be an overestimate because of stealers lagging increments
1097 >     * of base).  However, this strategy alone leads to serious
1098 >     * mis-estimates in some non-steady-state conditions (ramp-up,
1099 >     * ramp-down, other stalls). We can detect many of these by
1100 >     * further considering the number of "idle" threads, that are
1101 >     * known to have zero queued tasks, so compensate by a factor of
1102 >     * (#idle/#active) threads.
1103 >     */
1104 >    final int getEstimatedSurplusTaskCount() {
1105 >        return sp - base - pool.idlePerActive();
1106      }
1107  
1108      /**
1109 <     * Runs tasks until pool isQuiescent
1109 >     * Runs tasks until {@code pool.isQuiescent()}.
1110       */
1111      final void helpQuiescePool() {
1112 +        ForkJoinTask<?> ps = currentSteal; // to restore below
1113          for (;;) {
1114 <            ForkJoinTask<?> t = pollTask();
1115 <            if (t != null)
1114 >            ForkJoinTask<?> t = pollLocalTask();
1115 >            if (t != null || (t = scan()) != null)
1116                  t.quietlyExec();
1117 <            else if (tryInactivate() && pool.isQuiescent())
1118 <                break;
1117 >            else {
1118 >                ForkJoinPool p = pool;
1119 >                int a; // to inline CASes
1120 >                if (active) {
1121 >                    if (!UNSAFE.compareAndSwapInt
1122 >                        (p, poolRunStateOffset, a = p.runState, a - 1))
1123 >                        continue;   // retry later
1124 >                    active = false; // inactivate
1125 >                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
1126 >                }
1127 >                if (p.isQuiescent()) {
1128 >                    active = true; // re-activate
1129 >                    do {} while (!UNSAFE.compareAndSwapInt
1130 >                                 (p, poolRunStateOffset, a = p.runState, a+1));
1131 >                    return;
1132 >                }
1133 >            }
1134 >        }
1135 >    }
1136 >
1137 >    // Unsafe mechanics
1138 >
1139 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1140 >    private static final long spOffset =
1141 >        objectFieldOffset("sp", ForkJoinWorkerThread.class);
1142 >    private static final long runStateOffset =
1143 >        objectFieldOffset("runState", ForkJoinWorkerThread.class);
1144 >    private static final long currentJoinOffset =
1145 >        objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1146 >    private static final long currentStealOffset =
1147 >        objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1148 >    private static final long qBase =
1149 >        UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1150 >    private static final long poolRunStateOffset = // to inline CAS
1151 >        objectFieldOffset("runState", ForkJoinPool.class);
1152 >
1153 >    private static final int qShift;
1154 >
1155 >    static {
1156 >        int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
1157 >        if ((s & (s-1)) != 0)
1158 >            throw new Error("data type scale not a power of two");
1159 >        qShift = 31 - Integer.numberOfLeadingZeros(s);
1160 >    }
1161 >
1162 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1163 >        try {
1164 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1165 >        } catch (NoSuchFieldException e) {
1166 >            // Convert Exception to corresponding Error
1167 >            NoSuchFieldError error = new NoSuchFieldError(field);
1168 >            error.initCause(e);
1169 >            throw error;
1170          }
719        do;while (!tryActivate()); // re-activate on exit
1171      }
1172  
1173 <    // Temporary Unsafe mechanics for preliminary release
1174 <    private static Unsafe getUnsafe() throws Throwable {
1173 >    /**
1174 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1175 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1176 >     * into a jdk.
1177 >     *
1178 >     * @return a sun.misc.Unsafe
1179 >     */
1180 >    private static sun.misc.Unsafe getUnsafe() {
1181          try {
1182 <            return Unsafe.getUnsafe();
1182 >            return sun.misc.Unsafe.getUnsafe();
1183          } catch (SecurityException se) {
1184              try {
1185                  return java.security.AccessController.doPrivileged
1186 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1187 <                        public Unsafe run() throws Exception {
1188 <                            return getUnsafePrivileged();
1186 >                    (new java.security
1187 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1188 >                        public sun.misc.Unsafe run() throws Exception {
1189 >                            java.lang.reflect.Field f = sun.misc
1190 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1191 >                            f.setAccessible(true);
1192 >                            return (sun.misc.Unsafe) f.get(null);
1193                          }});
1194              } catch (java.security.PrivilegedActionException e) {
1195 <                throw e.getCause();
1195 >                throw new RuntimeException("Could not initialize intrinsics",
1196 >                                           e.getCause());
1197              }
1198          }
1199      }
738
739    private static Unsafe getUnsafePrivileged()
740            throws NoSuchFieldException, IllegalAccessException {
741        Field f = Unsafe.class.getDeclaredField("theUnsafe");
742        f.setAccessible(true);
743        return (Unsafe) f.get(null);
744    }
745
746    private static long fieldOffset(String fieldName)
747            throws NoSuchFieldException {
748        return _unsafe.objectFieldOffset
749            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
750    }
751
752    static final Unsafe _unsafe;
753    static final long baseOffset;
754    static final long spOffset;
755    static final long runStateOffset;
756    static final long qBase;
757    static final int qShift;
758    static {
759        try {
760            _unsafe = getUnsafe();
761            baseOffset = fieldOffset("base");
762            spOffset = fieldOffset("sp");
763            runStateOffset = fieldOffset("runState");
764            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
765            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
766            if ((s & (s-1)) != 0)
767                throw new Error("data type scale not a power of two");
768            qShift = 31 - Integer.numberOfLeadingZeros(s);
769        } catch (Throwable e) {
770            throw new RuntimeException("Could not initialize intrinsics", e);
771        }
772    }
1200   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines