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.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.8 by jsr166, Mon Jul 20 21:45:06 2009 UTC

# Line 13 | Line 13 | import sun.misc.Unsafe;
13   import java.lang.reflect.*;
14  
15   /**
16 < * A thread that is internally managed by a ForkJoinPool to execute
17 < * ForkJoinTasks. This class additionally provides public
18 < * <tt>static</tt> methods accessing some basic scheduling and
19 < * execution mechanics for the <em>current</em>
20 < * ForkJoinWorkerThread. These methods may be invoked only from within
21 < * other ForkJoinTask computations. Attempts to invoke in other
22 < * contexts result in exceptions or errors including
23 < * ClassCastException.  These methods enable construction of
24 < * special-purpose task classes, as well as specialized idioms
25 < * occasionally useful in ForkJoinTask processing.
16 > * A thread managed by a {@link ForkJoinPool}.  This class is
17 > * subclassable solely for the sake of adding functionality -- there
18 > * are no overridable methods dealing with scheduling or
19 > * execution. However, you can override initialization and termination
20 > * 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   *
27 * <p>The form of supported static methods reflects the fact that
28 * worker threads may access and process tasks obtained in any of
29 * three ways. In preference order: <em>Local</em> tasks are processed
30 * in LIFO (newest first) order. <em>Stolen</em> tasks are obtained
31 * from other threads in FIFO (oldest first) order, only if there are
32 * no local tasks to run.  <em>Submissions</em> form a FIFO queue
33 * common to the entire pool, and are started only if no other
34 * work is available.
35 *
36 * <p> This class is subclassable solely for the sake of adding
37 * functionality -- there are no overridable methods dealing with
38 * scheduling or execution. However, you can override initialization
39 * and termination cleanup methods surrounding the main task
40 * processing loop.  If you do create such a subclass, you will also
41 * need to supply a custom ForkJoinWorkerThreadFactory to use it in a
42 * ForkJoinPool.
24   */
25   public class ForkJoinWorkerThread extends Thread {
26      /*
# Line 149 | Line 130 | public class ForkJoinWorkerThread extend
130  
131      /**
132       * Maximum work-stealing queue array size.  Must be less than or
133 <     * equal to 1 << 30 to ensure lack of index wraparound.
133 >     * equal to 1 << 28 to ensure lack of index wraparound. (This
134 >     * is less than usual bounds, because we need leftshift by 3
135 >     * to be in int range).
136       */
137 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30;
137 >    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
138  
139      /**
140 <     * Generator of seeds for per-thread random numbers.
140 >     * The pool this thread works in. Accessed directly by ForkJoinTask
141       */
142 <    private static final Random randomSeedGenerator = new Random();
142 >    final ForkJoinPool pool;
143  
144      /**
145       * The work-stealing queue array. Size must be a power of two.
146 +     * Initialized when thread starts, to improve memory locality.
147       */
148      private ForkJoinTask<?>[] queue;
149  
# Line 178 | Line 162 | public class ForkJoinWorkerThread extend
162      private volatile int base;
163  
164      /**
165 <     * The pool this thread works in.
166 <     */
167 <    final ForkJoinPool pool;
168 <
185 <    /**
186 <     * Index of this worker in pool array. Set once by pool before
187 <     * running, and accessed directly by pool during cleanup etc
165 >     * Activity status. When true, this worker is considered active.
166 >     * Must be false upon construction. It must be true when executing
167 >     * tasks, and BEFORE stealing a task. It must be false before
168 >     * calling pool.sync
169       */
170 <    int poolIndex;
170 >    private boolean active;
171  
172      /**
173       * Run state of this worker. Supports simple versions of the usual
# Line 194 | Line 175 | public class ForkJoinWorkerThread extend
175       */
176      private volatile int runState;
177  
197    // Runstate values. Order matters
198    private static final int RUNNING     = 0;
199    private static final int SHUTDOWN    = 1;
200    private static final int TERMINATING = 2;
201    private static final int TERMINATED  = 3;
202
178      /**
179 <     * Activity status. When true, this worker is considered active.
180 <     * Must be false upon construction. It must be true when executing
206 <     * tasks, and BEFORE stealing a task. It must be false before
207 <     * blocking on the Pool Barrier.
179 >     * Seed for random number generator for choosing steal victims.
180 >     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
181       */
182 <    private boolean active;
182 >    private int seed;
183  
184      /**
185       * Number of steals, transferred to pool when idle
# Line 214 | Line 187 | public class ForkJoinWorkerThread extend
187      private int stealCount;
188  
189      /**
190 <     * Seed for random number generator for choosing steal victims
190 >     * Index of this worker in pool array. Set once by pool before
191 >     * running, and accessed directly by pool during cleanup etc
192       */
193 <    private int randomVictimSeed;
193 >    int poolIndex;
194  
195      /**
196 <     * Seed for embedded Jurandom
196 >     * The last barrier event waited for. Accessed in pool callback
197 >     * methods, but only by current thread.
198       */
199 <    private long juRandomSeed;
199 >    long lastEventCount;
200  
201      /**
202 <     * The last barrier event waited for
202 >     * True if use local fifo, not default lifo, for local polling
203       */
204 <    private long eventCount;
204 >    private boolean locallyFifo;
205  
206      /**
207       * Creates a ForkJoinWorkerThread operating in the given pool.
# Line 236 | Line 211 | public class ForkJoinWorkerThread extend
211      protected ForkJoinWorkerThread(ForkJoinPool pool) {
212          if (pool == null) throw new NullPointerException();
213          this.pool = pool;
214 <        // remaining initialization deferred to onStart
214 >        // Note: poolIndex is set by pool during construction
215 >        // Remaining initialization is deferred to onStart
216      }
217  
218 <    //  Access methods used by Pool
218 >    // Public access methods
219  
220      /**
221 <     * Get and clear steal count for accumulation by pool.  Called
222 <     * only when known to be idle (in pool.sync and termination).
221 >     * Returns the pool hosting this thread
222 >     * @return the pool
223       */
224 <    final int getAndClearStealCount() {
225 <        int sc = stealCount;
250 <        stealCount = 0;
251 <        return sc;
224 >    public ForkJoinPool getPool() {
225 >        return pool;
226      }
227  
228      /**
229 <     * Returns estimate of the number of tasks in the queue, without
230 <     * correcting for transient negative values
229 >     * Returns the index number of this thread in its pool.  The
230 >     * returned value ranges from zero to the maximum number of
231 >     * threads (minus one) that have ever been created in the pool.
232 >     * This method may be useful for applications that track status or
233 >     * collect results per-worker rather than per-task.
234 >     * @return the index number.
235       */
236 <    final int getRawQueueSize() {
237 <        return sp - base;
236 >    public int getPoolIndex() {
237 >        return poolIndex;
238      }
239  
240 <    // Intrinsics-based support for queue operations.
241 <    // Currently these three (setSp, setSlot, casSlotNull) are
242 <    // usually manually inlined to improve performance
240 >    /**
241 >     * Establishes local first-in-first-out scheduling mode for forked
242 >     * tasks that are never joined.
243 >     * @param async if true, use locally FIFO scheduling
244 >     */
245 >    void setAsyncMode(boolean async) {
246 >        locallyFifo = async;
247 >    }
248 >
249 >    // Runstate management
250 >
251 >    // Runstate values. Order matters
252 >    private static final int RUNNING     = 0;
253 >    private static final int SHUTDOWN    = 1;
254 >    private static final int TERMINATING = 2;
255 >    private static final int TERMINATED  = 3;
256 >
257 >    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
258 >    final boolean isTerminating() { return runState >= TERMINATING;  }
259 >    final boolean isTerminated()  { return runState == TERMINATED; }
260 >    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
261 >    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
262  
263      /**
264 <     * Sets sp in store-order.
264 >     * Transition to at least the given state. Return true if not
265 >     * already at least given state.
266       */
267 <    private void setSp(int s) {
268 <        _unsafe.putOrderedInt(this, spOffset, s);
267 >    private boolean transitionRunStateTo(int state) {
268 >        for (;;) {
269 >            int s = runState;
270 >            if (s >= state)
271 >                return false;
272 >            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
273 >                return true;
274 >        }
275 >    }
276 >
277 >    /**
278 >     * Try to set status to active; fail on contention
279 >     */
280 >    private boolean tryActivate() {
281 >        if (!active) {
282 >            if (!pool.tryIncrementActiveCount())
283 >                return false;
284 >            active = true;
285 >        }
286 >        return true;
287 >    }
288 >
289 >    /**
290 >     * Try to set status to active; fail on contention
291 >     */
292 >    private boolean tryInactivate() {
293 >        if (active) {
294 >            if (!pool.tryDecrementActiveCount())
295 >                return false;
296 >            active = false;
297 >        }
298 >        return true;
299 >    }
300 >
301 >    /**
302 >     * Computes next value for random victim probe. Scans don't
303 >     * require a very high quality generator, but also not a crummy
304 >     * one. Marsaglia xor-shift is cheap and works well.
305 >     */
306 >    private static int xorShift(int r) {
307 >        r ^= r << 1;
308 >        r ^= r >>> 3;
309 >        r ^= r << 10;
310 >        return r;
311 >    }
312 >
313 >    // Lifecycle methods
314 >
315 >    /**
316 >     * This method is required to be public, but should never be
317 >     * called explicitly. It performs the main run loop to execute
318 >     * ForkJoinTasks.
319 >     */
320 >    public void run() {
321 >        Throwable exception = null;
322 >        try {
323 >            onStart();
324 >            pool.sync(this); // await first pool event
325 >            mainLoop();
326 >        } catch (Throwable ex) {
327 >            exception = ex;
328 >        } finally {
329 >            onTermination(exception);
330 >        }
331 >    }
332 >
333 >    /**
334 >     * Execute tasks until shut down.
335 >     */
336 >    private void mainLoop() {
337 >        while (!isShutdown()) {
338 >            ForkJoinTask<?> t = pollTask();
339 >            if (t != null || (t = pollSubmission()) != null)
340 >                t.quietlyExec();
341 >            else if (tryInactivate())
342 >                pool.sync(this);
343 >        }
344 >    }
345 >
346 >    /**
347 >     * Initializes internal state after construction but before
348 >     * processing any tasks. If you override this method, you must
349 >     * invoke super.onStart() at the beginning of the method.
350 >     * Initialization requires care: Most fields must have legal
351 >     * default values, to ensure that attempted accesses from other
352 >     * threads work correctly even before this thread starts
353 >     * processing tasks.
354 >     */
355 >    protected void onStart() {
356 >        // Allocate while starting to improve chances of thread-local
357 >        // isolation
358 >        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
359 >        // Initial value of seed need not be especially random but
360 >        // should differ across workers and must be nonzero
361 >        int p = poolIndex + 1;
362 >        seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
363 >    }
364 >
365 >    /**
366 >     * Perform cleanup associated with termination of this worker
367 >     * thread.  If you override this method, you must invoke
368 >     * super.onTermination at the end of the overridden method.
369 >     *
370 >     * @param exception the exception causing this thread to abort due
371 >     * to an unrecoverable error, or null if completed normally.
372 >     */
373 >    protected void onTermination(Throwable exception) {
374 >        // Execute remaining local tasks unless aborting or terminating
375 >        while (exception == null &&  !pool.isTerminating() && base != sp) {
376 >            try {
377 >                ForkJoinTask<?> t = popTask();
378 >                if (t != null)
379 >                    t.quietlyExec();
380 >            } catch(Throwable ex) {
381 >                exception = ex;
382 >            }
383 >        }
384 >        // Cancel other tasks, transition status, notify pool, and
385 >        // propagate exception to uncaught exception handler
386 >        try {
387 >            do;while (!tryInactivate()); // ensure inactive
388 >            cancelTasks();
389 >            runState = TERMINATED;
390 >            pool.workerTerminated(this);
391 >        } catch (Throwable ex) {        // Shouldn't ever happen
392 >            if (exception == null)      // but if so, at least rethrown
393 >                exception = ex;
394 >        } finally {
395 >            if (exception != null)
396 >                ForkJoinTask.rethrowException(exception);
397 >        }
398      }
399  
400 +    // Intrinsics-based support for queue operations.
401 +
402      /**
403       * Add in store-order the given task at given slot of q to
404       * null. Caller must ensure q is nonnull and index is in range.
# Line 288 | Line 417 | public class ForkJoinWorkerThread extend
417          return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
418      }
419  
420 +    /**
421 +     * Sets sp in store-order.
422 +     */
423 +    private void storeSp(int s) {
424 +        _unsafe.putOrderedInt(this, spOffset, s);
425 +    }
426 +
427      // Main queue methods
428  
429      /**
# Line 298 | Line 434 | public class ForkJoinWorkerThread extend
434          ForkJoinTask<?>[] q = queue;
435          int mask = q.length - 1;
436          int s = sp;
437 <        _unsafe.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
438 <        _unsafe.putOrderedInt(this, spOffset, ++s);
437 >        setSlot(q, s & mask, t);
438 >        storeSp(++s);
439          if ((s -= base) == 1)
440 <            pool.signalNonEmptyWorkerQueue();
440 >            pool.signalWork();
441          else if (s >= mask)
442              growQueue();
443      }
# Line 311 | Line 447 | public class ForkJoinWorkerThread extend
447       * either empty or contended.
448       * @return a task, or null if none or contended.
449       */
450 <    private ForkJoinTask<?> deqTask() {
315 <        ForkJoinTask<?>[] q;
450 >    final ForkJoinTask<?> deqTask() {
451          ForkJoinTask<?> t;
452 +        ForkJoinTask<?>[] q;
453          int i;
454          int b;
455          if (sp != (b = base) &&
456              (q = queue) != null && // must read q after b
457              (t = q[i = (q.length - 1) & b]) != null &&
458 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
458 >            casSlotNull(q, i, t)) {
459              base = b + 1;
460              return t;
461          }
# Line 327 | Line 463 | public class ForkJoinWorkerThread extend
463      }
464  
465      /**
466 <     * Returns a popped task, or null if empty.  Called only by
467 <     * current thread.
466 >     * Returns a popped task, or null if empty. Ensures active status
467 >     * if nonnull. Called only by current thread.
468       */
469      final ForkJoinTask<?> popTask() {
334        ForkJoinTask<?> t;
335        int i;
336        ForkJoinTask<?>[] q = queue;
337        int mask = q.length - 1;
470          int s = sp;
471 <        if (s != base &&
472 <            (t = q[i = (s - 1) & mask]) != null &&
473 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
474 <            _unsafe.putOrderedInt(this, spOffset, s - 1);
475 <            return t;
471 >        while (s != base) {
472 >            if (tryActivate()) {
473 >                ForkJoinTask<?>[] q = queue;
474 >                int mask = q.length - 1;
475 >                int i = (s - 1) & mask;
476 >                ForkJoinTask<?> t = q[i];
477 >                if (t == null || !casSlotNull(q, i, t))
478 >                    break;
479 >                storeSp(s - 1);
480 >                return t;
481 >            }
482          }
483          return null;
484      }
# Line 348 | Line 486 | public class ForkJoinWorkerThread extend
486      /**
487       * Specialized version of popTask to pop only if
488       * topmost element is the given task. Called only
489 <     * by current thread.
489 >     * by current thread while active.
490       * @param t the task. Caller must ensure nonnull
491       */
492      final boolean unpushTask(ForkJoinTask<?> t) {
493          ForkJoinTask<?>[] q = queue;
494          int mask = q.length - 1;
495          int s = sp - 1;
496 <        if (_unsafe.compareAndSwapObject(q, ((s & mask) << qShift) + qBase,
497 <                                         t, null)) {
360 <            _unsafe.putOrderedInt(this, spOffset, s);
496 >        if (casSlotNull(q, s & mask, t)) {
497 >            storeSp(s);
498              return true;
499          }
500          return false;
501      }
502  
503      /**
504 <     * Returns next task to pop.
504 >     * Returns next task.
505       */
506 <    private ForkJoinTask<?> peekTask() {
506 >    final ForkJoinTask<?> peekTask() {
507          ForkJoinTask<?>[] q = queue;
508 <        return q == null? null : q[(sp - 1) & (q.length - 1)];
508 >        if (q == null)
509 >            return null;
510 >        int mask = q.length - 1;
511 >        int i = locallyFifo? base : (sp - 1);
512 >        return q[i & mask];
513      }
514  
515      /**
# Line 395 | Line 536 | public class ForkJoinWorkerThread extend
536                  t = null;
537              setSlot(newQ, b & newMask, t);
538          } while (++b != bf);
539 <        pool.signalIdleWorkers(false);
539 >        pool.signalWork();
540      }
541  
401    // Runstate management
402
403    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
404    final boolean isTerminating() { return runState >= TERMINATING;  }
405    final boolean isTerminated()  { return runState == TERMINATED; }
406    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
407    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
408
542      /**
543 <     * Transition to at least the given state. Return true if not
544 <     * already at least given state.
545 <     */
546 <    private boolean transitionRunStateTo(int state) {
547 <        for (;;) {
548 <            int s = runState;
549 <            if (s >= state)
550 <                return false;
418 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
419 <                return true;
420 <        }
421 <    }
422 <
423 <    /**
424 <     * Ensure status is active and if necessary adjust pool active count
425 <     */
426 <    final void activate() {
427 <        if (!active) {
428 <            active = true;
429 <            pool.incrementActiveCount();
430 <        }
431 <    }
432 <
433 <    /**
434 <     * Ensure status is inactive and if necessary adjust pool active count
435 <     */
436 <    final void inactivate() {
437 <        if (active) {
438 <            active = false;
439 <            pool.decrementActiveCount();
440 <        }
441 <    }
442 <
443 <    // Lifecycle methods
444 <
445 <    /**
446 <     * Initializes internal state after construction but before
447 <     * processing any tasks. If you override this method, you must
448 <     * invoke super.onStart() at the beginning of the method.
449 <     * Initialization requires care: Most fields must have legal
450 <     * default values, to ensure that attempted accesses from other
451 <     * threads work correctly even before this thread starts
452 <     * processing tasks.
453 <     */
454 <    protected void onStart() {
455 <        juRandomSeed = randomSeedGenerator.nextLong();
456 <        do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero
457 <        if (queue == null)
458 <            queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
459 <
460 <        // Heuristically allow one initial thread to warm up; others wait
461 <        if (poolIndex < pool.getParallelism() - 1) {
462 <            eventCount = pool.sync(this, 0);
463 <            activate();
464 <        }
465 <    }
466 <
467 <    /**
468 <     * Perform cleanup associated with termination of this worker
469 <     * thread.  If you override this method, you must invoke
470 <     * super.onTermination at the end of the overridden method.
471 <     *
472 <     * @param exception the exception causing this thread to abort due
473 <     * to an unrecoverable error, or null if completed normally.
474 <     */
475 <    protected void onTermination(Throwable exception) {
476 <        try {
477 <            clearLocalTasks();
478 <            inactivate();
479 <            cancelTasks();
480 <        } finally {
481 <            terminate(exception);
482 <        }
483 <    }
484 <
485 <    /**
486 <     * Notify pool of termination and, if exception is nonnull,
487 <     * rethrow it to trigger this thread's uncaughtExceptionHandler
488 <     */
489 <    private void terminate(Throwable exception) {
490 <        transitionRunStateTo(TERMINATED);
491 <        try {
492 <            pool.workerTerminated(this);
493 <        } finally {
494 <            if (exception != null)
495 <                ForkJoinTask.rethrowException(exception);
496 <        }
497 <    }
498 <
499 <    /**
500 <     * Run local tasks on exit from main.
501 <     */
502 <    private void clearLocalTasks() {
503 <        while (base != sp && !pool.isTerminating()) {
504 <            ForkJoinTask<?> t = popTask();
505 <            if (t != null) {
506 <                activate(); // ensure active status
507 <                t.quietlyExec();
508 <            }
509 <        }
510 <    }
511 <
512 <    /**
513 <     * Removes and cancels all tasks in queue.  Can be called from any
514 <     * thread.
515 <     */
516 <    final void cancelTasks() {
517 <        while (base != sp) {
518 <            ForkJoinTask<?> t = deqTask();
519 <            if (t != null)
520 <                t.cancelIgnoreExceptions();
521 <        }
522 <    }
523 <
524 <    /**
525 <     * This method is required to be public, but should never be
526 <     * called explicitly. It performs the main run loop to execute
527 <     * ForkJoinTasks.
528 <     */
529 <    public void run() {
530 <        Throwable exception = null;
531 <        try {
532 <            onStart();
533 <            while (!isShutdown())
534 <                step();
535 <        } catch (Throwable ex) {
536 <            exception = ex;
537 <        } finally {
538 <            onTermination(exception);
539 <        }
540 <    }
541 <
542 <    /**
543 <     * Main top-level action.
544 <     */
545 <    private void step() {
546 <        ForkJoinTask<?> t = sp != base? popTask() : null;
547 <        if (t != null || (t = scan(null, true)) != null) {
548 <            activate();
549 <            t.quietlyExec();
550 <        }
551 <        else {
552 <            inactivate();
553 <            eventCount = pool.sync(this, eventCount);
554 <        }
555 <    }
556 <
557 <    // scanning for and stealing tasks
558 <
559 <    /**
560 <     * Computes next value for random victim probe. Scans don't
561 <     * require a very high quality generator, but also not a crummy
562 <     * one. Marsaglia xor-shift is cheap and works well.
563 <     *
564 <     * This is currently unused, and manually inlined
565 <     */
566 <    private static int xorShift(int r) {
567 <        r ^= r << 1;
568 <        r ^= r >>> 3;
569 <        r ^= r << 10;
570 <        return r;
571 <    }
572 <
573 <    /**
574 <     * Tries to steal a task from another worker and/or, if enabled,
575 <     * submission queue. Starts at a random index of workers array,
576 <     * and probes workers until finding one with non-empty queue or
577 <     * finding that all are empty.  It randomly selects the first n-1
578 <     * probes. If these are empty, it resorts to full circular
579 <     * traversal, which is necessary to accurately set active status
580 <     * by caller. Also restarts if pool barrier has tripped since last
581 <     * scan, which forces refresh of workers array, in case barrier
582 <     * was associated with resize.
543 >     * Tries to steal a task from another worker. Starts at a random
544 >     * index of workers array, and probes workers until finding one
545 >     * with non-empty queue or finding that all are empty.  It
546 >     * randomly selects the first n probes. If these are empty, it
547 >     * resorts to a full circular traversal, which is necessary to
548 >     * accurately set active status by caller. Also restarts if pool
549 >     * events occurred since last scan, which forces refresh of
550 >     * workers array, in case barrier was associated with resize.
551       *
552       * This method must be both fast and quiet -- usually avoiding
553       * memory accesses that could disrupt cache sharing etc other than
554       * those needed to check for and take tasks. This accounts for,
555       * among other things, updating random seed in place without
556 <     * storing it until exit. (Note that we only need to store it if
589 <     * we found a task; otherwise it doesn't matter if we start at the
590 <     * same place next time.)
556 >     * storing it until exit.
557       *
592     * @param joinMe if non null; exit early if done
593     * @param checkSubmissions true if OK to take submissions
558       * @return a task, or null if none found
559       */
560 <    private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe,
561 <                                 boolean checkSubmissions) {
562 <        ForkJoinPool p = pool;
563 <        if (p == null)                    // Never null, but avoids
564 <            return null;                  //   implicit nullchecks below
565 <        int r = randomVictimSeed;         // extract once to keep scan quiet
566 <        restart:                          // outer loop refreshes ws array
603 <        while (joinMe == null || joinMe.status >= 0) {
604 <            int mask;
605 <            ForkJoinWorkerThread[] ws = p.workers;
606 <            if (ws != null && (mask = ws.length - 1) > 0) {
607 <                int probes = -mask;       // use random index while negative
560 >    private ForkJoinTask<?> scan() {
561 >        ForkJoinTask<?> t = null;
562 >        int r = seed;                    // extract once to keep scan quiet
563 >        ForkJoinWorkerThread[] ws;       // refreshed on outer loop
564 >        int mask;                        // must be power 2 minus 1 and > 0
565 >        outer:do {
566 >            if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
567                  int idx = r;
568 +                int probes = ~mask;      // use random index while negative
569                  for (;;) {
570 <                    ForkJoinWorkerThread v;
571 <                    // inlined xorshift to update seed
572 <                    r ^= r << 1;  r ^= r >>> 3; r ^= r << 10;
573 <                    if ((v = ws[mask & idx]) != null && v.sp != v.base) {
574 <                        ForkJoinTask<?> t;
575 <                        activate();
576 <                        if ((joinMe == null || joinMe.status >= 0) &&
617 <                            (t = v.deqTask()) != null) {
618 <                            randomVictimSeed = r;
619 <                            ++stealCount;
620 <                            return t;
621 <                        }
622 <                        continue restart; // restart on contention
570 >                    r = xorShift(r);     // update random seed
571 >                    ForkJoinWorkerThread v = ws[mask & idx];
572 >                    if (v == null || v.sp == v.base) {
573 >                        if (probes <= mask)
574 >                            idx = (probes++ < 0)? r : (idx + 1);
575 >                        else
576 >                            break;
577                      }
578 <                    if ((probes >> 1) <= mask) // n-1 random then circular
579 <                        idx = (probes++ < 0)? r : (idx + 1);
578 >                    else if (!tryActivate() || (t = v.deqTask()) == null)
579 >                        continue outer;  // restart on contention
580                      else
581 <                        break;
581 >                        break outer;
582                  }
583              }
584 <            if (checkSubmissions && p.hasQueuedSubmissions()) {
585 <                activate();
586 <                ForkJoinTask<?> t = p.pollSubmission();
633 <                if (t != null)
634 <                    return t;
635 <            }
636 <            else {
637 <                long ec = eventCount;     // restart on pool event
638 <                if ((eventCount = p.getEventCount()) == ec)
639 <                    break;
640 <            }
641 <        }
642 <        return null;
584 >        } while (pool.hasNewSyncEvent(this)); // retry on pool events
585 >        seed = r;
586 >        return t;
587      }
588  
589      /**
590 <     * Callback from pool.sync to rescan before blocking.  If a
591 <     * task is found, it is pushed so it can be executed upon return.
648 <     * @return true if found and pushed a task
649 <     */
650 <    final boolean prescan() {
651 <        ForkJoinTask<?> t = scan(null, true);
652 <        if (t != null) {
653 <            pushTask(t);
654 <            return true;
655 <        }
656 <        else {
657 <            inactivate();
658 <            return false;
659 <        }
660 <    }
661 <
662 <    /**
663 <     * Implements ForkJoinTask.helpJoin
590 >     * gets and removes a local or stolen a task
591 >     * @return a task, if available
592       */
593 <    final int helpJoinTask(ForkJoinTask<?> joinMe) {
594 <        ForkJoinTask<?> t = null;
595 <        int s;
596 <        while ((s = joinMe.status) >= 0) {
597 <            if (t == null) {
670 <                if ((t = scan(joinMe, false)) == null)  // block if no work
671 <                    return joinMe.awaitDone(this, false);
672 <                // else recheck status before exec
673 <            }
674 <            else {
675 <                t.quietlyExec();
676 <                t = null;
677 <            }
678 <        }
679 <        if (t != null) // unsteal
680 <            pushTask(t);
681 <        return s;
593 >    final ForkJoinTask<?> pollTask() {
594 >        ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
595 >        if (t == null && (t = scan()) != null)
596 >            ++stealCount;
597 >        return t;
598      }
599  
684    // Support for public static and/or ForkJoinTask methods
685
600      /**
601 <     * Returns an estimate of the number of tasks in the queue.
601 >     * gets a local task
602 >     * @return a task, if available
603       */
604 <    final int getQueueSize() {
605 <        int b = base;
691 <        int n = sp - b;
692 <        return n <= 0? 0 : n; // suppress momentarily negative values
604 >    final ForkJoinTask<?> pollLocalTask() {
605 >        return locallyFifo? deqTask() : popTask();
606      }
607  
608      /**
609 <     * Runs one popped task, if available
610 <     * @return true if ran a task
609 >     * Returns a pool submission, if one exists, activating first.
610 >     * @return a submission, if available
611       */
612 <    private boolean runLocalTask() {
613 <        ForkJoinTask<?> t = popTask();
614 <        if (t == null)
615 <            return false;
616 <        t.quietlyExec();
617 <        return true;
612 >    private ForkJoinTask<?> pollSubmission() {
613 >        ForkJoinPool p = pool;
614 >        while (p.hasQueuedSubmissions()) {
615 >            ForkJoinTask<?> t;
616 >            if (tryActivate() && (t = p.pollSubmission()) != null)
617 >                return t;
618 >        }
619 >        return null;
620      }
621  
622 <    /**
708 <     * Pops or steals a task
709 <     * @return task, or null if none available
710 <     */
711 <    private ForkJoinTask<?> getLocalOrStolenTask() {
712 <        ForkJoinTask<?> t = popTask();
713 <        return t != null? t : scan(null, false);
714 <    }
622 >    // Methods accessed only by Pool
623  
624      /**
625 <     * Runs a popped or stolen task, if available
626 <     * @return true if ran a task
625 >     * Removes and cancels all tasks in queue.  Can be called from any
626 >     * thread.
627       */
628 <    private boolean runLocalOrStolenTask() {
629 <        ForkJoinTask<?> t = getLocalOrStolenTask();
630 <        if (t == null)
631 <            return false;
724 <        t.quietlyExec();
725 <        return true;
628 >    final void cancelTasks() {
629 >        ForkJoinTask<?> t;
630 >        while (base != sp && (t = deqTask()) != null)
631 >            t.cancelIgnoringExceptions();
632      }
633  
634      /**
635 <     * Runs tasks until pool isQuiescent
635 >     * Drains tasks to given collection c
636 >     * @return the number of tasks drained
637       */
638 <    final void helpQuiescePool() {
639 <        activate();
640 <        for (;;) {
641 <            if (!runLocalOrStolenTask()) {
642 <                inactivate();
643 <                if (pool.isQuiescent()) {
737 <                    activate(); // re-activate on exit
738 <                    break;
739 <                }
740 <            }
638 >    final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
639 >        int n = 0;
640 >        ForkJoinTask<?> t;
641 >        while (base != sp && (t = deqTask()) != null) {
642 >            c.add(t);
643 >            ++n;
644          }
645 +        return n;
646      }
647  
648      /**
649 <     * Returns an estimate of the number of tasks, offset by a
650 <     * function of number of idle workers.
747 <     */
748 <    final int getEstimatedSurplusTaskCount() {
749 <        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
750 <    }
751 <
752 <    // Public methods on current thread
753 <
754 <    /**
755 <     * Returns the pool hosting the current task execution.
756 <     * @return the pool
757 <     */
758 <    public static ForkJoinPool getPool() {
759 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pool;
760 <    }
761 <
762 <    /**
763 <     * Returns the index number of the current worker thread in its
764 <     * pool.  The returned value ranges from zero to the maximum
765 <     * number of threads (minus one) that have ever been created in
766 <     * the pool.  This method may be useful for applications that
767 <     * track status or collect results per-worker rather than
768 <     * per-task.
769 <     * @return the index number.
649 >     * Get and clear steal count for accumulation by pool.  Called
650 >     * only when known to be idle (in pool.sync and termination).
651       */
652 <    public static int getPoolIndex() {
653 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex;
652 >    final int getAndClearStealCount() {
653 >        int sc = stealCount;
654 >        stealCount = 0;
655 >        return sc;
656      }
657  
658      /**
659 <     * Returns an estimate of the number of tasks waiting to be run by
660 <     * the current worker thread. This value may be useful for
661 <     * heuristic decisions about whether to fork other tasks.
662 <     * @return the number of tasks
663 <     */
664 <    public static int getLocalQueueSize() {
665 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
666 <            getQueueSize();
659 >     * Returns true if at least one worker in the given array appears
660 >     * to have at least one queued task.
661 >     * @param ws array of workers
662 >     */
663 >    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
664 >        if (ws != null) {
665 >            int len = ws.length;
666 >            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
667 >                for (int i = 0; i < len; ++i) {
668 >                    ForkJoinWorkerThread w = ws[i];
669 >                    if (w != null && w.sp != w.base)
670 >                        return true;
671 >                }
672 >            }
673 >        }
674 >        return false;
675      }
676  
677 <    /**
787 <     * Returns, but does not remove or execute, the next task locally
788 <     * queued for execution by the current worker thread. There is no
789 <     * guarantee that this task will be the next one actually returned
790 <     * or executed from other polling or execution methods.
791 <     * @return the next task or null if none
792 <     */
793 <    public static ForkJoinTask<?> peekLocalTask() {
794 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
795 <    }
677 >    // Support methods for ForkJoinTask
678  
679      /**
680 <     * Removes and returns, without executing, the next task queued
799 <     * for execution in the current worker thread's local queue.
800 <     * @return the next task to execute, or null if none
680 >     * Returns an estimate of the number of tasks in the queue.
681       */
682 <    public static ForkJoinTask<?> pollLocalTask() {
683 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask();
682 >    final int getQueueSize() {
683 >        int n = sp - base;
684 >        return n < 0? 0 : n; // suppress momentarily negative values
685      }
686  
687      /**
688 <     * Execute the next task locally queued by the current worker, if
689 <     * one is available.
809 <     * @return true if a task was run; a false return indicates
810 <     * that no task was available.
688 >     * Returns an estimate of the number of tasks, offset by a
689 >     * function of number of idle workers.
690       */
691 <    public static boolean executeLocalTask() {
692 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
693 <            runLocalTask();
691 >    final int getEstimatedSurplusTaskCount() {
692 >        // The halving approximates weighting idle vs non-idle workers
693 >        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
694      }
695  
696      /**
697 <     * Removes and returns, without executing, the next task queued
819 <     * for execution in the current worker thread's local queue or if
820 <     * none, a task stolen from another worker, if one is available.
821 <     * A null return does not necessarily imply that all tasks are
822 <     * completed, only that there are currently none available.
823 <     * @return the next task to execute, or null if none
697 >     * Scan, returning early if joinMe done
698       */
699 <    public static ForkJoinTask<?> pollTask() {
700 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
701 <            getLocalOrStolenTask();
699 >    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
700 >        ForkJoinTask<?> t = pollTask();
701 >        if (t != null && joinMe.status < 0 && sp == base) {
702 >            pushTask(t); // unsteal if done and this task would be stealable
703 >            t = null;
704 >        }
705 >        return t;
706      }
707  
708      /**
709 <     * Helps this program complete by processing a local or stolen
832 <     * task, if one is available.  This method may be useful when
833 <     * several tasks are forked, and only one of them must be joined,
834 <     * as in:
835 <     *
836 <     * <pre>
837 <     *   while (!t1.isDone() &amp;&amp; !t2.isDone())
838 <     *     ForkJoinWorkerThread.executeTask();
839 <     * </pre>
840 <     *
841 <     * @return true if a task was run; a false return indicates
842 <     * that no task was available.
709 >     * Runs tasks until pool isQuiescent
710       */
711 <    public static boolean executeTask() {
845 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
846 <            runLocalOrStolenTask();
847 <    }
848 <
849 <    // Per-worker exported random numbers
850 <
851 <    // Same constants as java.util.Random
852 <    final static long JURandomMultiplier = 0x5DEECE66DL;
853 <    final static long JURandomAddend = 0xBL;
854 <    final static long JURandomMask = (1L << 48) - 1;
855 <
856 <    private final int nextJURandom(int bits) {
857 <        long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) &
858 <            JURandomMask;
859 <        juRandomSeed = next;
860 <        return (int)(next >>> (48 - bits));
861 <    }
862 <
863 <    private final int nextJURandomInt(int n) {
864 <        if (n <= 0)
865 <            throw new IllegalArgumentException("n must be positive");
866 <        int bits = nextJURandom(31);
867 <        if ((n & -n) == n)
868 <            return (int)((n * (long)bits) >> 31);
869 <
711 >    final void helpQuiescePool() {
712          for (;;) {
713 <            int val = bits % n;
714 <            if (bits - val + (n-1) >= 0)
715 <                return val;
716 <            bits = nextJURandom(31);
713 >            ForkJoinTask<?> t = pollTask();
714 >            if (t != null)
715 >                t.quietlyExec();
716 >            else if (tryInactivate() && pool.isQuiescent())
717 >                break;
718          }
719 +        do;while (!tryActivate()); // re-activate on exit
720      }
721  
722 <    private final long nextJURandomLong() {
723 <        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
724 <    }
725 <
726 <    private final long nextJURandomLong(long n) {
727 <        if (n <= 0)
728 <            throw new IllegalArgumentException("n must be positive");
729 <        long offset = 0;
730 <        while (n >= Integer.MAX_VALUE) { // randomly pick half range
731 <            int bits = nextJURandom(2); // 2nd bit for odd vs even split
732 <            long half = n >>> 1;
733 <            long nextn = ((bits & 2) == 0)? half : n - half;
734 <            if ((bits & 1) == 0)
735 <                offset += n - nextn;
892 <            n = nextn;
722 >    // Temporary Unsafe mechanics for preliminary release
723 >    private static Unsafe getUnsafe() throws Throwable {
724 >        try {
725 >            return Unsafe.getUnsafe();
726 >        } catch (SecurityException se) {
727 >            try {
728 >                return java.security.AccessController.doPrivileged
729 >                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
730 >                        public Unsafe run() throws Exception {
731 >                            return getUnsafePrivileged();
732 >                        }});
733 >            } catch (java.security.PrivilegedActionException e) {
734 >                throw e.getCause();
735 >            }
736          }
894        return offset + nextJURandomInt((int)n);
737      }
738  
739 <    private final double nextJURandomDouble() {
740 <        return (((long)(nextJURandom(26)) << 27) + nextJURandom(27))
741 <            / (double)(1L << 53);
739 >    private static Unsafe getUnsafePrivileged()
740 >            throws NoSuchFieldException, IllegalAccessException {
741 >        Field f = Unsafe.class.getDeclaredField("theUnsafe");
742 >        f.setAccessible(true);
743 >        return (Unsafe) f.get(null);
744      }
745  
746 <    /**
747 <     * Returns a random integer using a per-worker random
748 <     * number generator with the same properties as
749 <     * {@link java.util.Random#nextInt}
906 <     * @return the next pseudorandom, uniformly distributed {@code int}
907 <     *         value from this worker's random number generator's sequence
908 <     */
909 <    public static int nextRandomInt() {
910 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
911 <            nextJURandom(32);
746 >    private static long fieldOffset(String fieldName)
747 >            throws NoSuchFieldException {
748 >        return _unsafe.objectFieldOffset
749 >            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
750      }
751  
914    /**
915     * Returns a random integer using a per-worker random
916     * number generator with the same properties as
917     * {@link java.util.Random#nextInt(int)}
918     * @param n the bound on the random number to be returned.  Must be
919     *        positive.
920     * @return the next pseudorandom, uniformly distributed {@code int}
921     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
922     *         from this worker's random number generator's sequence
923     * @throws IllegalArgumentException if n is not positive
924     */
925    public static int nextRandomInt(int n) {
926        return ((ForkJoinWorkerThread)(Thread.currentThread())).
927            nextJURandomInt(n);
928    }
929
930    /**
931     * Returns a random long using a per-worker random
932     * number generator with the same properties as
933     * {@link java.util.Random#nextLong}
934     * @return the next pseudorandom, uniformly distributed {@code long}
935     *         value from this worker's random number generator's sequence
936     */
937    public static long nextRandomLong() {
938        return ((ForkJoinWorkerThread)(Thread.currentThread())).
939            nextJURandomLong();
940    }
941
942    /**
943     * Returns a random integer using a per-worker random
944     * number generator with the same properties as
945     * {@link java.util.Random#nextInt(int)}
946     * @param n the bound on the random number to be returned.  Must be
947     *        positive.
948     * @return the next pseudorandom, uniformly distributed {@code int}
949     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
950     *         from this worker's random number generator's sequence
951     * @throws IllegalArgumentException if n is not positive
952     */
953    public static long nextRandomLong(long n) {
954        return ((ForkJoinWorkerThread)(Thread.currentThread())).
955            nextJURandomLong(n);
956    }
957
958    /**
959     * Returns a random double using a per-worker random
960     * number generator with the same properties as
961     * {@link java.util.Random#nextDouble}
962     * @return the next pseudorandom, uniformly distributed {@code double}
963     *         value between {@code 0.0} and {@code 1.0} from this
964     *         worker's random number generator's sequence
965     */
966    public static double nextRandomDouble() {
967        return ((ForkJoinWorkerThread)(Thread.currentThread())).
968            nextJURandomDouble();
969    }
970
971    // Temporary Unsafe mechanics for preliminary release
972
752      static final Unsafe _unsafe;
753      static final long baseOffset;
754      static final long spOffset;
755 +    static final long runStateOffset;
756      static final long qBase;
757      static final int qShift;
978    static final long runStateOffset;
758      static {
759          try {
760 <            if (ForkJoinWorkerThread.class.getClassLoader() != null) {
761 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
762 <                f.setAccessible(true);
763 <                _unsafe = (Unsafe)f.get(null);
985 <            }
986 <            else
987 <                _unsafe = Unsafe.getUnsafe();
988 <            baseOffset = _unsafe.objectFieldOffset
989 <                (ForkJoinWorkerThread.class.getDeclaredField("base"));
990 <            spOffset = _unsafe.objectFieldOffset
991 <                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
992 <            runStateOffset = _unsafe.objectFieldOffset
993 <                (ForkJoinWorkerThread.class.getDeclaredField("runState"));
760 >            _unsafe = getUnsafe();
761 >            baseOffset = fieldOffset("base");
762 >            spOffset = fieldOffset("sp");
763 >            runStateOffset = fieldOffset("runState");
764              qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
765              int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
766              if ((s & (s-1)) != 0)
767                  throw new Error("data type scale not a power of two");
768              qShift = 31 - Integer.numberOfLeadingZeros(s);
769 <        } catch (Exception e) {
769 >        } catch (Throwable e) {
770              throw new RuntimeException("Could not initialize intrinsics", e);
771          }
772      }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines