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

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.4 by dl, Wed Jan 7 20:51:36 2009 UTC vs.
Revision 1.19 by jsr166, Sun Jul 26 05:55:34 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import java.util.concurrent.locks.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
10 >
11 > import java.util.Collection;
12  
13   /**
14   * A thread managed by a {@link ForkJoinPool}.  This class is
15   * subclassable solely for the sake of adding functionality -- there
16   * are no overridable methods dealing with scheduling or
17   * execution. However, you can override initialization and termination
18 < * cleanup methods surrounding the main task processing loop.  If you
19 < * do create such a subclass, you will also need to supply a custom
18 > * methods surrounding the main task processing loop.  If you do
19 > * create such a subclass, you will also need to supply a custom
20   * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
21 < *
22 < * <p>This class also provides methods for generating per-thread
23 < * random numbers, with the same properties as {@link
26 < * java.util.Random} but with each generator isolated from those of
27 < * other threads.
21 > *
22 > * @since 1.7
23 > * @author Doug Lea
24   */
25   public class ForkJoinWorkerThread extends Thread {
26      /*
# Line 48 | Line 44 | public class ForkJoinWorkerThread extend
44       * of tasks. To accomplish this, we shift the CAS arbitrating pop
45       * vs deq (steal) from being on the indices ("base" and "sp") to
46       * the slots themselves (mainly via method "casSlotNull()"). So,
47 <     * both a successful pop and deq mainly entail CAS'ing a nonnull
47 >     * both a successful pop and deq mainly entail CAS'ing a non-null
48       * slot to null.  Because we rely on CASes of references, we do
49       * not need tag bits on base or sp.  They are simple ints as used
50       * in any circular array-based queue (see for example ArrayDeque).
# Line 60 | Line 56 | public class ForkJoinWorkerThread extend
56       * considered individually, is not wait-free. One thief cannot
57       * successfully continue until another in-progress one (or, if
58       * previously empty, a push) completes.  However, in the
59 <     * aggregate, we ensure at least probablistic non-blockingness. If
59 >     * aggregate, we ensure at least probabilistic non-blockingness. If
60       * an attempted steal fails, a thief always chooses a different
61       * random victim target to try next. So, in order for one thief to
62       * progress, it suffices for any in-progress deq or new push on
# Line 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 this thread
222 >     * Returns the pool hosting this thread.
223 >     *
224       * @return the pool
225       */
226      public ForkJoinPool getPool() {
# Line 239 | Line 232 | public class ForkJoinWorkerThread extend
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 on a per-worker basis.
236 <     * @return the index number.
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 <    //  Access methods used by Pool
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 >     * Transitions to at least the given state.  Returns true if not
269 >     * already at least at given state.
270 >     */
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 >    /**
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 inactive; 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 <    private void setSp(int s) {
360 <        _unsafe.putOrderedInt(this, spOffset, s);
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 >     * {@code 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 >    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);
411 >                                ForkJoinTask<?> 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.cancelIgnoringExceptions();
528 <        }
639 >        ForkJoinTask<?> t;
640 >        while (base != sp && (t = deqTask()) != null)
641 >            t.cancelIgnoringExceptions();
642      }
643  
644      /**
645 <     * This method is required to be public, but should never be
646 <     * called explicitly. It performs the main run loop to execute
647 <     * ForkJoinTasks.
645 >     * Drains tasks to given collection c.
646 >     *
647 >     * @return the number of tasks drained
648       */
649 <    public void run() {
650 <        Throwable exception = null;
651 <        try {
652 <            onStart();
653 <            while (!isShutdown())
654 <                step();
542 <        } catch (Throwable ex) {
543 <            exception = ex;
544 <        } finally {
545 <            onTermination(exception);
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 +        return n;
657      }
658  
659      /**
660 <     * Main top-level action.
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 <    private void step() {
664 <        ForkJoinTask<?> t = sp != base? popTask() : null;
665 <        if (t != null || (t = scan(null, true)) != null) {
666 <            activate();
556 <            t.quietlyExec();
557 <        }
558 <        else {
559 <            inactivate();
560 <            eventCount = pool.sync(this, eventCount);
561 <        }
663 >    final int getAndClearStealCount() {
664 >        int sc = stealCount;
665 >        stealCount = 0;
666 >        return sc;
667      }
668  
564    // scanning for and stealing tasks
565
669      /**
670 <     * Computes next value for random victim probe. Scans don't
671 <     * require a very high quality generator, but also not a crummy
569 <     * one. Marsaglia xor-shift is cheap and works well.
670 >     * Returns true if at least one worker in the given array appears
671 >     * to have at least one queued task.
672       *
673 <     * This is currently unused, and manually inlined
673 >     * @param ws array of workers
674       */
675 <    private static int xorShift(int r) {
676 <        r ^= r << 1;
677 <        r ^= r >>> 3;
678 <        r ^= r << 10;
679 <        return r;
680 <    }
681 <
682 <    /**
581 <     * Tries to steal a task from another worker and/or, if enabled,
582 <     * submission queue. Starts at a random index of workers array,
583 <     * and probes workers until finding one with non-empty queue or
584 <     * finding that all are empty.  It randomly selects the first n-1
585 <     * probes. If these are empty, it resorts to full circular
586 <     * traversal, which is necessary to accurately set active status
587 <     * by caller. Also restarts if pool barrier has tripped since last
588 <     * scan, which forces refresh of workers array, in case barrier
589 <     * was associated with resize.
590 <     *
591 <     * This method must be both fast and quiet -- usually avoiding
592 <     * memory accesses that could disrupt cache sharing etc other than
593 <     * those needed to check for and take tasks. This accounts for,
594 <     * among other things, updating random seed in place without
595 <     * storing it until exit. (Note that we only need to store it if
596 <     * we found a task; otherwise it doesn't matter if we start at the
597 <     * same place next time.)
598 <     *
599 <     * @param joinMe if non null; exit early if done
600 <     * @param checkSubmissions true if OK to take submissions
601 <     * @return a task, or null if none found
602 <     */
603 <    private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe,
604 <                                 boolean checkSubmissions) {
605 <        ForkJoinPool p = pool;
606 <        if (p == null)                    // Never null, but avoids
607 <            return null;                  //   implicit nullchecks below
608 <        int r = randomVictimSeed;         // extract once to keep scan quiet
609 <        restart:                          // outer loop refreshes ws array
610 <        while (joinMe == null || joinMe.status >= 0) {
611 <            int mask;
612 <            ForkJoinWorkerThread[] ws = p.workers;
613 <            if (ws != null && (mask = ws.length - 1) > 0) {
614 <                int probes = -mask;       // use random index while negative
615 <                int idx = r;
616 <                for (;;) {
617 <                    ForkJoinWorkerThread v;
618 <                    // inlined xorshift to update seed
619 <                    r ^= r << 1;  r ^= r >>> 3; r ^= r << 10;
620 <                    if ((v = ws[mask & idx]) != null && v.sp != v.base) {
621 <                        ForkJoinTask<?> t;
622 <                        activate();
623 <                        if ((joinMe == null || joinMe.status >= 0) &&
624 <                            (t = v.deqTask()) != null) {
625 <                            randomVictimSeed = r;
626 <                            ++stealCount;
627 <                            return t;
628 <                        }
629 <                        continue restart; // restart on contention
630 <                    }
631 <                    if ((probes >> 1) <= mask) // n-1 random then circular
632 <                        idx = (probes++ < 0)? r : (idx + 1);
633 <                    else
634 <                        break;
675 >    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
676 >        if (ws != null) {
677 >            int len = ws.length;
678 >            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
679 >                for (int i = 0; i < len; ++i) {
680 >                    ForkJoinWorkerThread w = ws[i];
681 >                    if (w != null && w.sp != w.base)
682 >                        return true;
683                  }
684              }
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;
685          }
686 +        return false;
687      }
688  
689 <    // Support for ForkJoinTask methods
670 <
671 <    /**
672 <     * Scan, returning early if joinMe done
673 <     */
674 <    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
675 <        ForkJoinTask<?> t = scan(joinMe, false);
676 <        if (t != null && joinMe.status < 0 && sp == base) {
677 <            pushTask(t); // unsteal if done and this task would be stealable
678 <            t = null;
679 <        }
680 <        return t;
681 <    }
682 <    
683 <    /**
684 <     * Pops or steals a task
685 <     * @return task, or null if none available
686 <     */
687 <    final ForkJoinTask<?> pollLocalOrStolenTask() {
688 <        ForkJoinTask<?> t;
689 <        return (t = popTask()) == null? scan(null, false) : t;
690 <    }
691 <
692 <    /**
693 <     * Runs tasks until pool isQuiescent
694 <     */
695 <    final void helpQuiescePool() {
696 <        for (;;) {
697 <            ForkJoinTask<?> t = pollLocalOrStolenTask();
698 <            if (t != null) {
699 <                activate();
700 <                t.quietlyExec();
701 <            }
702 <            else {
703 <                inactivate();
704 <                if (pool.isQuiescent()) {
705 <                    activate(); // re-activate on exit
706 <                    break;
707 <                }
708 <            }
709 <        }
710 <    }
689 >    // Support methods for ForkJoinTask
690  
691      /**
692       * Returns an estimate of the number of tasks in the queue.
693       */
694      final int getQueueSize() {
695 <        int n = sp - base;
696 <        return n <= 0? 0 : n; // suppress momentarily negative values
695 >        // suppress momentarily negative values
696 >        return Math.max(0, sp - base);
697      }
698  
699      /**
# Line 726 | Line 705 | public class ForkJoinWorkerThread extend
705          return (sp - base) - (pool.getIdleThreadCount() >>> 1);
706      }
707  
729    // Per-worker exported random numbers
730
731    // Same constants as java.util.Random
732    final static long JURandomMultiplier = 0x5DEECE66DL;
733    final static long JURandomAddend = 0xBL;
734    final static long JURandomMask = (1L << 48) - 1;
735
736    private final int nextJURandom(int bits) {
737        long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) &
738            JURandomMask;
739        juRandomSeed = next;
740        return (int)(next >>> (48 - bits));
741    }
742
743    private final int nextJURandomInt(int n) {
744        if (n <= 0)
745            throw new IllegalArgumentException("n must be positive");
746        int bits = nextJURandom(31);
747        if ((n & -n) == n)
748            return (int)((n * (long)bits) >> 31);
749
750        for (;;) {
751            int val = bits % n;
752            if (bits - val + (n-1) >= 0)
753                return val;
754            bits = nextJURandom(31);
755        }
756    }
757
758    private final long nextJURandomLong() {
759        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
760    }
761
762    private final long nextJURandomLong(long n) {
763        if (n <= 0)
764            throw new IllegalArgumentException("n must be positive");
765        long offset = 0;
766        while (n >= Integer.MAX_VALUE) { // randomly pick half range
767            int bits = nextJURandom(2); // 2nd bit for odd vs even split
768            long half = n >>> 1;
769            long nextn = ((bits & 2) == 0)? half : n - half;
770            if ((bits & 1) == 0)
771                offset += n - nextn;
772            n = nextn;
773        }
774        return offset + nextJURandomInt((int)n);
775    }
776
777    private final double nextJURandomDouble() {
778        return (((long)(nextJURandom(26)) << 27) + nextJURandom(27))
779            / (double)(1L << 53);
780    }
781
708      /**
709 <     * Returns a random integer using a per-worker random
784 <     * number generator with the same properties as
785 <     * {@link java.util.Random#nextInt}
786 <     * @return the next pseudorandom, uniformly distributed {@code int}
787 <     *         value from this worker's random number generator's sequence
709 >     * Scans, returning early if joinMe done.
710       */
711 <    public static int nextRandomInt() {
712 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
713 <            nextJURandom(32);
711 >    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
712 >        ForkJoinTask<?> t = pollTask();
713 >        if (t != null && joinMe.status < 0 && sp == base) {
714 >            pushTask(t); // unsteal if done and this task would be stealable
715 >            t = null;
716 >        }
717 >        return t;
718      }
719  
720      /**
721 <     * Returns a random integer using a per-worker random
796 <     * number generator with the same properties as
797 <     * {@link java.util.Random#nextInt(int)}
798 <     * @param n the bound on the random number to be returned.  Must be
799 <     *        positive.
800 <     * @return the next pseudorandom, uniformly distributed {@code int}
801 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
802 <     *         from this worker's random number generator's sequence
803 <     * @throws IllegalArgumentException if n is not positive
721 >     * Runs tasks until {@code pool.isQuiescent()}.
722       */
723 <    public static int nextRandomInt(int n) {
724 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
725 <            nextJURandomInt(n);
723 >    final void helpQuiescePool() {
724 >        for (;;) {
725 >            ForkJoinTask<?> t = pollTask();
726 >            if (t != null)
727 >                t.quietlyExec();
728 >            else if (tryInactivate() && pool.isQuiescent())
729 >                break;
730 >        }
731 >        do {} while (!tryActivate()); // re-activate on exit
732      }
733  
734 <    /**
735 <     * Returns a random long using a per-worker random
736 <     * number generator with the same properties as
737 <     * {@link java.util.Random#nextLong}
738 <     * @return the next pseudorandom, uniformly distributed {@code long}
739 <     *         value from this worker's random number generator's sequence
740 <     */
741 <    public static long nextRandomLong() {
742 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
743 <            nextJURandomLong();
734 >    // Unsafe mechanics for jsr166y 3rd party package.
735 >    private static sun.misc.Unsafe getUnsafe() {
736 >        try {
737 >            return sun.misc.Unsafe.getUnsafe();
738 >        } catch (SecurityException se) {
739 >            try {
740 >                return java.security.AccessController.doPrivileged
741 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
742 >                        public sun.misc.Unsafe run() throws Exception {
743 >                            return getUnsafeByReflection();
744 >                        }});
745 >            } catch (java.security.PrivilegedActionException e) {
746 >                throw new RuntimeException("Could not initialize intrinsics",
747 >                                           e.getCause());
748 >            }
749 >        }
750      }
751  
752 <    /**
753 <     * Returns a random integer using a per-worker random
754 <     * number generator with the same properties as
755 <     * {@link java.util.Random#nextInt(int)}
756 <     * @param n the bound on the random number to be returned.  Must be
757 <     *        positive.
828 <     * @return the next pseudorandom, uniformly distributed {@code int}
829 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
830 <     *         from this worker's random number generator's sequence
831 <     * @throws IllegalArgumentException if n is not positive
832 <     */
833 <    public static long nextRandomLong(long n) {
834 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
835 <            nextJURandomLong(n);
752 >    private static sun.misc.Unsafe getUnsafeByReflection()
753 >            throws NoSuchFieldException, IllegalAccessException {
754 >        java.lang.reflect.Field f =
755 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
756 >        f.setAccessible(true);
757 >        return (sun.misc.Unsafe) f.get(null);
758      }
759  
760 <    /**
761 <     * Returns a random double using a per-worker random
762 <     * number generator with the same properties as
763 <     * {@link java.util.Random#nextDouble}
764 <     * @return the next pseudorandom, uniformly distributed {@code double}
765 <     *         value between {@code 0.0} and {@code 1.0} from this
766 <     *         worker's random number generator's sequence
767 <     */
768 <    public static double nextRandomDouble() {
847 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
848 <            nextJURandomDouble();
760 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
761 >        try {
762 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
763 >        } catch (NoSuchFieldException e) {
764 >            // Convert Exception to Error
765 >            NoSuchFieldError error = new NoSuchFieldError(fieldName);
766 >            error.initCause(e);
767 >            throw error;
768 >        }
769      }
770  
771 <    // Temporary Unsafe mechanics for preliminary release
771 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
772 >    private static final long spOffset =
773 >        fieldOffset("sp", ForkJoinWorkerThread.class);
774 >    private static final long runStateOffset =
775 >        fieldOffset("runState", ForkJoinWorkerThread.class);
776 >    private static final long qBase;
777 >    private static final int qShift;
778  
853    static final Unsafe _unsafe;
854    static final long baseOffset;
855    static final long spOffset;
856    static final long qBase;
857    static final int qShift;
858    static final long runStateOffset;
779      static {
780 <        try {
781 <            if (ForkJoinWorkerThread.class.getClassLoader() != null) {
782 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
783 <                f.setAccessible(true);
784 <                _unsafe = (Unsafe)f.get(null);
865 <            }
866 <            else
867 <                _unsafe = Unsafe.getUnsafe();
868 <            baseOffset = _unsafe.objectFieldOffset
869 <                (ForkJoinWorkerThread.class.getDeclaredField("base"));
870 <            spOffset = _unsafe.objectFieldOffset
871 <                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
872 <            runStateOffset = _unsafe.objectFieldOffset
873 <                (ForkJoinWorkerThread.class.getDeclaredField("runState"));
874 <            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
875 <            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
876 <            if ((s & (s-1)) != 0)
877 <                throw new Error("data type scale not a power of two");
878 <            qShift = 31 - Integer.numberOfLeadingZeros(s);
879 <        } catch (Exception e) {
880 <            throw new RuntimeException("Could not initialize intrinsics", e);
881 <        }
780 >        qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
781 >        int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
782 >        if ((s & (s-1)) != 0)
783 >            throw new Error("data type scale not a power of two");
784 >        qShift = 31 - Integer.numberOfLeadingZeros(s);
785      }
786   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines