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.2 by dl, Wed Jan 7 16:07:37 2009 UTC vs.
Revision 1.7 by dl, Thu Jul 16 15:32:34 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   */
25   public class ForkJoinWorkerThread extends Thread {
26      /*
# Line 134 | 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 163 | 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 <
170 <    /**
171 <     * Index of this worker in pool array. Set once by pool before
172 <     * 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 179 | Line 175 | public class ForkJoinWorkerThread extend
175       */
176      private volatile int runState;
177  
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
178      /**
179 <     * Activity status. When true, this worker is considered active.
180 <     * 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.
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 199 | 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 221 | 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 <    // public access methods
218 >    // Public access methods
219  
220      /**
221 <     * Returns the pool hosting the current task execution.
221 >     * Returns the pool hosting this thread
222       * @return the pool
223       */
224 <    public static ForkJoinPool getPool() {
225 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pool;
224 >    public ForkJoinPool getPool() {
225 >        return pool;
226      }
227  
228      /**
229 <     * Returns the index number of the current worker thread in its
230 <     * pool.  The returned value ranges from zero to the maximum
231 <     * number of threads (minus one) that have ever been created in
232 <     * the pool.  This method may be useful for applications that
233 <     * track status or collect results on a per-worker basis.
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 <    public static int getPoolIndex() {
237 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex;
236 >    public int getPoolIndex() {
237 >        return poolIndex;
238 >    }
239 >
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 <    //  Access methods used by Pool
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 <     * Get and clear steal count for accumulation by pool.  Called
265 <     * only when known to be idle (in pool.sync and termination).
264 >     * Transition to at least the given state. Return true if not
265 >     * already at least given state.
266       */
267 <    final int getAndClearStealCount() {
268 <        int sc = stealCount;
269 <        stealCount = 0;
270 <        return sc;
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 <     * Returns estimate of the number of tasks in the queue, without
263 <     * correcting for transient negative values
278 >     * Try to set status to active; fail on contention
279       */
280 <    final int getRawQueueSize() {
281 <        return sp - base;
280 >    private boolean tryActivate() {
281 >        if (!active) {
282 >            if (!pool.tryIncrementActiveCount())
283 >                return false;
284 >            active = true;
285 >        }
286 >        return true;
287      }
288  
289 <    // Intrinsics-based support for queue operations.
290 <    // Currently these three (setSp, setSlot, casSlotNull) are
291 <    // usually manually inlined to improve performance
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 <     * Sets sp in store-order.
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 void setSp(int s) {
307 <        _unsafe.putOrderedInt(this, spOffset, s);
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 295 | 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 305 | 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 318 | 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() {
322 <        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 334 | 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() {
341        ForkJoinTask<?> t;
342        int i;
343        ForkJoinTask<?>[] q = queue;
344        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 355 | 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)) {
367 <            _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      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 402 | Line 536 | public class ForkJoinWorkerThread extend
536                  t = null;
537              setSlot(newQ, b & newMask, t);
538          } while (++b != bf);
539 <        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 <        }
539 >        pool.signalWork();
540      }
541  
542      /**
543 <     * Ensure status is active and if necessary adjust pool active count
544 <     */
545 <    final void activate() {
546 <        if (!active) {
547 <            active = true;
548 <            pool.incrementActiveCount();
549 <        }
550 <    }
551 <
552 <    /**
553 <     * Ensure status is inactive and if necessary adjust pool active count
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.
557 >     *
558 >     * @return a task, or null if none found
559       */
560 <    final void inactivate() {
561 <        if (active) {
562 <            active = false;
563 <            pool.decrementActiveCount();
564 <        }
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 >                    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 >                    else if (!tryActivate() || (t = v.deqTask()) == null)
579 >                        continue outer;  // restart on contention
580 >                    else
581 >                        break outer;
582 >                }
583 >            }
584 >        } while (pool.hasNewSyncEvent(this)); // retry on pool events
585 >        seed = r;
586 >        return t;
587      }
588  
450    // Lifecycle methods
451
589      /**
590 <     * Initializes internal state after construction but before
591 <     * processing any tasks. If you override this method, you must
455 <     * 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.
590 >     * gets and removes a local or stolen a task
591 >     * @return a task, if available
592       */
593 <    protected void onStart() {
594 <        juRandomSeed = randomSeedGenerator.nextLong();
595 <        do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero
596 <        if (queue == null)
597 <            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 <        }
593 >    final ForkJoinTask<?> pollTask() {
594 >        ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
595 >        if (t == null && (t = scan()) != null)
596 >            ++stealCount;
597 >        return t;
598      }
599  
600      /**
601 <     * Perform cleanup associated with termination of this worker
602 <     * thread.  If you override this method, you must invoke
477 <     * super.onTermination at the end of the overridden method.
478 <     *
479 <     * @param exception the exception causing this thread to abort due
480 <     * to an unrecoverable error, or null if completed normally.
601 >     * gets a local task
602 >     * @return a task, if available
603       */
604 <    protected void onTermination(Throwable exception) {
605 <        try {
484 <            clearLocalTasks();
485 <            inactivate();
486 <            cancelTasks();
487 <        } finally {
488 <            terminate(exception);
489 <        }
604 >    final ForkJoinTask<?> pollLocalTask() {
605 >        return locallyFifo? deqTask() : popTask();
606      }
607  
608      /**
609 <     * Notify pool of termination and, if exception is nonnull,
610 <     * rethrow it to trigger this thread's uncaughtExceptionHandler
609 >     * Returns a pool submission, if one exists, activating first.
610 >     * @return a submission, if available
611       */
612 <    private void terminate(Throwable exception) {
613 <        transitionRunStateTo(TERMINATED);
614 <        try {
615 <            pool.workerTerminated(this);
616 <        } finally {
617 <            if (exception != null)
502 <                ForkJoinTask.rethrowException(exception);
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 <    /**
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 <    }
622 >    // Methods accessed only by Pool
623  
624      /**
625       * Removes and cancels all tasks in queue.  Can be called from any
626       * thread.
627       */
628      final void cancelTasks() {
629 <        while (base != sp) {
630 <            ForkJoinTask<?> t = deqTask();
631 <            if (t != null)
527 <                t.cancelIgnoreExceptions();
528 <        }
529 <    }
530 <
531 <    /**
532 <     * This method is required to be public, but should never be
533 <     * called explicitly. It performs the main run loop to execute
534 <     * ForkJoinTasks.
535 <     */
536 <    public void run() {
537 <        Throwable exception = null;
538 <        try {
539 <            onStart();
540 <            while (!isShutdown())
541 <                step();
542 <        } catch (Throwable ex) {
543 <            exception = ex;
544 <        } finally {
545 <            onTermination(exception);
546 <        }
629 >        ForkJoinTask<?> t;
630 >        while (base != sp && (t = deqTask()) != null)
631 >            t.cancelIgnoringExceptions();
632      }
633  
634      /**
635 <     * Main top-level action.
635 >     * Drains tasks to given collection c
636 >     * @return the number of tasks drained
637       */
638 <    private void step() {
639 <        ForkJoinTask<?> t = sp != base? popTask() : null;
640 <        if (t != null || (t = scan(null, true)) != null) {
641 <            activate();
642 <            t.quietlyExec();
643 <        }
558 <        else {
559 <            inactivate();
560 <            eventCount = pool.sync(this, eventCount);
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  
564    // scanning for and stealing tasks
565
648      /**
649 <     * Computes next value for random victim probe. Scans don't
650 <     * require a very high quality generator, but also not a crummy
569 <     * one. Marsaglia xor-shift is cheap and works well.
570 <     *
571 <     * This is currently unused, and manually inlined
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 <    private static int xorShift(int r) {
653 <        r ^= r << 1;
654 <        r ^= r >>> 3;
655 <        r ^= r << 10;
577 <        return r;
652 >    final int getAndClearStealCount() {
653 >        int sc = stealCount;
654 >        stealCount = 0;
655 >        return sc;
656      }
657  
658      /**
659 <     * Tries to steal a task from another worker and/or, if enabled,
660 <     * submission queue. Starts at a random index of workers array,
661 <     * and probes workers until finding one with non-empty queue or
662 <     * finding that all are empty.  It randomly selects the first n-1
663 <     * probes. If these are empty, it resorts to full circular
664 <     * traversal, which is necessary to accurately set active status
665 <     * by caller. Also restarts if pool barrier has tripped since last
666 <     * scan, which forces refresh of workers array, in case barrier
667 <     * was associated with resize.
668 <     *
669 <     * This method must be both fast and quiet -- usually avoiding
670 <     * 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;
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              }
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            }
673          }
674 <        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;
666 <        }
667 <    }
668 <
669 <    // Support for ForkJoinTask methods
670 <
671 <    /**
672 <     * Implements ForkJoinTask.helpJoin
673 <     */
674 <    final int helpJoinTask(ForkJoinTask<?> joinMe) {
675 <        ForkJoinTask<?> t = null;
676 <        int s;
677 <        while ((s = joinMe.status) >= 0) {
678 <            if (t == null) {
679 <                if ((t = scan(joinMe, false)) == null)  // block if no work
680 <                    return joinMe.awaitDone(this, false);
681 <                // else recheck status before exec
682 <            }
683 <            else {
684 <                t.quietlyExec();
685 <                t = null;
686 <            }
687 <        }
688 <        if (t != null) // unsteal
689 <            pushTask(t);
690 <        return s;
691 <    }
692 <
693 <    /**
694 <     * Pops or steals a task
695 <     * @return task, or null if none available
696 <     */
697 <    final ForkJoinTask<?> getLocalOrStolenTask() {
698 <        ForkJoinTask<?> t = popTask();
699 <        return t != null? t : scan(null, false);
674 >        return false;
675      }
676  
677 <    /**
703 <     * Runs tasks until pool isQuiescent
704 <     */
705 <    final void helpQuiescePool() {
706 <        for (;;) {
707 <            ForkJoinTask<?> t = getLocalOrStolenTask();
708 <            if (t != null) {
709 <                activate();
710 <                t.quietlyExec();
711 <            }
712 <            else {
713 <                inactivate();
714 <                if (pool.isQuiescent()) {
715 <                    activate(); // re-activate on exit
716 <                    break;
717 <                }
718 <            }
719 <        }
720 <    }
677 >    // Support methods for ForkJoinTask
678  
679      /**
680       * Returns an estimate of the number of tasks in the queue.
681       */
682      final int getQueueSize() {
683 <        int b = base;
684 <        int n = sp - b;
728 <        return n <= 0? 0 : n; // suppress momentarily negative values
683 >        int n = sp - base;
684 >        return n < 0? 0 : n; // suppress momentarily negative values
685      }
686  
687      /**
# Line 733 | Line 689 | public class ForkJoinWorkerThread extend
689       * function of number of idle workers.
690       */
691      final int getEstimatedSurplusTaskCount() {
692 +        // The halving approximates weighting idle vs non-idle workers
693          return (sp - base) - (pool.getIdleThreadCount() >>> 1);
694      }
695  
739    // Per-worker exported random numbers
740
741    // Same constants as java.util.Random
742    final static long JURandomMultiplier = 0x5DEECE66DL;
743    final static long JURandomAddend = 0xBL;
744    final static long JURandomMask = (1L << 48) - 1;
745
746    private final int nextJURandom(int bits) {
747        long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) &
748            JURandomMask;
749        juRandomSeed = next;
750        return (int)(next >>> (48 - bits));
751    }
752
753    private final int nextJURandomInt(int n) {
754        if (n <= 0)
755            throw new IllegalArgumentException("n must be positive");
756        int bits = nextJURandom(31);
757        if ((n & -n) == n)
758            return (int)((n * (long)bits) >> 31);
759
760        for (;;) {
761            int val = bits % n;
762            if (bits - val + (n-1) >= 0)
763                return val;
764            bits = nextJURandom(31);
765        }
766    }
767
768    private final long nextJURandomLong() {
769        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
770    }
771
772    private final long nextJURandomLong(long n) {
773        if (n <= 0)
774            throw new IllegalArgumentException("n must be positive");
775        long offset = 0;
776        while (n >= Integer.MAX_VALUE) { // randomly pick half range
777            int bits = nextJURandom(2); // 2nd bit for odd vs even split
778            long half = n >>> 1;
779            long nextn = ((bits & 2) == 0)? half : n - half;
780            if ((bits & 1) == 0)
781                offset += n - nextn;
782            n = nextn;
783        }
784        return offset + nextJURandomInt((int)n);
785    }
786
787    private final double nextJURandomDouble() {
788        return (((long)(nextJURandom(26)) << 27) + nextJURandom(27))
789            / (double)(1L << 53);
790    }
791
696      /**
697 <     * Returns a random integer using a per-worker random
794 <     * number generator with the same properties as
795 <     * {@link java.util.Random#nextInt}
796 <     * @return the next pseudorandom, uniformly distributed {@code int}
797 <     *         value from this worker's random number generator's sequence
697 >     * Scan, returning early if joinMe done
698       */
699 <    public static int nextRandomInt() {
700 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
701 <            nextJURandom(32);
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 <     * Returns a random integer using a per-worker random
806 <     * number generator with the same properties as
807 <     * {@link java.util.Random#nextInt(int)}
808 <     * @param n the bound on the random number to be returned.  Must be
809 <     *        positive.
810 <     * @return the next pseudorandom, uniformly distributed {@code int}
811 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
812 <     *         from this worker's random number generator's sequence
813 <     * @throws IllegalArgumentException if n is not positive
709 >     * Runs tasks until pool isQuiescent
710       */
711 <    public static int nextRandomInt(int n) {
712 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
713 <            nextJURandomInt(n);
711 >    final void helpQuiescePool() {
712 >        for (;;) {
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 <    /**
723 <     * Returns a random long using a per-worker random
724 <     * number generator with the same properties as
725 <     * {@link java.util.Random#nextLong}
726 <     * @return the next pseudorandom, uniformly distributed {@code long}
727 <     *         value from this worker's random number generator's sequence
728 <     */
729 <    public static long nextRandomLong() {
730 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
731 <            nextJURandomLong();
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 >        }
737      }
738  
739 <    /**
740 <     * Returns a random integer using a per-worker random
741 <     * number generator with the same properties as
742 <     * {@link java.util.Random#nextInt(int)}
743 <     * @param n the bound on the random number to be returned.  Must be
837 <     *        positive.
838 <     * @return the next pseudorandom, uniformly distributed {@code int}
839 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
840 <     *         from this worker's random number generator's sequence
841 <     * @throws IllegalArgumentException if n is not positive
842 <     */
843 <    public static long nextRandomLong(long n) {
844 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
845 <            nextJURandomLong(n);
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 double using a per-worker random
748 <     * number generator with the same properties as
749 <     * {@link java.util.Random#nextDouble}
852 <     * @return the next pseudorandom, uniformly distributed {@code double}
853 <     *         value between {@code 0.0} and {@code 1.0} from this
854 <     *         worker's random number generator's sequence
855 <     */
856 <    public static double nextRandomDouble() {
857 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
858 <            nextJURandomDouble();
746 >    private static long fieldOffset(String fieldName)
747 >            throws NoSuchFieldException {
748 >        return _unsafe.objectFieldOffset
749 >            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
750      }
751  
861    // Temporary Unsafe mechanics for preliminary release
862
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;
868    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);
875 <            }
876 <            else
877 <                _unsafe = Unsafe.getUnsafe();
878 <            baseOffset = _unsafe.objectFieldOffset
879 <                (ForkJoinWorkerThread.class.getDeclaredField("base"));
880 <            spOffset = _unsafe.objectFieldOffset
881 <                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
882 <            runStateOffset = _unsafe.objectFieldOffset
883 <                (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