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.4 by dl, Wed Jan 7 20:51:36 2009 UTC vs.
Revision 1.28 by dl, Mon Aug 3 13:40:07 2009 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.Collection;
12  
13   /**
14   * A thread managed by a {@link ForkJoinPool}.  This class is
15   * subclassable solely for the sake of adding functionality -- there
16 < * are no overridable methods dealing with scheduling or
17 < * execution. However, you can override initialization and termination
18 < * cleanup methods surrounding the main task processing loop.  If you
19 < * do create such a subclass, you will also need to supply a custom
20 < * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
21 < *
22 < * <p>This class also provides methods for generating per-thread
23 < * random numbers, with the same properties as {@link
24 < * java.util.Random} but with each generator isolated from those of
27 < * other threads.
16 > * are no overridable methods dealing with scheduling or execution.
17 > * However, you can override initialization and termination methods
18 > * surrounding the main task processing loop.  If you do create such a
19 > * subclass, you will also need to supply a custom {@link
20 > * ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code
21 > * ForkJoinPool}.
22 > *
23 > * @since 1.7
24 > * @author Doug Lea
25   */
26   public class ForkJoinWorkerThread extends Thread {
27      /*
# Line 48 | Line 45 | public class ForkJoinWorkerThread extend
45       * of tasks. To accomplish this, we shift the CAS arbitrating pop
46       * vs deq (steal) from being on the indices ("base" and "sp") to
47       * the slots themselves (mainly via method "casSlotNull()"). So,
48 <     * both a successful pop and deq mainly entail CAS'ing a nonnull
48 >     * both a successful pop and deq mainly entail CAS'ing a non-null
49       * slot to null.  Because we rely on CASes of references, we do
50       * not need tag bits on base or sp.  They are simple ints as used
51       * in any circular array-based queue (see for example ArrayDeque).
# Line 60 | Line 57 | public class ForkJoinWorkerThread extend
57       * considered individually, is not wait-free. One thief cannot
58       * successfully continue until another in-progress one (or, if
59       * previously empty, a push) completes.  However, in the
60 <     * aggregate, we ensure at least probablistic non-blockingness. If
61 <     * an attempted steal fails, a thief always chooses a different
62 <     * random victim target to try next. So, in order for one thief to
63 <     * progress, it suffices for any in-progress deq or new push on
64 <     * any empty queue to complete. One reason this works well here is
65 <     * that apparently-nonempty often means soon-to-be-stealable,
66 <     * which gives threads a chance to activate if necessary before
67 <     * stealing (see below).
60 >     * aggregate, we ensure at least probabilistic
61 >     * non-blockingness. If an attempted steal fails, a thief always
62 >     * chooses a different random victim target to try next. So, in
63 >     * order for one thief to progress, it suffices for any
64 >     * in-progress deq or new push on any empty queue to complete. One
65 >     * reason this works well here is that apparently-nonempty often
66 >     * means soon-to-be-stealable, which gives threads a chance to
67 >     * activate if necessary before stealing (see below).
68 >     *
69 >     * This approach also enables support for "async mode" where local
70 >     * task processing is in FIFO, not LIFO order; simply by using a
71 >     * version of deq rather than pop when locallyFifo is true (as set
72 >     * by the ForkJoinPool).  This allows use in message-passing
73 >     * frameworks in which tasks are never joined.
74       *
75       * Efficient implementation of this approach currently relies on
76       * an uncomfortable amount of "Unsafe" mechanics. To maintain
# Line 77 | Line 80 | public class ForkJoinWorkerThread extend
80       * protected by volatile base reads, reads of the queue array and
81       * its slots do not need volatile load semantics, but writes (in
82       * push) require store order and CASes (in pop and deq) require
83 <     * (volatile) CAS semantics. Since these combinations aren't
84 <     * supported using ordinary volatiles, the only way to accomplish
85 <     * these effciently is to use direct Unsafe calls. (Using external
83 >     * (volatile) CAS semantics.  (See "Idempotent work stealing" by
84 >     * Michael, Saraswat, and Vechev, PPoPP 2009
85 >     * http://portal.acm.org/citation.cfm?id=1504186 for an algorithm
86 >     * with similar properties, but without support for nulling
87 >     * slots.)  Since these combinations aren't supported using
88 >     * ordinary volatiles, the only way to accomplish these
89 >     * efficiently is to use direct Unsafe calls. (Using external
90       * AtomicIntegers and AtomicReferenceArrays for the indices and
91       * array is significantly slower because of memory locality and
92 <     * indirection effects.) Further, performance on most platforms is
93 <     * very sensitive to placement and sizing of the (resizable) queue
94 <     * array.  Even though these queues don't usually become all that
95 <     * big, the initial size must be large enough to counteract cache
92 >     * indirection effects.)
93 >     *
94 >     * Further, performance on most platforms is very sensitive to
95 >     * placement and sizing of the (resizable) queue array.  Even
96 >     * though these queues don't usually become all that big, the
97 >     * initial size must be large enough to counteract cache
98       * contention effects across multiple queues (especially in the
99       * presence of GC cardmarking). Also, to improve thread-locality,
100       * queues are currently initialized immediately after the thread
# Line 102 | Line 111 | public class ForkJoinWorkerThread extend
111       * counter (activeCount) held by the pool. It uses an algorithm
112       * similar to that in Herlihy and Shavit section 17.6 to cause
113       * threads to eventually block when all threads declare they are
114 <     * inactive. (See variable "scans".)  For this to work, threads
115 <     * must be declared active when executing tasks, and before
116 <     * stealing a task. They must be inactive before blocking on the
117 <     * Pool Barrier (awaiting a new submission or other Pool
118 <     * event). In between, there is some free play which we take
119 <     * advantage of to avoid contention and rapid flickering of the
120 <     * global activeCount: If inactive, we activate only if a victim
121 <     * queue appears to be nonempty (see above).  Similarly, a thread
122 <     * tries to inactivate only after a full scan of other threads.
123 <     * The net effect is that contention on activeCount is rarely a
124 <     * measurable performance issue. (There are also a few other cases
125 <     * where we scan for work rather than retry/block upon
117 <     * contention.)
114 >     * inactive. For this to work, threads must be declared active
115 >     * when executing tasks, and before stealing a task. They must be
116 >     * inactive before blocking on the Pool Barrier (awaiting a new
117 >     * submission or other Pool event). In between, there is some free
118 >     * play which we take advantage of to avoid contention and rapid
119 >     * flickering of the global activeCount: If inactive, we activate
120 >     * only if a victim queue appears to be nonempty (see above).
121 >     * Similarly, a thread tries to inactivate only after a full scan
122 >     * of other threads.  The net effect is that contention on
123 >     * activeCount is rarely a measurable performance issue. (There
124 >     * are also a few other cases where we scan for work rather than
125 >     * retry/block upon contention.)
126       *
127       * 3. Selection control. We maintain policy of always choosing to
128       * run local tasks rather than stealing, and always trying to
# Line 134 | Line 142 | public class ForkJoinWorkerThread extend
142  
143      /**
144       * Maximum work-stealing queue array size.  Must be less than or
145 <     * equal to 1 << 30 to ensure lack of index wraparound.
145 >     * equal to 1 << 28 to ensure lack of index wraparound. (This
146 >     * is less than usual bounds, because we need leftshift by 3
147 >     * to be in int range).
148       */
149 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30;
149 >    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
150  
151      /**
152 <     * Generator of seeds for per-thread random numbers.
152 >     * The pool this thread works in. Accessed directly by ForkJoinTask.
153       */
154 <    private static final Random randomSeedGenerator = new Random();
154 >    final ForkJoinPool pool;
155  
156      /**
157       * The work-stealing queue array. Size must be a power of two.
158 +     * Initialized when thread starts, to improve memory locality.
159       */
160      private ForkJoinTask<?>[] queue;
161  
# Line 163 | Line 174 | public class ForkJoinWorkerThread extend
174      private volatile int base;
175  
176      /**
177 <     * The pool this thread works in.
178 <     */
179 <    final ForkJoinPool pool;
180 <
170 <    /**
171 <     * Index of this worker in pool array. Set once by pool before
172 <     * running, and accessed directly by pool during cleanup etc
177 >     * Activity status. When true, this worker is considered active.
178 >     * Must be false upon construction. It must be true when executing
179 >     * tasks, and BEFORE stealing a task. It must be false before
180 >     * calling pool.sync.
181       */
182 <    int poolIndex;
182 >    private boolean active;
183  
184      /**
185       * Run state of this worker. Supports simple versions of the usual
# Line 179 | Line 187 | public class ForkJoinWorkerThread extend
187       */
188      private volatile int runState;
189  
182    // Runstate values. Order matters
183    private static final int RUNNING     = 0;
184    private static final int SHUTDOWN    = 1;
185    private static final int TERMINATING = 2;
186    private static final int TERMINATED  = 3;
187
190      /**
191 <     * Activity status. When true, this worker is considered active.
192 <     * 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.
191 >     * Seed for random number generator for choosing steal victims.
192 >     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
193       */
194 <    private boolean active;
194 >    private int seed;
195  
196      /**
197       * Number of steals, transferred to pool when idle
# Line 199 | Line 199 | public class ForkJoinWorkerThread extend
199      private int stealCount;
200  
201      /**
202 <     * Seed for random number generator for choosing steal victims
202 >     * Index of this worker in pool array. Set once by pool before
203 >     * running, and accessed directly by pool during cleanup etc.
204       */
205 <    private int randomVictimSeed;
205 >    int poolIndex;
206  
207      /**
208 <     * Seed for embedded Jurandom
208 >     * The last barrier event waited for. Accessed in pool callback
209 >     * methods, but only by current thread.
210       */
211 <    private long juRandomSeed;
211 >    long lastEventCount;
212  
213      /**
214 <     * The last barrier event waited for
214 >     * True if use local fifo, not default lifo, for local polling
215       */
216 <    private long eventCount;
216 >    private boolean locallyFifo;
217  
218      /**
219       * Creates a ForkJoinWorkerThread operating in the given pool.
220 +     *
221       * @param pool the pool this thread works in
222       * @throws NullPointerException if pool is null
223       */
224      protected ForkJoinWorkerThread(ForkJoinPool pool) {
225          if (pool == null) throw new NullPointerException();
226          this.pool = pool;
227 <        // remaining initialization deferred to onStart
227 >        // Note: poolIndex is set by pool during construction
228 >        // Remaining initialization is deferred to onStart
229      }
230  
231 <    // public access methods
231 >    // Public access methods
232  
233      /**
234 <     * Returns the pool hosting this thread
234 >     * Returns the pool hosting this thread.
235 >     *
236       * @return the pool
237       */
238      public ForkJoinPool getPool() {
# Line 239 | Line 244 | public class ForkJoinWorkerThread extend
244       * returned value ranges from zero to the maximum number of
245       * threads (minus one) that have ever been created in the pool.
246       * This method may be useful for applications that track status or
247 <     * collect results on a per-worker basis.
248 <     * @return the index number.
247 >     * collect results per-worker rather than per-task.
248 >     *
249 >     * @return the index number
250       */
251      public int getPoolIndex() {
252          return poolIndex;
253      }
254  
255 <    //  Access methods used by Pool
255 >    /**
256 >     * Establishes local first-in-first-out scheduling mode for forked
257 >     * tasks that are never joined.
258 >     *
259 >     * @param async if true, use locally FIFO scheduling
260 >     */
261 >    void setAsyncMode(boolean async) {
262 >        locallyFifo = async;
263 >    }
264 >
265 >    // Runstate management
266 >
267 >    // Runstate values. Order matters
268 >    private static final int RUNNING     = 0;
269 >    private static final int SHUTDOWN    = 1;
270 >    private static final int TERMINATING = 2;
271 >    private static final int TERMINATED  = 3;
272 >
273 >    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
274 >    final boolean isTerminating() { return runState >= TERMINATING;  }
275 >    final boolean isTerminated()  { return runState == TERMINATED; }
276 >    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
277 >    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
278  
279      /**
280 <     * Get and clear steal count for accumulation by pool.  Called
281 <     * only when known to be idle (in pool.sync and termination).
280 >     * Transitions to at least the given state.
281 >     *
282 >     * @return {@code true} if not already at least at given state
283       */
284 <    final int getAndClearStealCount() {
285 <        int sc = stealCount;
286 <        stealCount = 0;
287 <        return sc;
284 >    private boolean transitionRunStateTo(int state) {
285 >        for (;;) {
286 >            int s = runState;
287 >            if (s >= state)
288 >                return false;
289 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state))
290 >                return true;
291 >        }
292      }
293  
294      /**
295 <     * Returns estimate of the number of tasks in the queue, without
263 <     * correcting for transient negative values
295 >     * Tries to set status to active; fails on contention.
296       */
297 <    final int getRawQueueSize() {
298 <        return sp - base;
297 >    private boolean tryActivate() {
298 >        if (!active) {
299 >            if (!pool.tryIncrementActiveCount())
300 >                return false;
301 >            active = true;
302 >        }
303 >        return true;
304      }
305  
306 <    // Intrinsics-based support for queue operations.
307 <    // Currently these three (setSp, setSlot, casSlotNull) are
308 <    // usually manually inlined to improve performance
306 >    /**
307 >     * Tries to set status to inactive; fails on contention.
308 >     */
309 >    private boolean tryInactivate() {
310 >        if (active) {
311 >            if (!pool.tryDecrementActiveCount())
312 >                return false;
313 >            active = false;
314 >        }
315 >        return true;
316 >    }
317  
318      /**
319 <     * Sets sp in store-order.
319 >     * Computes next value for random victim probe.  Scans don't
320 >     * require a very high quality generator, but also not a crummy
321 >     * one.  Marsaglia xor-shift is cheap and works well.
322 >     */
323 >    private static int xorShift(int r) {
324 >        r ^= (r << 13);
325 >        r ^= (r >>> 17);
326 >        return r ^ (r << 5);
327 >    }
328 >
329 >    // Lifecycle methods
330 >
331 >    /**
332 >     * This method is required to be public, but should never be
333 >     * called explicitly. It performs the main run loop to execute
334 >     * ForkJoinTasks.
335 >     */
336 >    public void run() {
337 >        Throwable exception = null;
338 >        try {
339 >            onStart();
340 >            pool.sync(this); // await first pool event
341 >            mainLoop();
342 >        } catch (Throwable ex) {
343 >            exception = ex;
344 >        } finally {
345 >            onTermination(exception);
346 >        }
347 >    }
348 >
349 >    /**
350 >     * Executes tasks until shut down.
351       */
352 <    private void setSp(int s) {
353 <        _unsafe.putOrderedInt(this, spOffset, s);
352 >    private void mainLoop() {
353 >        while (!isShutdown()) {
354 >            ForkJoinTask<?> t = pollTask();
355 >            if (t != null || (t = pollSubmission()) != null)
356 >                t.quietlyExec();
357 >            else if (tryInactivate())
358 >                pool.sync(this);
359 >        }
360      }
361  
362      /**
363 <     * Add in store-order the given task at given slot of q to
364 <     * null. Caller must ensure q is nonnull and index is in range.
363 >     * Initializes internal state after construction but before
364 >     * processing any tasks. If you override this method, you must
365 >     * invoke super.onStart() at the beginning of the method.
366 >     * Initialization requires care: Most fields must have legal
367 >     * default values, to ensure that attempted accesses from other
368 >     * threads work correctly even before this thread starts
369 >     * processing tasks.
370 >     */
371 >    protected void onStart() {
372 >        // Allocate while starting to improve chances of thread-local
373 >        // isolation
374 >        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
375 >        // Initial value of seed need not be especially random but
376 >        // should differ across workers and must be nonzero
377 >        int p = poolIndex + 1;
378 >        seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
379 >    }
380 >
381 >    /**
382 >     * Performs cleanup associated with termination of this worker
383 >     * thread.  If you override this method, you must invoke
384 >     * {@code super.onTermination} at the end of the overridden method.
385 >     *
386 >     * @param exception the exception causing this thread to abort due
387 >     * to an unrecoverable error, or {@code null} if completed normally
388 >     */
389 >    protected void onTermination(Throwable exception) {
390 >        // Execute remaining local tasks unless aborting or terminating
391 >        while (exception == null && pool.isProcessingTasks() && base != sp) {
392 >            try {
393 >                ForkJoinTask<?> t = popTask();
394 >                if (t != null)
395 >                    t.quietlyExec();
396 >            } catch (Throwable ex) {
397 >                exception = ex;
398 >            }
399 >        }
400 >        // Cancel other tasks, transition status, notify pool, and
401 >        // propagate exception to uncaught exception handler
402 >        try {
403 >            do {} while (!tryInactivate()); // ensure inactive
404 >            cancelTasks();
405 >            runState = TERMINATED;
406 >            pool.workerTerminated(this);
407 >        } catch (Throwable ex) {        // Shouldn't ever happen
408 >            if (exception == null)      // but if so, at least rethrown
409 >                exception = ex;
410 >        } finally {
411 >            if (exception != null)
412 >                ForkJoinTask.rethrowException(exception);
413 >        }
414 >    }
415 >
416 >    // Intrinsics-based support for queue operations.
417 >
418 >    /**
419 >     * Adds in store-order the given task at given slot of q to null.
420 >     * Caller must ensure q is non-null and index is in range.
421       */
422      private static void setSlot(ForkJoinTask<?>[] q, int i,
423 <                                ForkJoinTask<?> t){
424 <        _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
423 >                                ForkJoinTask<?> t) {
424 >        UNSAFE.putOrderedObject(q, (i << qShift) + qBase, t);
425      }
426  
427      /**
428 <     * CAS given slot of q to null. Caller must ensure q is nonnull
428 >     * CAS given slot of q to null. Caller must ensure q is non-null
429       * and index is in range.
430       */
431      private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
432                                         ForkJoinTask<?> t) {
433 <        return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
433 >        return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
434 >    }
435 >
436 >    /**
437 >     * Sets sp in store-order.
438 >     */
439 >    private void storeSp(int s) {
440 >        UNSAFE.putOrderedInt(this, spOffset, s);
441      }
442  
443      // Main queue methods
444  
445      /**
446       * Pushes a task. Called only by current thread.
447 <     * @param t the task. Caller must ensure nonnull
447 >     *
448 >     * @param t the task. Caller must ensure non-null.
449       */
450      final void pushTask(ForkJoinTask<?> t) {
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);
454 >        setSlot(q, s & mask, t);
455 >        storeSp(++s);
456          if ((s -= base) == 1)
457 <            pool.signalNonEmptyWorkerQueue();
457 >            pool.signalWork();
458          else if (s >= mask)
459              growQueue();
460      }
# Line 316 | Line 462 | public class ForkJoinWorkerThread extend
462      /**
463       * Tries to take a task from the base of the queue, failing if
464       * either empty or contended.
465 <     * @return a task, or null if none or contended.
465 >     *
466 >     * @return a task, or null if none or contended
467       */
468 <    private ForkJoinTask<?> deqTask() {
322 <        ForkJoinTask<?>[] q;
468 >    final ForkJoinTask<?> deqTask() {
469          ForkJoinTask<?> t;
470 +        ForkJoinTask<?>[] q;
471          int i;
472          int b;
473          if (sp != (b = base) &&
474              (q = queue) != null && // must read q after b
475              (t = q[i = (q.length - 1) & b]) != null &&
476 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
476 >            casSlotNull(q, i, t)) {
477              base = b + 1;
478              return t;
479          }
# Line 334 | Line 481 | public class ForkJoinWorkerThread extend
481      }
482  
483      /**
484 <     * Returns a popped task, or null if empty.  Called only by
485 <     * current thread.
484 >     * Tries to take a task from the base of own queue, activating if
485 >     * necessary, failing only if empty. Called only by current thread.
486 >     *
487 >     * @return a task, or null if none
488 >     */
489 >    final ForkJoinTask<?> locallyDeqTask() {
490 >        int b;
491 >        while (sp != (b = base)) {
492 >            if (tryActivate()) {
493 >                ForkJoinTask<?>[] q = queue;
494 >                int i = (q.length - 1) & b;
495 >                ForkJoinTask<?> t = q[i];
496 >                if (t != null && casSlotNull(q, i, t)) {
497 >                    base = b + 1;
498 >                    return t;
499 >                }
500 >            }
501 >        }
502 >        return null;
503 >    }
504 >
505 >    /**
506 >     * Returns a popped task, or null if empty. Ensures active status
507 >     * if non-null. Called only by current thread.
508       */
509      final ForkJoinTask<?> popTask() {
341        ForkJoinTask<?> t;
342        int i;
343        ForkJoinTask<?>[] q = queue;
344        int mask = q.length - 1;
510          int s = sp;
511 <        if (s != base &&
512 <            (t = q[i = (s - 1) & mask]) != null &&
513 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
514 <            _unsafe.putOrderedInt(this, spOffset, s - 1);
515 <            return t;
511 >        while (s != base) {
512 >            if (tryActivate()) {
513 >                ForkJoinTask<?>[] q = queue;
514 >                int mask = q.length - 1;
515 >                int i = (s - 1) & mask;
516 >                ForkJoinTask<?> t = q[i];
517 >                if (t == null || !casSlotNull(q, i, t))
518 >                    break;
519 >                storeSp(s - 1);
520 >                return t;
521 >            }
522          }
523          return null;
524      }
# Line 355 | Line 526 | public class ForkJoinWorkerThread extend
526      /**
527       * Specialized version of popTask to pop only if
528       * topmost element is the given task. Called only
529 <     * by current thread.
530 <     * @param t the task. Caller must ensure nonnull
529 >     * by current thread while active.
530 >     *
531 >     * @param t the task. Caller must ensure non-null.
532       */
533      final boolean unpushTask(ForkJoinTask<?> t) {
534          ForkJoinTask<?>[] q = queue;
535          int mask = q.length - 1;
536          int s = sp - 1;
537 <        if (_unsafe.compareAndSwapObject(q, ((s & mask) << qShift) + qBase,
538 <                                         t, null)) {
367 <            _unsafe.putOrderedInt(this, spOffset, s);
537 >        if (casSlotNull(q, s & mask, t)) {
538 >            storeSp(s);
539              return true;
540          }
541          return false;
542      }
543  
544      /**
545 <     * Returns next task to pop.
545 >     * Returns next task or null if empty or contended
546       */
547      final ForkJoinTask<?> peekTask() {
548          ForkJoinTask<?>[] q = queue;
549 <        return q == null? null : q[(sp - 1) & (q.length - 1)];
549 >        if (q == null)
550 >            return null;
551 >        int mask = q.length - 1;
552 >        int i = locallyFifo ? base : (sp - 1);
553 >        return q[i & mask];
554      }
555  
556      /**
# Line 402 | Line 577 | public class ForkJoinWorkerThread extend
577                  t = null;
578              setSlot(newQ, b & newMask, t);
579          } while (++b != bf);
580 <        pool.signalIdleWorkers(false);
580 >        pool.signalWork();
581      }
582  
408    // Runstate management
409
410    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
411    final boolean isTerminating() { return runState >= TERMINATING;  }
412    final boolean isTerminated()  { return runState == TERMINATED; }
413    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
414    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
415
583      /**
584 <     * Transition to at least the given state. Return true if not
585 <     * already at least given state.
586 <     */
587 <    private boolean transitionRunStateTo(int state) {
588 <        for (;;) {
589 <            int s = runState;
590 <            if (s >= state)
591 <                return false;
592 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
593 <                return true;
594 <        }
595 <    }
596 <
597 <    /**
598 <     * Ensure status is active and if necessary adjust pool active count
599 <     */
433 <    final void activate() {
434 <        if (!active) {
435 <            active = true;
436 <            pool.incrementActiveCount();
437 <        }
438 <    }
439 <
440 <    /**
441 <     * Ensure status is inactive and if necessary adjust pool active count
584 >     * Tries to steal a task from another worker. Starts at a random
585 >     * index of workers array, and probes workers until finding one
586 >     * with non-empty queue or finding that all are empty.  It
587 >     * randomly selects the first n probes. If these are empty, it
588 >     * resorts to a full circular traversal, which is necessary to
589 >     * accurately set active status by caller. Also restarts if pool
590 >     * events occurred since last scan, which forces refresh of
591 >     * workers array, in case barrier was associated with resize.
592 >     *
593 >     * This method must be both fast and quiet -- usually avoiding
594 >     * memory accesses that could disrupt cache sharing etc other than
595 >     * those needed to check for and take tasks. This accounts for,
596 >     * among other things, updating random seed in place without
597 >     * storing it until exit.
598 >     *
599 >     * @return a task, or null if none found
600       */
601 <    final void inactivate() {
602 <        if (active) {
603 <            active = false;
604 <            pool.decrementActiveCount();
605 <        }
601 >    private ForkJoinTask<?> scan() {
602 >        ForkJoinTask<?> t = null;
603 >        int r = seed;                    // extract once to keep scan quiet
604 >        ForkJoinWorkerThread[] ws;       // refreshed on outer loop
605 >        int mask;                        // must be power 2 minus 1 and > 0
606 >        outer:do {
607 >            if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
608 >                int idx = r;
609 >                int probes = ~mask;      // use random index while negative
610 >                for (;;) {
611 >                    r = xorShift(r);     // update random seed
612 >                    ForkJoinWorkerThread v = ws[mask & idx];
613 >                    if (v == null || v.sp == v.base) {
614 >                        if (probes <= mask)
615 >                            idx = (probes++ < 0) ? r : (idx + 1);
616 >                        else
617 >                            break;
618 >                    }
619 >                    else if (!tryActivate() || (t = v.deqTask()) == null)
620 >                        continue outer;  // restart on contention
621 >                    else
622 >                        break outer;
623 >                }
624 >            }
625 >        } while (pool.hasNewSyncEvent(this)); // retry on pool events
626 >        seed = r;
627 >        return t;
628      }
629  
450    // Lifecycle methods
451
630      /**
631 <     * Initializes internal state after construction but before
632 <     * processing any tasks. If you override this method, you must
633 <     * invoke super.onStart() at the beginning of the method.
456 <     * 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.
631 >     * Gets and removes a local or stolen task.
632 >     *
633 >     * @return a task, if available
634       */
635 <    protected void onStart() {
636 <        juRandomSeed = randomSeedGenerator.nextLong();
637 <        do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero
638 <        if (queue == null)
639 <            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 <        }
635 >    final ForkJoinTask<?> pollTask() {
636 >        ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
637 >        if (t == null && (t = scan()) != null)
638 >            ++stealCount;
639 >        return t;
640      }
641  
642      /**
643 <     * Perform cleanup associated with termination of this worker
476 <     * thread.  If you override this method, you must invoke
477 <     * super.onTermination at the end of the overridden method.
643 >     * Gets a local task.
644       *
645 <     * @param exception the exception causing this thread to abort due
480 <     * to an unrecoverable error, or null if completed normally.
645 >     * @return a task, if available
646       */
647 <    protected void onTermination(Throwable exception) {
648 <        try {
484 <            clearLocalTasks();
485 <            inactivate();
486 <            cancelTasks();
487 <        } finally {
488 <            terminate(exception);
489 <        }
647 >    final ForkJoinTask<?> pollLocalTask() {
648 >        return locallyFifo ? locallyDeqTask() : popTask();
649      }
650  
651      /**
652 <     * Notify pool of termination and, if exception is nonnull,
653 <     * rethrow it to trigger this thread's uncaughtExceptionHandler
652 >     * Returns a pool submission, if one exists, activating first.
653 >     *
654 >     * @return a submission, if available
655       */
656 <    private void terminate(Throwable exception) {
657 <        transitionRunStateTo(TERMINATED);
658 <        try {
659 <            pool.workerTerminated(this);
660 <        } finally {
661 <            if (exception != null)
502 <                ForkJoinTask.rethrowException(exception);
656 >    private ForkJoinTask<?> pollSubmission() {
657 >        ForkJoinPool p = pool;
658 >        while (p.hasQueuedSubmissions()) {
659 >            ForkJoinTask<?> t;
660 >            if (tryActivate() && (t = p.pollSubmission()) != null)
661 >                return t;
662          }
663 +        return null;
664      }
665  
666 <    /**
507 <     * Run local tasks on exit from main.
508 <     */
509 <    private void clearLocalTasks() {
510 <        while (base != sp && !pool.isTerminating()) {
511 <            ForkJoinTask<?> t = popTask();
512 <            if (t != null) {
513 <                activate(); // ensure active status
514 <                t.quietlyExec();
515 <            }
516 <        }
517 <    }
666 >    // Methods accessed only by Pool
667  
668      /**
669       * Removes and cancels all tasks in queue.  Can be called from any
670       * thread.
671       */
672      final void cancelTasks() {
673 <        while (base != sp) {
674 <            ForkJoinTask<?> t = deqTask();
675 <            if (t != null)
527 <                t.cancelIgnoringExceptions();
528 <        }
529 <    }
530 <
531 <    /**
532 <     * This method is required to be public, but should never be
533 <     * called explicitly. It performs the main run loop to execute
534 <     * ForkJoinTasks.
535 <     */
536 <    public void run() {
537 <        Throwable exception = null;
538 <        try {
539 <            onStart();
540 <            while (!isShutdown())
541 <                step();
542 <        } catch (Throwable ex) {
543 <            exception = ex;
544 <        } finally {
545 <            onTermination(exception);
546 <        }
673 >        ForkJoinTask<?> t;
674 >        while (base != sp && (t = deqTask()) != null)
675 >            t.cancelIgnoringExceptions();
676      }
677  
678      /**
679 <     * Main top-level action.
679 >     * Drains tasks to given collection c.
680 >     *
681 >     * @return the number of tasks drained
682       */
683 <    private void step() {
684 <        ForkJoinTask<?> t = sp != base? popTask() : null;
685 <        if (t != null || (t = scan(null, true)) != null) {
686 <            activate();
687 <            t.quietlyExec();
688 <        }
558 <        else {
559 <            inactivate();
560 <            eventCount = pool.sync(this, eventCount);
683 >    final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
684 >        int n = 0;
685 >        ForkJoinTask<?> t;
686 >        while (base != sp && (t = deqTask()) != null) {
687 >            c.add(t);
688 >            ++n;
689          }
690 +        return n;
691      }
692  
564    // scanning for and stealing tasks
565
693      /**
694 <     * Computes next value for random victim probe. Scans don't
695 <     * require a very high quality generator, but also not a crummy
569 <     * one. Marsaglia xor-shift is cheap and works well.
570 <     *
571 <     * This is currently unused, and manually inlined
694 >     * Gets and clears steal count for accumulation by pool.  Called
695 >     * only when known to be idle (in pool.sync and termination).
696       */
697 <    private static int xorShift(int r) {
698 <        r ^= r << 1;
699 <        r ^= r >>> 3;
700 <        r ^= r << 10;
577 <        return r;
697 >    final int getAndClearStealCount() {
698 >        int sc = stealCount;
699 >        stealCount = 0;
700 >        return sc;
701      }
702  
703      /**
704 <     * Tries to steal a task from another worker and/or, if enabled,
705 <     * 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.
704 >     * Returns {@code true} if at least one worker in the given array
705 >     * appears to have at least one queued task.
706       *
707 <     * This method must be both fast and quiet -- usually avoiding
592 <     * memory accesses that could disrupt cache sharing etc other than
593 <     * those needed to check for and take tasks. This accounts for,
594 <     * among other things, updating random seed in place without
595 <     * storing it until exit. (Note that we only need to store it if
596 <     * we found a task; otherwise it doesn't matter if we start at the
597 <     * same place next time.)
598 <     *
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
707 >     * @param ws array of workers
708       */
709 <    private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe,
710 <                                 boolean checkSubmissions) {
711 <        ForkJoinPool p = pool;
712 <        if (p == null)                    // Never null, but avoids
713 <            return null;                  //   implicit nullchecks below
714 <        int r = randomVictimSeed;         // extract once to keep scan quiet
715 <        restart:                          // outer loop refreshes ws array
716 <        while (joinMe == null || joinMe.status >= 0) {
611 <            int mask;
612 <            ForkJoinWorkerThread[] ws = p.workers;
613 <            if (ws != null && (mask = ws.length - 1) > 0) {
614 <                int probes = -mask;       // use random index while negative
615 <                int idx = r;
616 <                for (;;) {
617 <                    ForkJoinWorkerThread v;
618 <                    // inlined xorshift to update seed
619 <                    r ^= r << 1;  r ^= r >>> 3; r ^= r << 10;
620 <                    if ((v = ws[mask & idx]) != null && v.sp != v.base) {
621 <                        ForkJoinTask<?> t;
622 <                        activate();
623 <                        if ((joinMe == null || joinMe.status >= 0) &&
624 <                            (t = v.deqTask()) != null) {
625 <                            randomVictimSeed = r;
626 <                            ++stealCount;
627 <                            return t;
628 <                        }
629 <                        continue restart; // restart on contention
630 <                    }
631 <                    if ((probes >> 1) <= mask) // n-1 random then circular
632 <                        idx = (probes++ < 0)? r : (idx + 1);
633 <                    else
634 <                        break;
709 >    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
710 >        if (ws != null) {
711 >            int len = ws.length;
712 >            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
713 >                for (int i = 0; i < len; ++i) {
714 >                    ForkJoinWorkerThread w = ws[i];
715 >                    if (w != null && w.sp != w.base)
716 >                        return true;
717                  }
718              }
637            if (checkSubmissions && p.hasQueuedSubmissions()) {
638                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            }
719          }
720 <        return null;
720 >        return false;
721      }
722  
723 +    // Support methods for ForkJoinTask
724 +
725      /**
726 <     * Callback from pool.sync to rescan before blocking.  If a
727 <     * task is found, it is pushed so it can be executed upon return.
728 <     * @return true if found and pushed a task
729 <     */
730 <    final boolean prescan() {
658 <        ForkJoinTask<?> t = scan(null, true);
659 <        if (t != null) {
660 <            pushTask(t);
661 <            return true;
662 <        }
663 <        else {
664 <            inactivate();
665 <            return false;
666 <        }
726 >     * Returns an estimate of the number of tasks in the queue.
727 >     */
728 >    final int getQueueSize() {
729 >        // suppress momentarily negative values
730 >        return Math.max(0, sp - base);
731      }
732  
733 <    // Support for ForkJoinTask methods
733 >    /**
734 >     * Returns an estimate of the number of tasks, offset by a
735 >     * function of number of idle workers.
736 >     */
737 >    final int getEstimatedSurplusTaskCount() {
738 >        // The halving approximates weighting idle vs non-idle workers
739 >        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
740 >    }
741  
742      /**
743 <     * Scan, returning early if joinMe done
743 >     * Scans, returning early if joinMe done.
744       */
745      final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
746 <        ForkJoinTask<?> t = scan(joinMe, false);
746 >        ForkJoinTask<?> t = pollTask();
747          if (t != null && joinMe.status < 0 && sp == base) {
748              pushTask(t); // unsteal if done and this task would be stealable
749              t = null;
750          }
751          return t;
752      }
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;
690    }
753  
754      /**
755 <     * Runs tasks until pool isQuiescent
755 >     * Runs tasks until {@code pool.isQuiescent()}.
756       */
757      final void helpQuiescePool() {
758          for (;;) {
759 <            ForkJoinTask<?> t = pollLocalOrStolenTask();
760 <            if (t != null) {
699 <                activate();
759 >            ForkJoinTask<?> t = pollTask();
760 >            if (t != null)
761                  t.quietlyExec();
762 <            }
763 <            else {
703 <                inactivate();
704 <                if (pool.isQuiescent()) {
705 <                    activate(); // re-activate on exit
706 <                    break;
707 <                }
708 <            }
762 >            else if (tryInactivate() && pool.isQuiescent())
763 >                break;
764          }
765 +        do {} while (!tryActivate()); // re-activate on exit
766      }
767  
768 <    /**
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 <    }
768 >    // Unsafe mechanics
769  
770 <    // Per-worker exported random numbers
770 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
771 >    private static final long spOffset =
772 >        objectFieldOffset("sp", ForkJoinWorkerThread.class);
773 >    private static final long runStateOffset =
774 >        objectFieldOffset("runState", ForkJoinWorkerThread.class);
775 >    private static final long qBase;
776 >    private static final int qShift;
777  
778 <    // Same constants as java.util.Random
779 <    final static long JURandomMultiplier = 0x5DEECE66DL;
780 <    final static long JURandomAddend = 0xBL;
781 <    final static long JURandomMask = (1L << 48) - 1;
782 <
783 <    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);
749 <
750 <        for (;;) {
751 <            int val = bits % n;
752 <            if (bits - val + (n-1) >= 0)
753 <                return val;
754 <            bits = nextJURandom(31);
755 <        }
756 <    }
757 <
758 <    private final long nextJURandomLong() {
759 <        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
778 >    static {
779 >        qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
780 >        int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
781 >        if ((s & (s-1)) != 0)
782 >            throw new Error("data type scale not a power of two");
783 >        qShift = 31 - Integer.numberOfLeadingZeros(s);
784      }
785  
786 <    private final long nextJURandomLong(long n) {
787 <        if (n <= 0)
788 <            throw new IllegalArgumentException("n must be positive");
789 <        long offset = 0;
790 <        while (n >= Integer.MAX_VALUE) { // randomly pick half range
791 <            int bits = nextJURandom(2); // 2nd bit for odd vs even split
792 <            long half = n >>> 1;
793 <            long nextn = ((bits & 2) == 0)? half : n - half;
770 <            if ((bits & 1) == 0)
771 <                offset += n - nextn;
772 <            n = nextn;
786 >    private static long objectFieldOffset(String field, Class<?> klazz) {
787 >        try {
788 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
789 >        } catch (NoSuchFieldException e) {
790 >            // Convert Exception to corresponding Error
791 >            NoSuchFieldError error = new NoSuchFieldError(field);
792 >            error.initCause(e);
793 >            throw error;
794          }
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);
792    }
793
794    /**
795     * Returns a random integer using a per-worker random
796     * number generator with the same properties as
797     * {@link java.util.Random#nextInt(int)}
798     * @param n the bound on the random number to be returned.  Must be
799     *        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);
795      }
796  
797      /**
798 <     * Returns a random double using a per-worker random
799 <     * number generator with the same properties as
800 <     * {@link java.util.Random#nextDouble}
801 <     * @return the next pseudorandom, uniformly distributed {@code double}
802 <     *         value between {@code 0.0} and {@code 1.0} from this
844 <     *         worker's random number generator's sequence
798 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
799 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
800 >     * into a jdk.
801 >     *
802 >     * @return a sun.misc.Unsafe
803       */
804 <    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 {
804 >    private static sun.misc.Unsafe getUnsafe() {
805          try {
806 <            if (ForkJoinWorkerThread.class.getClassLoader() != null) {
807 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
808 <                f.setAccessible(true);
809 <                _unsafe = (Unsafe)f.get(null);
806 >            return sun.misc.Unsafe.getUnsafe();
807 >        } catch (SecurityException se) {
808 >            try {
809 >                return java.security.AccessController.doPrivileged
810 >                    (new java.security
811 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
812 >                        public sun.misc.Unsafe run() throws Exception {
813 >                            java.lang.reflect.Field f = sun.misc
814 >                                .Unsafe.class.getDeclaredField("theUnsafe");
815 >                            f.setAccessible(true);
816 >                            return (sun.misc.Unsafe) f.get(null);
817 >                        }});
818 >            } catch (java.security.PrivilegedActionException e) {
819 >                throw new RuntimeException("Could not initialize intrinsics",
820 >                                           e.getCause());
821              }
866            else
867                _unsafe = Unsafe.getUnsafe();
868            baseOffset = _unsafe.objectFieldOffset
869                (ForkJoinWorkerThread.class.getDeclaredField("base"));
870            spOffset = _unsafe.objectFieldOffset
871                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
872            runStateOffset = _unsafe.objectFieldOffset
873                (ForkJoinWorkerThread.class.getDeclaredField("runState"));
874            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
875            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
876            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);
822          }
823      }
824   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines