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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines