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.46 by dl, Sat Sep 4 11:33:53 2010 UTC vs.
Revision 1.67 by jsr166, Wed Jun 8 05:12:25 2011 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  
9 import java.util.concurrent.*;
10
11 import java.util.Random;
9   import java.util.Collection;
10 < import java.util.concurrent.locks.LockSupport;
10 > import java.util.concurrent.RejectedExecutionException;
11  
12   /**
13 < * A thread managed by a {@link ForkJoinPool}.  This class is
14 < * subclassable solely for the sake of adding functionality -- there
15 < * are no overridable methods dealing with scheduling or execution.
16 < * However, you can override initialization and termination methods
17 < * surrounding the main task processing loop.  If you do create such a
18 < * subclass, you will also need to supply a custom {@link
19 < * ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code
20 < * ForkJoinPool}.
13 > * A thread managed by a {@link ForkJoinPool}, which executes
14 > * {@link ForkJoinTask}s.
15 > * This class is subclassable solely for the sake of adding
16 > * functionality -- there are no overridable methods dealing with
17 > * scheduling or execution.  However, you can override initialization
18 > * and termination methods surrounding the main task processing loop.
19 > * If you do create such a subclass, you will also need to supply a
20 > * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
21 > * in a {@code ForkJoinPool}.
22   *
23   * @since 1.7
24   * @author Doug Lea
# Line 55 | Line 53 | public class ForkJoinWorkerThread extend
53       * a footprint as possible even in programs generating huge
54       * numbers of tasks. To accomplish this, we shift the CAS
55       * arbitrating pop vs deq (steal) from being on the indices
56 <     * ("base" and "sp") to the slots themselves (mainly via method
57 <     * "casSlotNull()"). So, both a successful pop and deq mainly
58 <     * entail a CAS of a slot from non-null to null.  Because we rely
59 <     * on CASes of references, we do not need tag bits on base or sp.
60 <     * They are simple ints as used in any circular array-based queue
61 <     * (see for example ArrayDeque).  Updates to the indices must
62 <     * still be ordered in a way that guarantees that sp == base means
63 <     * the queue is empty, but otherwise may err on the side of
64 <     * possibly making the queue appear nonempty when a push, pop, or
65 <     * deq have not fully committed. Note that this means that the deq
66 <     * operation, considered individually, is not wait-free. One thief
67 <     * cannot successfully continue until another in-progress one (or,
68 <     * if previously empty, a push) completes.  However, in the
56 >     * ("queueBase" and "queueTop") to the slots themselves (mainly
57 >     * via method "casSlotNull()"). So, both a successful pop and deq
58 >     * mainly entail a CAS of a slot from non-null to null.  Because
59 >     * we rely on CASes of references, we do not need tag bits on
60 >     * queueBase or queueTop.  They are simple ints as used in any
61 >     * circular array-based queue (see for example ArrayDeque).
62 >     * Updates to the indices must still be ordered in a way that
63 >     * guarantees that queueTop == queueBase means the queue is empty,
64 >     * but 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 probabilistic non-blockingness.
71       * If an attempted steal fails, a thief always chooses a different
72       * random victim target to try next. So, in order for one thief to
73       * progress, it suffices for any in-progress deq or new push on
74 <     * any empty queue to complete. One reason this works well here is
76 <     * that apparently-nonempty often means soon-to-be-stealable,
77 <     * which gives threads a chance to set activation status if
78 <     * necessary before stealing.
74 >     * any empty queue to complete.
75       *
76       * This approach also enables support for "async mode" where local
77       * task processing is in FIFO, not LIFO order; simply by using a
78       * version of deq rather than pop when locallyFifo is true (as set
79       * by the ForkJoinPool).  This allows use in message-passing
80 <     * frameworks in which tasks are never joined.
80 >     * frameworks in which tasks are never joined.  However neither
81 >     * mode considers affinities, loads, cache localities, etc, so
82 >     * rarely provide the best possible performance on a given
83 >     * machine, but portably provide good throughput by averaging over
84 >     * these factors.  (Further, even if we did try to use such
85 >     * information, we do not usually have a basis for exploiting
86 >     * it. For example, some sets of tasks profit from cache
87 >     * affinities, but others are harmed by cache pollution effects.)
88       *
89       * When a worker would otherwise be blocked waiting to join a
90       * task, it first tries a form of linear helping: Each worker
# Line 108 | Line 111 | public class ForkJoinWorkerThread extend
111       * miss links in the chain during long-lived tasks, GC stalls etc
112       * (which is OK since blocking in such cases is usually a good
113       * idea).  (4) We bound the number of attempts to find work (see
114 <     * MAX_HELP_DEPTH) and fall back to suspending the worker and if
115 <     * necessary replacing it with a spare (see
113 <     * ForkJoinPool.awaitJoin).
114 >     * MAX_HELP) and fall back to suspending the worker and if
115 >     * necessary replacing it with another.
116       *
117       * Efficient implementation of these algorithms currently relies
118       * on an uncomfortable amount of "Unsafe" mechanics. To maintain
119 <     * correct orderings, reads and writes of variable base require
120 <     * volatile ordering.  Variable sp does not require volatile
121 <     * writes but still needs store-ordering, which we accomplish by
122 <     * pre-incrementing sp before filling the slot with an ordered
123 <     * store.  (Pre-incrementing also enables backouts used in
124 <     * joinTask.)  Because they are protected by volatile base reads,
125 <     * reads of the queue array and its slots by other threads do not
126 <     * need volatile load semantics, but writes (in push) require
127 <     * store order and CASes (in pop and deq) require (volatile) CAS
128 <     * semantics.  (Michael, Saraswat, and Vechev's algorithm has
129 <     * similar properties, but without support for nulling slots.)
130 <     * Since these combinations aren't supported using ordinary
131 <     * volatiles, the only way to accomplish these efficiently is to
132 <     * use direct Unsafe calls. (Using external AtomicIntegers and
133 <     * AtomicReferenceArrays for the indices and array is
132 <     * significantly slower because of memory locality and indirection
133 <     * effects.)
119 >     * correct orderings, reads and writes of variable queueBase
120 >     * require volatile ordering.  Variable queueTop need not be
121 >     * volatile because non-local reads always follow those of
122 >     * queueBase.  Similarly, because they are protected by volatile
123 >     * queueBase reads, reads of the queue array and its slots by
124 >     * other threads do not need volatile load semantics, but writes
125 >     * (in push) require store order and CASes (in pop and deq)
126 >     * require (volatile) CAS semantics.  (Michael, Saraswat, and
127 >     * Vechev's algorithm has similar properties, but without support
128 >     * for nulling slots.)  Since these combinations aren't supported
129 >     * using ordinary volatiles, the only way to accomplish these
130 >     * efficiently is to use direct Unsafe calls. (Using external
131 >     * AtomicIntegers and AtomicReferenceArrays for the indices and
132 >     * array is significantly slower because of memory locality and
133 >     * indirection effects.)
134       *
135       * Further, performance on most platforms is very sensitive to
136       * placement and sizing of the (resizable) queue array.  Even
# Line 138 | Line 138 | public class ForkJoinWorkerThread extend
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 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.
141 >     * queues are initialized after starting.
142       */
155    private static final Random seedGenerator = new Random();
143  
144      /**
145 <     * 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.
145 >     * Mask for pool indices encoded as shorts
146       */
147 <    private static final int MAX_HELP_DEPTH = 8;
147 >    private static final int  SMASK  = 0xffff;
148  
149      /**
150       * Capacity of work-stealing queue array upon initialization.
# Line 171 | Line 154 | public class ForkJoinWorkerThread extend
154      private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
155  
156      /**
157 <     * Maximum work-stealing queue array size.  Must be less than or
158 <     * equal to 1 << (31 - width of array entry) to ensure lack of
159 <     * index wraparound. The value is set in the static block
160 <     * at the end of this file after obtaining width.
157 >     * Maximum size for queue array. Must be a power of two
158 >     * less than or equal to 1 << (31 - width of array entry) to
159 >     * ensure lack of index wraparound, but is capped at a lower
160 >     * value to help users trap runaway computations.
161 >     */
162 >    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
163 >
164 >    /**
165 >     * The work-stealing queue array. Size must be a power of two.
166 >     * Initialized when started (as opposed to when constructed), to
167 >     * improve memory locality.
168       */
169 <    private static final int MAXIMUM_QUEUE_CAPACITY;
169 >    ForkJoinTask<?>[] queue;
170  
171      /**
172       * The pool this thread works in. Accessed directly by ForkJoinTask.
# Line 184 | Line 174 | public class ForkJoinWorkerThread extend
174      final ForkJoinPool pool;
175  
176      /**
177 <     * The work-stealing queue array. Size must be a power of two.
178 <     * Initialized in onStart, to improve memory locality.
177 >     * Index (mod queue.length) of next queue slot to push to or pop
178 >     * from. It is written only by owner thread, and accessed by other
179 >     * threads only after reading (volatile) queueBase.  Both queueTop
180 >     * and queueBase are allowed to wrap around on overflow, but
181 >     * (queueTop - queueBase) still estimates size.
182       */
183 <    private ForkJoinTask<?>[] queue;
183 >    int queueTop;
184  
185      /**
186       * Index (mod queue.length) of least valid queue slot, which is
187       * always the next position to steal from if nonempty.
188       */
189 <    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, 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 int sp;
189 >    volatile int queueBase;
190  
191      /**
192       * The index of most recent stealer, used as a hint to avoid
# Line 211 | Line 195 | public class ForkJoinWorkerThread extend
195       * of them (usually the most current). Declared non-volatile,
196       * relying on other prevailing sync to keep reasonably current.
197       */
198 <    private int stealHint;
198 >    int stealHint;
199  
200      /**
201 <     * Run state of this worker. In addition to the usual run levels,
202 <     * tracks if this worker is suspended as a spare, and if it was
203 <     * 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.
201 >     * Index of this worker in pool array. Set once by pool before
202 >     * running, and accessed directly by pool to locate this worker in
203 >     * its workers array.
204       */
205 <    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
205 >    final int poolIndex;
206  
207      /**
208 <     * Number of steals. Directly accessed (and reset) by
209 <     * pool.tryAccumulateStealCount when idle.
208 >     * Encoded record for pool task waits. Usages are always
209 >     * surrounded by volatile reads/writes
210       */
211 <    int stealCount;
211 >    int nextWait;
212  
213      /**
214 <     * Seed for random number generator for choosing steal victims.
215 <     * Uses Marsaglia xorshift. Must be initialized as nonzero.
214 >     * Complement of poolIndex, offset by count of entries of task
215 >     * waits. Accessed by ForkJoinPool to manage event waiters.
216       */
217 <    private int seed;
217 >    volatile int eventCount;
218  
219      /**
220 <     * Activity status. When true, this worker is considered active.
221 <     * Accessed directly by pool.  Must be false upon construction.
247 <     */
248 <    boolean active;
249 <
250 <    /**
251 <     * True if use local fifo, not default lifo, for local polling.
252 <     * Shadows value from ForkJoinPool.
220 >     * Seed for random number generator for choosing steal victims.
221 >     * Uses Marsaglia xorshift. Must be initialized as nonzero.
222       */
223 <    private final boolean locallyFifo;
223 >    int seed;
224  
225      /**
226 <     * Index of this worker in pool array. Set once by pool before
227 <     * running, and accessed directly by pool to locate this worker in
259 <     * its workers array.
226 >     * Number of steals. Directly accessed (and reset) by pool when
227 >     * idle.
228       */
229 <    int poolIndex;
229 >    int stealCount;
230  
231      /**
232 <     * The last pool event waited for. Accessed only by pool in
265 <     * callback methods invoked within this thread.
232 >     * True if this worker should or did terminate
233       */
234 <    int lastEventCount;
234 >    volatile boolean terminate;
235  
236      /**
237 <     * Encoded index and event count of next event waiter. Accessed
271 <     * only by ForkJoinPool for managing event waiters.
237 >     * Set to true before LockSupport.park; false on return
238       */
239 <    volatile long nextWaiter;
239 >    volatile boolean parked;
240  
241      /**
242 <     * Number of times this thread suspended as spare. Accessed only
243 <     * by pool.
242 >     * True if use local fifo, not default lifo, for local polling.
243 >     * Shadows value from ForkJoinPool.
244       */
245 <    int spareCount;
245 >    final boolean locallyFifo;
246  
247      /**
248 <     * Encoded index and count of next spare waiter. Accessed only
249 <     * by ForkJoinPool for managing spares.
248 >     * The task most recently stolen from another worker (or
249 >     * submission queue).  All uses are surrounded by enough volatile
250 >     * reads/writes to maintain as non-volatile.
251       */
252 <    volatile int nextSpare;
252 >    ForkJoinTask<?> currentSteal;
253  
254      /**
255       * The task currently being joined, set only when actively trying
256 <     * to help other stealers in helpJoinTask. Written only by this
257 <     * thread, but read by others.
256 >     * to help other stealers in helpJoinTask. All uses are surrounded
257 >     * by enough volatile reads/writes to maintain as non-volatile.
258       */
259 <    private volatile ForkJoinTask<?> currentJoin;
293 <
294 <    /**
295 <     * The task most recently stolen from another worker (or
296 <     * submission queue).  Written only by this thread, but read by
297 <     * others.
298 <     */
299 <    private volatile ForkJoinTask<?> currentSteal;
259 >    ForkJoinTask<?> currentJoin;
260  
261      /**
262       * Creates a ForkJoinWorkerThread operating in the given pool.
# Line 305 | Line 265 | public class ForkJoinWorkerThread extend
265       * @throws NullPointerException if pool is null
266       */
267      protected ForkJoinWorkerThread(ForkJoinPool pool) {
268 +        super(pool.nextWorkerName());
269          this.pool = pool;
270 <        this.locallyFifo = pool.locallyFifo;
271 <        setDaemon(true);
272 <        // To avoid exposing construction details to subclasses,
273 <        // remaining initialization is in start() and onStart()
274 <    }
314 <
315 <    /**
316 <     * Performs additional initialization and starts this thread.
317 <     */
318 <    final void start(int poolIndex, UncaughtExceptionHandler ueh) {
319 <        this.poolIndex = poolIndex;
270 >        int k = pool.registerWorker(this);
271 >        poolIndex = k;
272 >        eventCount = ~k & SMASK; // clear wait count
273 >        locallyFifo = pool.locallyFifo;
274 >        Thread.UncaughtExceptionHandler ueh = pool.ueh;
275          if (ueh != null)
276              setUncaughtExceptionHandler(ueh);
277 <        start();
277 >        setDaemon(true);
278      }
279  
280 <    // Public/protected methods
280 >    // Public methods
281  
282      /**
283       * Returns the pool hosting this thread.
# Line 346 | Line 301 | public class ForkJoinWorkerThread extend
301          return poolIndex;
302      }
303  
304 +    // Randomization
305 +
306 +    /**
307 +     * Computes next value for random victim probes and backoffs.
308 +     * Scans don't require a very high quality generator, but also not
309 +     * a crummy one.  Marsaglia xor-shift is cheap and works well
310 +     * enough.  Note: This is manually inlined in FJP.scan() to avoid
311 +     * writes inside busy loops.
312 +     */
313 +    private int nextSeed() {
314 +        int r = seed;
315 +        r ^= r << 13;
316 +        r ^= r >>> 17;
317 +        r ^= r << 5;
318 +        return seed = r;
319 +    }
320 +
321 +    // Run State management
322 +
323      /**
324       * Initializes internal state after construction but before
325       * processing any tasks. If you override this method, you must
326 <     * invoke @code{super.onStart()} at the beginning of the method.
326 >     * invoke {@code super.onStart()} at the beginning of the method.
327       * Initialization requires care: Most fields must have legal
328       * default values, to ensure that attempted accesses from other
329       * threads work correctly even before this thread starts
330       * processing tasks.
331       */
332      protected void onStart() {
359        int rs = seedGenerator.nextInt();
360        seed = rs == 0? 1 : rs; // seed must be nonzero
361
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
333          queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
334 +        int r = ForkJoinPool.workerSeedGenerator.nextInt();
335 +        seed = (r == 0) ? 1 : r; //  must be nonzero
336      }
337  
338      /**
# Line 377 | Line 345 | public class ForkJoinWorkerThread extend
345       */
346      protected void onTermination(Throwable exception) {
347          try {
348 <            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 <            }
348 >            terminate = true;
349              cancelTasks();
350 <            setTerminated();
389 <            p.workerTerminated(this);
350 >            pool.deregisterWorker(this, exception);
351          } catch (Throwable ex) {        // Shouldn't ever happen
352              if (exception == null)      // but if so, at least rethrown
353                  exception = ex;
# Line 399 | Line 360 | public class ForkJoinWorkerThread extend
360      /**
361       * This method is required to be public, but should never be
362       * called explicitly. It performs the main run loop to execute
363 <     * ForkJoinTasks.
363 >     * {@link ForkJoinTask}s.
364       */
365      public void run() {
366          Throwable exception = null;
367          try {
368              onStart();
369 <            mainLoop();
369 >            pool.work(this);
370          } catch (Throwable ex) {
371              exception = ex;
372          } finally {
# Line 413 | Line 374 | public class ForkJoinWorkerThread extend
374          }
375      }
376  
416    // helpers for run()
417
418    /**
419     * Finds and executes tasks, and checks status while running.
420     */
421    private void mainLoop() {
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     * Tries to steal a task and execute it.
434     *
435     * @return true if ran a task
436     */
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     * If a submission exists, try to activate and run it.
451     *
452     * @return true if ran a task
453     */
454    private boolean tryExecSubmission() {
455        ForkJoinPool p = pool;
456        // This loop is needed in case attempt to activate fails, in
457        // which case we only retry if there still appears to be a
458        // submission.
459        while (p.hasQueuedSubmissions()) {
460            ForkJoinTask<?> t; int a;
461            if (active || // inline p.tryIncrementActiveCount
462                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
463                                                   a = p.runState, a + 1))) {
464                if ((t = p.pollSubmission()) != null) {
465                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
466                    t.quietlyExec();
467                    UNSAFE.putOrderedObject(this, currentStealOffset, null);
468                    if (sp != base)
469                        execLocalTasks();
470                    return true;
471                }
472            }
473        }
474        return false;
475    }
476
477    /**
478     * Runs local tasks until queue is empty or shut down.  Call only
479     * while active.
480     */
481    private void execLocalTasks() {
482        while (runState == 0) {
483            ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
484            if (t != null)
485                t.quietlyExec();
486            else if (sp == base)
487                break;
488        }
489    }
490
377      /*
378       * Intrinsics-based atomic writes for queue slots. These are
379 <     * basically the same as methods in AtomicObjectArray, but
379 >     * basically the same as methods in AtomicReferenceArray, but
380       * specialized for (1) ForkJoinTask elements (2) requirement that
381       * nullness and bounds checks have already been performed by
382       * callers and (3) effective offsets are known not to overflow
383       * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
384       * need corresponding version for reads: plain array reads are OK
385 <     * because they protected by other volatile reads and are
385 >     * because they are protected by other volatile reads and are
386       * confirmed by CASes.
387       *
388 <     * Most uses don't actually call these methods, but instead contain
389 <     * inlined forms that enable more predictable optimization.  We
390 <     * don't define the version of write used in pushTask at all, but
391 <     * instead inline there a store-fenced array slot write.
388 >     * Most uses don't actually call these methods, but instead
389 >     * contain inlined forms that enable more predictable
390 >     * optimization.  We don't define the version of write used in
391 >     * pushTask at all, but instead inline there a store-fenced array
392 >     * slot write.
393 >     *
394 >     * Also in most methods, as a performance (not correctness) issue,
395 >     * we'd like to encourage compilers not to arbitrarily postpone
396 >     * setting queueTop after writing slot.  Currently there is no
397 >     * intrinsic for arranging this, but using Unsafe putOrderedInt
398 >     * may be a preferable strategy on some compilers even though its
399 >     * main effect is a pre-, not post- fence. To simplify possible
400 >     * changes, the option is left in comments next to the associated
401 >     * assignments.
402       */
403  
404      /**
# Line 511 | Line 407 | public class ForkJoinWorkerThread extend
407       */
408      private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
409                                               ForkJoinTask<?> t) {
410 <        return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
410 >        return UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null);
411      }
412  
413      /**
# Line 521 | Line 417 | public class ForkJoinWorkerThread extend
417       */
418      private static final void writeSlot(ForkJoinTask<?>[] q, int i,
419                                          ForkJoinTask<?> t) {
420 <        UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
420 >        UNSAFE.putObjectVolatile(q, (i << ASHIFT) + ABASE, t);
421      }
422  
423      // queue methods
# Line 532 | Line 428 | public class ForkJoinWorkerThread extend
428       * @param t the task. Caller must ensure non-null.
429       */
430      final void pushTask(ForkJoinTask<?> t) {
431 <        ForkJoinTask<?>[] q = queue;
432 <        int mask = q.length - 1; // implicit assert q != null
433 <        int s = sp++;            // ok to increment sp before slot write
434 <        UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
435 <        if ((s -= base) == 0)
436 <            pool.signalWork();   // was empty
437 <        else if (s == mask)
438 <            growQueue();         // is full
431 >        ForkJoinTask<?>[] q; int s, m;
432 >        if ((q = queue) != null) {    // ignore if queue removed
433 >            long u = (((s = queueTop) & (m = q.length - 1)) << ASHIFT) + ABASE;
434 >            UNSAFE.putOrderedObject(q, u, t);
435 >            queueTop = s + 1;         // or use putOrderedInt
436 >            if ((s -= queueBase) <= 2)
437 >                pool.signalWork();
438 >            else if (s == m)
439 >                growQueue();
440 >        }
441 >    }
442 >
443 >    /**
444 >     * Creates or doubles queue array.  Transfers elements by
445 >     * emulating steals (deqs) from old array and placing, oldest
446 >     * first, into new array.
447 >     */
448 >    private void growQueue() {
449 >        ForkJoinTask<?>[] oldQ = queue;
450 >        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
451 >        if (size > MAXIMUM_QUEUE_CAPACITY)
452 >            throw new RejectedExecutionException("Queue capacity exceeded");
453 >        if (size < INITIAL_QUEUE_CAPACITY)
454 >            size = INITIAL_QUEUE_CAPACITY;
455 >        ForkJoinTask<?>[] q = queue = new ForkJoinTask<?>[size];
456 >        int mask = size - 1;
457 >        int top = queueTop;
458 >        int oldMask;
459 >        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
460 >            for (int b = queueBase; b != top; ++b) {
461 >                long u = ((b & oldMask) << ASHIFT) + ABASE;
462 >                Object x = UNSAFE.getObjectVolatile(oldQ, u);
463 >                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
464 >                    UNSAFE.putObjectVolatile
465 >                        (q, ((b & mask) << ASHIFT) + ABASE, x);
466 >            }
467 >        }
468      }
469  
470      /**
# Line 550 | Line 475 | public class ForkJoinWorkerThread extend
475       * @return a task, or null if none or contended
476       */
477      final ForkJoinTask<?> deqTask() {
478 <        ForkJoinTask<?> t;
479 <        ForkJoinTask<?>[] q;
555 <        int b, i;
556 <        if (sp != (b = base) &&
478 >        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
479 >        if (queueTop != (b = queueBase) &&
480              (q = queue) != null && // must read q after b
481 <            (t = q[i = (q.length - 1) & b]) != null && base == b &&
482 <            UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
483 <            base = b + 1;
481 >            (i = (q.length - 1) & b) >= 0 &&
482 >            (t = q[i]) != null && queueBase == b &&
483 >            UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null)) {
484 >            queueBase = b + 1;
485              return t;
486          }
487          return null;
488      }
489  
490      /**
491 <     * Tries to take a task from the base of own queue. Assumes active
492 <     * status.  Called only by this thread.
491 >     * Tries to take a task from the base of own queue.  Called only
492 >     * by this thread.
493       *
494       * @return a task, or null if none
495       */
496      final ForkJoinTask<?> locallyDeqTask() {
497 +        ForkJoinTask<?> t; int m, b, i;
498          ForkJoinTask<?>[] q = queue;
499 <        if (q != null) {
500 <            ForkJoinTask<?> t;
501 <            int b, i;
502 <            while (sp != (b = base)) {
503 <                if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
579 <                    UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
499 >        if (q != null && (m = q.length - 1) >= 0) {
500 >            while (queueTop != (b = queueBase)) {
501 >                if ((t = q[i = m & b]) != null &&
502 >                    queueBase == b &&
503 >                    UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE,
504                                                  t, null)) {
505 <                    base = b + 1;
505 >                    queueBase = b + 1;
506                      return t;
507                  }
508              }
# Line 587 | Line 511 | public class ForkJoinWorkerThread extend
511      }
512  
513      /**
514 <     * Returns a popped task, or null if empty. Assumes active status.
514 >     * Returns a popped task, or null if empty.
515       * Called only by this thread.
516       */
517      private ForkJoinTask<?> popTask() {
518 +        int m;
519          ForkJoinTask<?>[] q = queue;
520 <        if (q != null) {
521 <            int s;
522 <            while ((s = sp) != base) {
523 <                int i = (q.length - 1) & --s;
599 <                long u = (i << qShift) + qBase; // raw offset
520 >        if (q != null && (m = q.length - 1) >= 0) {
521 >            for (int s; (s = queueTop) != queueBase;) {
522 >                int i = m & --s;
523 >                long u = (i << ASHIFT) + ABASE; // raw offset
524                  ForkJoinTask<?> t = q[i];
525                  if (t == null)   // lost to stealer
526                      break;
527                  if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
528 <                    sp = s; // putOrderedInt may encourage more timely write
605 <                    // UNSAFE.putOrderedInt(this, spOffset, s);
528 >                    queueTop = s; // or putOrderedInt
529                      return t;
530                  }
531              }
# Line 612 | Line 535 | public class ForkJoinWorkerThread extend
535  
536      /**
537       * Specialized version of popTask to pop only if topmost element
538 <     * is the given task. Called only by this thread while active.
538 >     * is the given task. Called only by this thread.
539       *
540       * @param t the task. Caller must ensure non-null.
541       */
542      final boolean unpushTask(ForkJoinTask<?> t) {
543 +        ForkJoinTask<?>[] q;
544          int s;
545 <        ForkJoinTask<?>[] q = queue;
622 <        if ((s = sp) != base && q != null &&
545 >        if ((q = queue) != null && (s = queueTop) != queueBase &&
546              UNSAFE.compareAndSwapObject
547 <            (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
548 <            sp = s; // putOrderedInt may encourage more timely write
626 <            // UNSAFE.putOrderedInt(this, spOffset, s);
547 >            (q, (((q.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
548 >            queueTop = s; // or putOrderedInt
549              return true;
550          }
551          return false;
# Line 633 | Line 555 | public class ForkJoinWorkerThread extend
555       * Returns next task, or null if empty or contended.
556       */
557      final ForkJoinTask<?> peekTask() {
558 +        int m;
559          ForkJoinTask<?>[] q = queue;
560 <        if (q == null)
560 >        if (q == null || (m = q.length - 1) < 0)
561              return null;
562 <        int mask = q.length - 1;
563 <        int i = locallyFifo ? base : (sp - 1);
641 <        return q[i & mask];
642 <    }
643 <
644 <    /**
645 <     * Doubles queue array size. Transfers elements by emulating
646 <     * steals (deqs) from old array and placing, oldest first, into
647 <     * new array.
648 <     */
649 <    private void growQueue() {
650 <        ForkJoinTask<?>[] oldQ = queue;
651 <        int oldSize = oldQ.length;
652 <        int newSize = oldSize << 1;
653 <        if (newSize > MAXIMUM_QUEUE_CAPACITY)
654 <            throw new RejectedExecutionException("Queue capacity exceeded");
655 <        ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
656 <
657 <        int b = base;
658 <        int bf = b + oldSize;
659 <        int oldMask = oldSize - 1;
660 <        int newMask = newSize - 1;
661 <        do {
662 <            int oldIndex = b & oldMask;
663 <            ForkJoinTask<?> t = oldQ[oldIndex];
664 <            if (t != null && !casSlotNull(oldQ, oldIndex, t))
665 <                t = null;
666 <            writeSlot(newQ, b & newMask, t);
667 <        } while (++b != bf);
668 <        pool.signalWork();
669 <    }
670 <
671 <    /**
672 <     * Computes next value for random victim probe in scan().  Scans
673 <     * don't require a very high quality generator, but also not a
674 <     * crummy one.  Marsaglia xor-shift is cheap and works well enough.
675 <     * Note: This is manually inlined in scan().
676 <     */
677 <    private static final int xorShift(int r) {
678 <        r ^= r << 13;
679 <        r ^= r >>> 17;
680 <        return r ^ (r << 5);
681 <    }
682 <
683 <    /**
684 <     * Tries to steal a task from another worker. Starts at a random
685 <     * index of workers array, and probes workers until finding one
686 <     * with non-empty queue or finding that all are empty.  It
687 <     * randomly selects the first n probes. If these are empty, it
688 <     * resorts to a circular sweep, which is necessary to accurately
689 <     * set active status. (The circular sweep uses steps of
690 <     * approximately half the array size plus 1, to avoid bias
691 <     * stemming from leftmost packing of the array in ForkJoinPool.)
692 <     *
693 <     * This method must be both fast and quiet -- usually avoiding
694 <     * memory accesses that could disrupt cache sharing etc other than
695 <     * those needed to check for and take tasks (or to activate if not
696 <     * already active). This accounts for, among other things,
697 <     * updating random seed in place without storing it until exit.
698 <     *
699 <     * @return a task, or null if none found
700 <     */
701 <    private ForkJoinTask<?> scan() {
702 <        ForkJoinPool p = pool;
703 <        ForkJoinWorkerThread[] ws;        // worker array
704 <        int n;                            // upper bound of #workers
705 <        if ((ws = p.workers) != null && (n = ws.length) > 1) {
706 <            boolean canSteal = active;    // shadow active status
707 <            int r = seed;                 // extract seed once
708 <            int mask = n - 1;
709 <            int j = -n;                   // loop counter
710 <            int k = r;                    // worker index, random if j < 0
711 <            for (;;) {
712 <                ForkJoinWorkerThread v = ws[k & mask];
713 <                r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
714 <                ForkJoinTask<?>[] q; ForkJoinTask<?> t; int b, a;
715 <                if (v != null && (b = v.base) != v.sp &&
716 <                    (q = v.queue) != null) {
717 <                    int i = (q.length - 1) & b;
718 <                    long u = (i << qShift) + qBase; // raw offset
719 <                    int pid = poolIndex;
720 <                    if ((t = q[i]) != null) {
721 <                        if (!canSteal &&  // inline p.tryIncrementActiveCount
722 <                            UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
723 <                                                     a = p.runState, a + 1))
724 <                            canSteal = active = true;
725 <                        if (canSteal && v.base == b++ &&
726 <                            UNSAFE.compareAndSwapObject(q, u, t, null)) {
727 <                            v.base = b;
728 <                            v.stealHint = pid;
729 <                            UNSAFE.putOrderedObject(this,
730 <                                                    currentStealOffset, t);
731 <                            seed = r;
732 <                            ++stealCount;
733 <                            return t;
734 <                        }
735 <                    }
736 <                    j = -n;
737 <                    k = r;                // restart on contention
738 <                }
739 <                else if (++j <= 0)
740 <                    k = r;
741 <                else if (j <= n)
742 <                    k += (n >>> 1) | 1;
743 <                else
744 <                    break;
745 <            }
746 <        }
747 <        return null;
562 >        int i = locallyFifo ? queueBase : (queueTop - 1);
563 >        return q[i & m];
564      }
565  
566 <    // Run State management
751 <
752 <    // status check methods used mainly by ForkJoinPool
753 <    final boolean isRunning()     { return runState == 0; }
754 <    final boolean isTerminating() { return (runState & TERMINATING) != 0; }
755 <    final boolean isTerminated()  { return (runState & TERMINATED) != 0; }
756 <    final boolean isSuspended()   { return (runState & SUSPENDED) != 0; }
757 <    final boolean isTrimmed()     { return (runState & TRIMMED) != 0; }
566 >    // Support methods for ForkJoinPool
567  
568      /**
569 <     * Sets state to TERMINATING. Does NOT unpark or interrupt
761 <     * to wake up if currently blocked. Callers must do so if desired.
569 >     * Runs the given task, plus any local tasks until queue is empty
570       */
571 <    final void shutdown() {
571 >    final void execTask(ForkJoinTask<?> t) {
572 >        currentSteal = t;
573          for (;;) {
574 <            int s = runState;
575 <            if ((s & (TERMINATING|TERMINATED)) != 0)
576 <                break;
768 <            if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
769 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
770 <                                             (s & ~SUSPENDED) |
771 <                                             (TRIMMED|TERMINATING)))
772 <                    break;
773 <            }
774 <            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
775 <                                              s | TERMINATING))
776 <                break;
777 <        }
778 <    }
779 <
780 <    /**
781 <     * Sets state to TERMINATED. Called only by onTermination().
782 <     */
783 <    private void setTerminated() {
784 <        int s;
785 <        do {} while (!UNSAFE.compareAndSwapInt(this, runStateOffset,
786 <                                               s = runState,
787 <                                               s | (TERMINATING|TERMINATED)));
788 <    }
789 <
790 <    /**
791 <     * If suspended, tries to set status to unsuspended.
792 <     * Does NOT wake up if blocked.
793 <     *
794 <     * @return true if successful
795 <     */
796 <    final boolean tryUnsuspend() {
797 <        int s;
798 <        while (((s = runState) & SUSPENDED) != 0) {
799 <            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
800 <                                         s & ~SUSPENDED))
801 <                return true;
802 <        }
803 <        return false;
804 <    }
805 <
806 <    /**
807 <     * Sets suspended status and blocks as spare until resumed
808 <     * or shutdown.
809 <     */
810 <    final void suspendAsSpare() {
811 <        for (;;) {                  // set suspended unless terminating
812 <            int s = runState;
813 <            if ((s & TERMINATING) != 0) { // must kill
814 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
815 <                                             s | (TRIMMED | TERMINATING)))
816 <                    return;
817 <            }
818 <            else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
819 <                                              s | SUSPENDED))
574 >            if (t != null)
575 >                t.doExec();
576 >            if (queueTop == queueBase)
577                  break;
578 +            t = locallyFifo ? locallyDeqTask() : popTask();
579          }
580 <        ForkJoinPool p = pool;
581 <        p.pushSpare(this);
824 <        while ((runState & SUSPENDED) != 0) {
825 <            if (p.tryAccumulateStealCount(this)) {
826 <                interrupted();          // clear/ignore interrupts
827 <                if ((runState & SUSPENDED) == 0)
828 <                    break;
829 <                LockSupport.park(this);
830 <            }
831 <        }
832 <    }
833 <
834 <    // Misc support methods for ForkJoinPool
835 <
836 <    /**
837 <     * Returns an estimate of the number of tasks in the queue.  Also
838 <     * used by ForkJoinTask.
839 <     */
840 <    final int getQueueSize() {
841 <        int n; // external calls must read base first
842 <        return (n = -base + sp) <= 0 ? 0 : n;
580 >        ++stealCount;
581 >        currentSteal = null;
582      }
583  
584      /**
# Line 848 | Line 587 | public class ForkJoinWorkerThread extend
587       */
588      final void cancelTasks() {
589          ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
590 <        if (cj != null) {
852 <            currentJoin = null;
590 >        if (cj != null && cj.status >= 0)
591              cj.cancelIgnoringExceptions();
854            try {
855                this.interrupt(); // awaken wait
856            } catch (SecurityException ignore) {
857            }
858        }
592          ForkJoinTask<?> cs = currentSteal;
593 <        if (cs != null) {
861 <            currentSteal = null;
593 >        if (cs != null && cs.status >= 0)
594              cs.cancelIgnoringExceptions();
595 <        }
864 <        while (base != sp) {
595 >        while (queueBase != queueTop) {
596              ForkJoinTask<?> t = deqTask();
597              if (t != null)
598                  t.cancelIgnoringExceptions();
# Line 875 | Line 606 | public class ForkJoinWorkerThread extend
606       */
607      final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
608          int n = 0;
609 <        while (base != sp) {
609 >        while (queueBase != queueTop) {
610              ForkJoinTask<?> t = deqTask();
611              if (t != null) {
612                  c.add(t);
# Line 888 | Line 619 | public class ForkJoinWorkerThread extend
619      // Support methods for ForkJoinTask
620  
621      /**
622 +     * Returns an estimate of the number of tasks in the queue.
623 +     */
624 +    final int getQueueSize() {
625 +        return queueTop - queueBase;
626 +    }
627 +
628 +    /**
629       * Gets and removes a local task.
630       *
631       * @return a task, if available
632       */
633      final ForkJoinTask<?> pollLocalTask() {
634 <        ForkJoinPool p = pool;
897 <        while (sp != base) {
898 <            int a; // inline p.tryIncrementActiveCount
899 <            if (active ||
900 <                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
901 <                                                   a = p.runState, a + 1)))
902 <                return locallyFifo ? locallyDeqTask() : popTask();
903 <        }
904 <        return null;
634 >        return locallyFifo ? locallyDeqTask() : popTask();
635      }
636  
637      /**
# Line 910 | Line 640 | public class ForkJoinWorkerThread extend
640       * @return a task, if available
641       */
642      final ForkJoinTask<?> pollTask() {
643 +        ForkJoinWorkerThread[] ws;
644          ForkJoinTask<?> t = pollLocalTask();
645 <        if (t == null) {
646 <            t = scan();
647 <            // cannot retain/track/help steal
648 <            UNSAFE.putOrderedObject(this, currentStealOffset, null);
645 >        if (t != null || (ws = pool.workers) == null)
646 >            return t;
647 >        int n = ws.length; // cheap version of FJP.scan
648 >        int steps = n << 1;
649 >        int r = nextSeed();
650 >        int i = 0;
651 >        while (i < steps) {
652 >            ForkJoinWorkerThread w = ws[(i++ + r) & (n - 1)];
653 >            if (w != null && w.queueBase != w.queueTop && w.queue != null) {
654 >                if ((t = w.deqTask()) != null)
655 >                    return t;
656 >                i = 0;
657 >            }
658          }
659 <        return t;
659 >        return null;
660      }
661  
662      /**
663 <     * Possibly runs some tasks and/or blocks, until task is done.
663 >     * The maximum stolen->joining link depth allowed in helpJoinTask,
664 >     * as well as the maximum number of retries (allowing on average
665 >     * one staleness retry per level) per attempt to instead try
666 >     * compensation.  Depths for legitimate chains are unbounded, but
667 >     * we use a fixed constant to avoid (otherwise unchecked) cycles
668 >     * and bound staleness of traversal parameters at the expense of
669 >     * sometimes blocking when we could be helping.
670 >     */
671 >    private static final int MAX_HELP = 16;
672 >
673 >    /**
674 >     * Possibly runs some tasks and/or blocks, until joinMe is done.
675       *
676       * @param joinMe the task to join
677 +     * @return completion status on exit
678       */
679 <    final void joinTask(ForkJoinTask<?> joinMe) {
928 <        // currentJoin only written by this thread; only need ordered store
679 >    final int joinTask(ForkJoinTask<?> joinMe) {
680          ForkJoinTask<?> prevJoin = currentJoin;
681 <        UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
682 <        if (sp != base)
683 <            localHelpJoinTask(joinMe);
684 <        if (joinMe.status >= 0)
685 <            pool.awaitJoin(joinMe, this);
686 <        UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
681 >        currentJoin = joinMe;
682 >        for (int s, retries = MAX_HELP;;) {
683 >            if ((s = joinMe.status) < 0) {
684 >                currentJoin = prevJoin;
685 >                return s;
686 >            }
687 >            if (retries > 0) {
688 >                if (queueTop != queueBase) {
689 >                    if (!localHelpJoinTask(joinMe))
690 >                        retries = 0;           // cannot help
691 >                }
692 >                else if (retries == MAX_HELP >>> 1) {
693 >                    --retries;                 // check uncommon case
694 >                    if (tryDeqAndExec(joinMe) >= 0)
695 >                        Thread.yield();        // for politeness
696 >                }
697 >                else
698 >                    retries = helpJoinTask(joinMe) ? MAX_HELP : retries - 1;
699 >            }
700 >            else {
701 >                retries = MAX_HELP;           // restart if not done
702 >                pool.tryAwaitJoin(joinMe);
703 >            }
704 >        }
705      }
706  
707      /**
708 <     * Run tasks in local queue until given task is done.
708 >     * If present, pops and executes the given task, or any other
709 >     * cancelled task
710       *
711 <     * @param joinMe the task to join
711 >     * @return false if any other non-cancelled task exists in local queue
712       */
713 <    private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
714 <        int s;
715 <        ForkJoinTask<?>[] q;
716 <        while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
717 <            int i = (q.length - 1) & --s;
718 <            long u = (i << qShift) + qBase; // raw offset
719 <            ForkJoinTask<?> t = q[i];
720 <            if (t == null)  // lost to a stealer
721 <                break;
722 <            if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
723 <                /*
954 <                 * This recheck (and similarly in helpJoinTask)
955 <                 * handles cases where joinMe is independently
956 <                 * cancelled or forced even though there is other work
957 <                 * available. Back out of the pop by putting t back
958 <                 * into slot before we commit by writing sp.
959 <                 */
960 <                if (joinMe.status < 0) {
961 <                    UNSAFE.putObjectVolatile(q, u, t);
962 <                    break;
963 <                }
964 <                sp = s;
965 <                // UNSAFE.putOrderedInt(this, spOffset, s);
966 <                t.quietlyExec();
713 >    private boolean localHelpJoinTask(ForkJoinTask<?> joinMe) {
714 >        int s, i; ForkJoinTask<?>[] q; ForkJoinTask<?> t;
715 >        if ((s = queueTop) != queueBase && (q = queue) != null &&
716 >            (i = (q.length - 1) & --s) >= 0 &&
717 >            (t = q[i]) != null) {
718 >            if (t != joinMe && t.status >= 0)
719 >                return false;
720 >            if (UNSAFE.compareAndSwapObject
721 >                (q, (i << ASHIFT) + ABASE, t, null)) {
722 >                queueTop = s;           // or putOrderedInt
723 >                t.doExec();
724              }
725          }
726 +        return true;
727      }
728  
729      /**
730 <     * Unless terminating, tries to locate and help perform tasks for
731 <     * a stealer of the given task, or in turn one of its stealers.
732 <     * Traces currentSteal->currentJoin links looking for a thread
733 <     * working on a descendant of the given task and with a non-empty
734 <     * queue to steal back and execute tasks from.
735 <     *
736 <     * The implementation is very branchy to cope with potential
737 <     * inconsistencies or loops encountering chains that are stale,
738 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
981 <     * of these cases are dealt with by just returning back to the
982 <     * caller, who is expected to retry if other join mechanisms also
983 <     * don't work out.
730 >     * Tries to locate and execute tasks for a stealer of the given
731 >     * task, or in turn one of its stealers, Traces
732 >     * currentSteal->currentJoin links looking for a thread working on
733 >     * a descendant of the given task and with a non-empty queue to
734 >     * steal back and execute tasks from.  The implementation is very
735 >     * branchy to cope with potential inconsistencies or loops
736 >     * encountering chains that are stale, unknown, or of length
737 >     * greater than MAX_HELP links.  All of these cases are dealt with
738 >     * by just retrying by caller.
739       *
740       * @param joinMe the task to join
741 +     * @param canSteal true if local queue is empty
742 +     * @return true if ran a task
743       */
744 <    final void helpJoinTask(ForkJoinTask<?> joinMe) {
745 <        ForkJoinWorkerThread[] ws;
746 <        int n;
747 <        if (joinMe.status < 0)                // already done
748 <            return;
749 <        if ((runState & TERMINATING) != 0) {  // cancel if shutting down
750 <            joinMe.cancelIgnoringExceptions();
751 <            return;
752 <        }
753 <        if ((ws = pool.workers) == null || (n = ws.length) <= 1)
754 <            return;                           // need at least 2 workers
755 <
756 <        ForkJoinTask<?> task = joinMe;        // base of chain
757 <        ForkJoinWorkerThread thread = this;   // thread with stolen task
758 <        for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1002 <            // Try to find v, the stealer of task, by first using hint
1003 <            ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1004 <            if (v == null || v.currentSteal != task) {
1005 <                for (int j = 0; ; ++j) {      // search array
1006 <                    if (j < n) {
1007 <                        ForkJoinTask<?> vs;
1008 <                        if ((v = ws[j]) != null &&
1009 <                            (vs = v.currentSteal) != null) {
1010 <                            if (joinMe.status < 0 || task.status < 0)
1011 <                                return;       // stale or done
1012 <                            if (vs == task) {
1013 <                                thread.stealHint = j;
1014 <                                break;        // save hint for next time
1015 <                            }
744 >    private boolean helpJoinTask(ForkJoinTask<?> joinMe) {
745 >        boolean helped = false;
746 >        int m = pool.scanGuard & SMASK;
747 >        ForkJoinWorkerThread[] ws = pool.workers;
748 >        if (ws != null && ws.length > m && joinMe.status >= 0) {
749 >            int levels = MAX_HELP;              // remaining chain length
750 >            ForkJoinTask<?> task = joinMe;      // base of chain
751 >            outer:for (ForkJoinWorkerThread thread = this;;) {
752 >                // Try to find v, the stealer of task, by first using hint
753 >                ForkJoinWorkerThread v = ws[thread.stealHint & m];
754 >                if (v == null || v.currentSteal != task) {
755 >                    for (int j = 0; ;) {        // search array
756 >                        if ((v = ws[j]) != null && v.currentSteal == task) {
757 >                            thread.stealHint = j;
758 >                            break;              // save hint for next time
759                          }
760 +                        if (++j > m)
761 +                            break outer;        // can't find stealer
762 +                    }
763 +                }
764 +                // Try to help v, using specialized form of deqTask
765 +                for (;;) {
766 +                    ForkJoinTask<?>[] q; int b, i;
767 +                    if (joinMe.status < 0)
768 +                        break outer;
769 +                    if ((b = v.queueBase) == v.queueTop ||
770 +                        (q = v.queue) == null ||
771 +                        (i = (q.length-1) & b) < 0)
772 +                        break;                  // empty
773 +                    long u = (i << ASHIFT) + ABASE;
774 +                    ForkJoinTask<?> t = q[i];
775 +                    if (task.status < 0)
776 +                        break outer;            // stale
777 +                    if (t != null && v.queueBase == b &&
778 +                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
779 +                        v.queueBase = b + 1;
780 +                        v.stealHint = poolIndex;
781 +                        ForkJoinTask<?> ps = currentSteal;
782 +                        currentSteal = t;
783 +                        t.doExec();
784 +                        currentSteal = ps;
785 +                        helped = true;
786                      }
1018                    else
1019                        return;               // no stealer
787                  }
788 +                // Try to descend to find v's stealer
789 +                ForkJoinTask<?> next = v.currentJoin;
790 +                if (--levels > 0 && task.status >= 0 &&
791 +                    next != null && next != task) {
792 +                    task = next;
793 +                    thread = v;
794 +                }
795 +                else
796 +                    break;  // max levels, stale, dead-end, or cyclic
797              }
798 <            for (;;) { // Try to help v, using specialized form of deqTask
799 <                if (joinMe.status < 0)
800 <                    return;
801 <                int b = v.base;
802 <                ForkJoinTask<?>[] q = v.queue;
803 <                if (b == v.sp || q == null)
804 <                    break;
805 <                int i = (q.length - 1) & b;
806 <                long u = (i << qShift) + qBase;
807 <                ForkJoinTask<?> t = q[i];
808 <                int pid = poolIndex;
809 <                ForkJoinTask<?> ps = currentSteal;
810 <                if (task.status < 0)
811 <                    return;                   // stale or done
812 <                if (t != null && v.base == b++ &&
813 <                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
814 <                    if (joinMe.status < 0) {
815 <                        UNSAFE.putObjectVolatile(q, u, t);
816 <                        return;               // back out on cancel
798 >        }
799 >        return helped;
800 >    }
801 >
802 >    /**
803 >     * Performs an uncommon case for joinTask: If task t is at base of
804 >     * some workers queue, steals and executes it.
805 >     *
806 >     * @param t the task
807 >     * @return t's status
808 >     */
809 >    private int tryDeqAndExec(ForkJoinTask<?> t) {
810 >        int m = pool.scanGuard & SMASK;
811 >        ForkJoinWorkerThread[] ws = pool.workers;
812 >        if (ws != null && ws.length > m && t.status >= 0) {
813 >            for (int j = 0; j <= m; ++j) {
814 >                ForkJoinTask<?>[] q; int b, i;
815 >                ForkJoinWorkerThread v = ws[j];
816 >                if (v != null &&
817 >                    (b = v.queueBase) != v.queueTop &&
818 >                    (q = v.queue) != null &&
819 >                    (i = (q.length - 1) & b) >= 0 &&
820 >                    q[i] ==  t) {
821 >                    long u = (i << ASHIFT) + ABASE;
822 >                    if (v.queueBase == b &&
823 >                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
824 >                        v.queueBase = b + 1;
825 >                        v.stealHint = poolIndex;
826 >                        ForkJoinTask<?> ps = currentSteal;
827 >                        currentSteal = t;
828 >                        t.doExec();
829 >                        currentSteal = ps;
830                      }
831 <                    v.base = b;
1043 <                    v.stealHint = pid;
1044 <                    UNSAFE.putOrderedObject(this, currentStealOffset, t);
1045 <                    t.quietlyExec();
1046 <                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
831 >                    break;
832                  }
833              }
1049            // Try to descend to find v's stealer
1050            ForkJoinTask<?> next = v.currentJoin;
1051            if (task.status < 0 || next == null || next == task ||
1052                joinMe.status < 0)
1053                return;
1054            task = next;
1055            thread = v;
834          }
835 +        return t.status;
836      }
837  
838      /**
839 <     * Implements ForJoinTask.getSurplusQueuedTaskCount().
840 <     * Returns an estimate of the number of tasks, offset by a
841 <     * function of number of idle workers.
839 >     * Implements ForkJoinTask.getSurplusQueuedTaskCount().  Returns
840 >     * an estimate of the number of tasks, offset by a function of
841 >     * number of idle workers.
842       *
843       * This method provides a cheap heuristic guide for task
844       * partitioning when programmers, frameworks, tools, or languages
# Line 1095 | Line 874 | public class ForkJoinWorkerThread extend
874       * When all threads are active, it is on average OK to estimate
875       * surplus strictly locally. In steady-state, if one thread is
876       * maintaining say 2 surplus tasks, then so are others. So we can
877 <     * just use estimated queue length (although note that (sp - base)
878 <     * can be an overestimate because of stealers lagging increments
879 <     * of base).  However, this strategy alone leads to serious
880 <     * mis-estimates in some non-steady-state conditions (ramp-up,
881 <     * ramp-down, other stalls). We can detect many of these by
882 <     * further considering the number of "idle" threads, that are
877 >     * just use estimated queue length (although note that (queueTop -
878 >     * queueBase) can be an overestimate because of stealers lagging
879 >     * increments of queueBase).  However, this strategy alone leads
880 >     * to serious mis-estimates in some non-steady-state conditions
881 >     * (ramp-up, ramp-down, other stalls). We can detect many of these
882 >     * by further considering the number of "idle" threads, that are
883       * known to have zero queued tasks, so compensate by a factor of
884       * (#idle/#active) threads.
885       */
886      final int getEstimatedSurplusTaskCount() {
887 <        return sp - base - pool.idlePerActive();
887 >        return queueTop - queueBase - pool.idlePerActive();
888      }
889  
890      /**
891 <     * Runs tasks until {@code pool.isQuiescent()}.
891 >     * Runs tasks until {@code pool.isQuiescent()}. We piggyback on
892 >     * pool's active count ctl maintenance, but rather than blocking
893 >     * when tasks cannot be found, we rescan until all others cannot
894 >     * find tasks either. The bracketing by pool quiescerCounts
895 >     * updates suppresses pool auto-shutdown mechanics that could
896 >     * otherwise prematurely terminate the pool because all threads
897 >     * appear to be inactive.
898       */
899      final void helpQuiescePool() {
900 +        boolean active = true;
901          ForkJoinTask<?> ps = currentSteal; // to restore below
902 +        ForkJoinPool p = pool;
903 +        p.addQuiescerCount(1);
904          for (;;) {
905 <            ForkJoinTask<?> t = pollLocalTask();
906 <            if (t != null || (t = scan()) != null)
907 <                t.quietlyExec();
905 >            ForkJoinWorkerThread[] ws = p.workers;
906 >            ForkJoinWorkerThread v = null;
907 >            int n;
908 >            if (queueTop != queueBase)
909 >                v = this;
910 >            else if (ws != null && (n = ws.length) > 1) {
911 >                ForkJoinWorkerThread w;
912 >                int r = nextSeed(); // cheap version of FJP.scan
913 >                int steps = n << 1;
914 >                for (int i = 0; i < steps; ++i) {
915 >                    if ((w = ws[(i + r) & (n - 1)]) != null &&
916 >                        w.queueBase != w.queueTop) {
917 >                        v = w;
918 >                        break;
919 >                    }
920 >                }
921 >            }
922 >            if (v != null) {
923 >                ForkJoinTask<?> t;
924 >                if (!active) {
925 >                    active = true;
926 >                    p.addActiveCount(1);
927 >                }
928 >                if ((t = (v != this) ? v.deqTask() :
929 >                     locallyFifo ? locallyDeqTask() : popTask()) != null) {
930 >                    currentSteal = t;
931 >                    t.doExec();
932 >                    currentSteal = ps;
933 >                }
934 >            }
935              else {
1121                ForkJoinPool p = pool;
1122                int a; // to inline CASes
936                  if (active) {
937 <                    if (!UNSAFE.compareAndSwapInt
938 <                        (p, poolRunStateOffset, a = p.runState, a - 1))
1126 <                        continue;   // retry later
1127 <                    active = false; // inactivate
1128 <                    UNSAFE.putOrderedObject(this, currentStealOffset, ps);
937 >                    active = false;
938 >                    p.addActiveCount(-1);
939                  }
940                  if (p.isQuiescent()) {
941 <                    active = true; // re-activate
942 <                    do {} while (!UNSAFE.compareAndSwapInt
943 <                                 (p, poolRunStateOffset, a = p.runState, a+1));
1134 <                    return;
941 >                    p.addActiveCount(1);
942 >                    p.addQuiescerCount(-1);
943 >                    break;
944                  }
945              }
946          }
947      }
948  
949      // Unsafe mechanics
950 <
951 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
952 <    private static final long spOffset =
1144 <        objectFieldOffset("sp", ForkJoinWorkerThread.class);
1145 <    private static final long runStateOffset =
1146 <        objectFieldOffset("runState", ForkJoinWorkerThread.class);
1147 <    private static final long currentJoinOffset =
1148 <        objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1149 <    private static final long currentStealOffset =
1150 <        objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1151 <    private static final long qBase =
1152 <        UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1153 <    private static final long poolRunStateOffset = // to inline CAS
1154 <        objectFieldOffset("runState", ForkJoinPool.class);
1155 <
1156 <    private static final int qShift;
950 >    private static final sun.misc.Unsafe UNSAFE;
951 >    private static final long ABASE;
952 >    private static final int ASHIFT;
953  
954      static {
955 <        int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
1160 <        if ((s & (s-1)) != 0)
1161 <            throw new Error("data type scale not a power of two");
1162 <        qShift = 31 - Integer.numberOfLeadingZeros(s);
1163 <        MAXIMUM_QUEUE_CAPACITY = 1 << (31 - qShift);
1164 <    }
1165 <
1166 <    private static long objectFieldOffset(String field, Class<?> klazz) {
955 >        int s;
956          try {
957 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
958 <        } catch (NoSuchFieldException e) {
959 <            // Convert Exception to corresponding Error
960 <            NoSuchFieldError error = new NoSuchFieldError(field);
961 <            error.initCause(e);
962 <            throw error;
957 >            UNSAFE = getUnsafe();
958 >            Class<?> a = ForkJoinTask[].class;
959 >            ABASE = UNSAFE.arrayBaseOffset(a);
960 >            s = UNSAFE.arrayIndexScale(a);
961 >        } catch (Exception e) {
962 >            throw new Error(e);
963          }
964 +        if ((s & (s-1)) != 0)
965 +            throw new Error("data type scale not a power of two");
966 +        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
967      }
968  
969      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines