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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines