ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.3 by dl, Wed Jan 7 19:12:36 2009 UTC vs.
Revision 1.16 by jsr166, Thu Jul 23 23:07:57 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines