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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines