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

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.12 by jsr166, Tue Jul 21 18:11:44 2009 UTC

# Line 13 | Line 13 | import sun.misc.Unsafe;
13   import java.lang.reflect.*;
14  
15   /**
16 < * A thread that is internally managed by a ForkJoinPool to execute
17 < * ForkJoinTasks. This class additionally provides public
18 < * <tt>static</tt> methods accessing some basic scheduling and
19 < * execution mechanics for the <em>current</em>
20 < * ForkJoinWorkerThread. These methods may be invoked only from within
21 < * other ForkJoinTask computations. Attempts to invoke in other
22 < * contexts result in exceptions or errors including
23 < * ClassCastException.  These methods enable construction of
24 < * special-purpose task classes, as well as specialized idioms
25 < * occasionally useful in ForkJoinTask processing.
16 > * A thread managed by a {@link ForkJoinPool}.  This class is
17 > * subclassable solely for the sake of adding functionality -- there
18 > * are no overridable methods dealing with scheduling or
19 > * execution. However, you can override initialization and termination
20 > * methods surrounding the main task processing loop.  If you do
21 > * create such a subclass, you will also need to supply a custom
22 > * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
23   *
27 * <p>The form of supported static methods reflects the fact that
28 * worker threads may access and process tasks obtained in any of
29 * three ways. In preference order: <em>Local</em> tasks are processed
30 * in LIFO (newest first) order. <em>Stolen</em> tasks are obtained
31 * from other threads in FIFO (oldest first) order, only if there are
32 * no local tasks to run.  <em>Submissions</em> form a FIFO queue
33 * common to the entire pool, and are started only if no other
34 * work is available.
35 *
36 * <p> This class is subclassable solely for the sake of adding
37 * functionality -- there are no overridable methods dealing with
38 * scheduling or execution. However, you can override initialization
39 * and termination cleanup methods surrounding the main task
40 * processing loop.  If you do create such a subclass, you will also
41 * need to supply a custom ForkJoinWorkerThreadFactory to use it in a
42 * ForkJoinPool.
24   */
25   public class ForkJoinWorkerThread extends Thread {
26      /*
# Line 63 | 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 75 | 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 94 | 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 149 | Line 130 | public class ForkJoinWorkerThread extend
130  
131      /**
132       * Maximum work-stealing queue array size.  Must be less than or
133 <     * equal to 1 << 30 to ensure lack of index wraparound.
133 >     * equal to 1 << 28 to ensure lack of index wraparound. (This
134 >     * is less than usual bounds, because we need leftshift by 3
135 >     * to be in int range).
136       */
137 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30;
137 >    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
138  
139      /**
140 <     * Generator of seeds for per-thread random numbers.
140 >     * The pool this thread works in. Accessed directly by ForkJoinTask
141       */
142 <    private static final Random randomSeedGenerator = new Random();
142 >    final ForkJoinPool pool;
143  
144      /**
145       * The work-stealing queue array. Size must be a power of two.
146 +     * Initialized when thread starts, to improve memory locality.
147       */
148      private ForkJoinTask<?>[] queue;
149  
# Line 178 | Line 162 | public class ForkJoinWorkerThread extend
162      private volatile int base;
163  
164      /**
165 <     * The pool this thread works in.
166 <     */
167 <    final ForkJoinPool pool;
168 <
185 <    /**
186 <     * Index of this worker in pool array. Set once by pool before
187 <     * running, and accessed directly by pool during cleanup etc
165 >     * Activity status. When true, this worker is considered active.
166 >     * Must be false upon construction. It must be true when executing
167 >     * tasks, and BEFORE stealing a task. It must be false before
168 >     * calling pool.sync
169       */
170 <    int poolIndex;
170 >    private boolean active;
171  
172      /**
173       * Run state of this worker. Supports simple versions of the usual
# Line 194 | Line 175 | public class ForkJoinWorkerThread extend
175       */
176      private volatile int runState;
177  
197    // Runstate values. Order matters
198    private static final int RUNNING     = 0;
199    private static final int SHUTDOWN    = 1;
200    private static final int TERMINATING = 2;
201    private static final int TERMINATED  = 3;
202
178      /**
179 <     * Activity status. When true, this worker is considered active.
180 <     * Must be false upon construction. It must be true when executing
206 <     * tasks, and BEFORE stealing a task. It must be false before
207 <     * blocking on the Pool Barrier.
179 >     * Seed for random number generator for choosing steal victims.
180 >     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
181       */
182 <    private boolean active;
182 >    private int seed;
183  
184      /**
185       * Number of steals, transferred to pool when idle
# Line 214 | Line 187 | public class ForkJoinWorkerThread extend
187      private int stealCount;
188  
189      /**
190 <     * Seed for random number generator for choosing steal victims
190 >     * Index of this worker in pool array. Set once by pool before
191 >     * running, and accessed directly by pool during cleanup etc
192       */
193 <    private int randomVictimSeed;
193 >    int poolIndex;
194  
195      /**
196 <     * Seed for embedded Jurandom
196 >     * The last barrier event waited for. Accessed in pool callback
197 >     * methods, but only by current thread.
198       */
199 <    private long juRandomSeed;
199 >    long lastEventCount;
200  
201      /**
202 <     * The last barrier event waited for
202 >     * True if use local fifo, not default lifo, for local polling
203       */
204 <    private long eventCount;
204 >    private boolean locallyFifo;
205  
206      /**
207       * Creates a ForkJoinWorkerThread operating in the given pool.
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 <    //  Access methods used by Pool
219 >    // Public access methods
220  
221      /**
222 <     * Get and clear steal count for accumulation by pool.  Called
223 <     * only when known to be idle (in pool.sync and termination).
222 >     * Returns the pool hosting this thread.
223 >     *
224 >     * @return the pool
225       */
226 <    final int getAndClearStealCount() {
227 <        int sc = stealCount;
250 <        stealCount = 0;
251 <        return sc;
226 >    public ForkJoinPool getPool() {
227 >        return pool;
228      }
229  
230      /**
231 <     * Returns estimate of the number of tasks in the queue, without
232 <     * correcting for transient negative values
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 <    final int getRawQueueSize() {
240 <        return sp - base;
239 >    public int getPoolIndex() {
240 >        return poolIndex;
241      }
242  
243 <    // Intrinsics-based support for queue operations.
244 <    // Currently these three (setSp, setSlot, casSlotNull) are
245 <    // usually manually inlined to improve performance
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 <     * Sets sp in store-order.
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 void setSp(int s) {
285 <        _unsafe.putOrderedInt(this, spOffset, s);
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 <     * Add in store-order the given task at given slot of q to
295 <     * null. Caller must ensure q is nonnull and index is in range.
294 >     * Tries to set status to active; fails on contention.
295 >     */
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 >     * 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 >    private static int xorShift(int r) {
311 >        r ^= r << 1;
312 >        r ^= r >>> 3;
313 >        r ^= r << 10;
314 >        return r;
315 >    }
316 >
317 >    // Lifecycle methods
318 >
319 >    /**
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 >    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 >     * 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 309 | 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() {
315 <        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 327 | 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() {
334        ForkJoinTask<?> t;
335        int i;
336        ForkJoinTask<?>[] q = queue;
337        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 348 | 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)) {
360 <            _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 <    private ForkJoinTask<?> peekTask() {
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 395 | Line 543 | public class ForkJoinWorkerThread extend
543                  t = null;
544              setSlot(newQ, b & newMask, t);
545          } while (++b != bf);
546 <        pool.signalIdleWorkers(false);
399 <    }
400 <
401 <    // Runstate management
402 <
403 <    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
404 <    final boolean isTerminating() { return runState >= TERMINATING;  }
405 <    final boolean isTerminated()  { return runState == TERMINATED; }
406 <    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
407 <    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
408 <
409 <    /**
410 <     * Transition to at least the given state. Return true if not
411 <     * already at least given state.
412 <     */
413 <    private boolean transitionRunStateTo(int state) {
414 <        for (;;) {
415 <            int s = runState;
416 <            if (s >= state)
417 <                return false;
418 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
419 <                return true;
420 <        }
421 <    }
422 <
423 <    /**
424 <     * Ensure status is active and if necessary adjust pool active count
425 <     */
426 <    final void activate() {
427 <        if (!active) {
428 <            active = true;
429 <            pool.incrementActiveCount();
430 <        }
546 >        pool.signalWork();
547      }
548  
549      /**
550 <     * 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  
443    // Lifecycle methods
444
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.
449 <     * Initialization requires care: Most fields must have legal
450 <     * default values, to ensure that attempted accesses from other
451 <     * threads work correctly even before this thread starts
452 <     * processing tasks.
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];
459 <
460 <        // Heuristically allow one initial thread to warm up; others wait
461 <        if (poolIndex < pool.getParallelism() - 1) {
462 <            eventCount = pool.sync(this, 0);
463 <            activate();
464 <        }
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
469 <     * thread.  If you override this method, you must invoke
470 <     * 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
473 <     * to an unrecoverable error, or null if completed normally.
611 >     * @return a task, if available
612       */
613 <    protected void onTermination(Throwable exception) {
614 <        try {
477 <            clearLocalTasks();
478 <            inactivate();
479 <            cancelTasks();
480 <        } finally {
481 <            terminate(exception);
482 <        }
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)
495 <                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 <    /**
500 <     * Run local tasks on exit from main.
501 <     */
502 <    private void clearLocalTasks() {
503 <        while (base != sp && !pool.isTerminating()) {
504 <            ForkJoinTask<?> t = popTask();
505 <            if (t != null) {
506 <                activate(); // ensure active status
507 <                t.quietlyExec();
508 <            }
509 <        }
510 <    }
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)
520 <                t.cancelIgnoreExceptions();
521 <        }
522 <    }
523 <
524 <    /**
525 <     * This method is required to be public, but should never be
526 <     * called explicitly. It performs the main run loop to execute
527 <     * ForkJoinTasks.
528 <     */
529 <    public void run() {
530 <        Throwable exception = null;
531 <        try {
532 <            onStart();
533 <            while (!isShutdown())
534 <                step();
535 <        } catch (Throwable ex) {
536 <            exception = ex;
537 <        } finally {
538 <            onTermination(exception);
539 <        }
639 >        ForkJoinTask<?> t;
640 >        while (base != sp && (t = deqTask()) != null)
641 >            t.cancelIgnoringExceptions();
642      }
643  
644      /**
645 <     * Main top-level action.
645 >     * Drains tasks to given collection c.
646 >     *
647 >     * @return the number of tasks drained
648       */
649 <    private void step() {
650 <        ForkJoinTask<?> t = sp != base? popTask() : null;
651 <        if (t != null || (t = scan(null, true)) != null) {
652 <            activate();
653 <            t.quietlyExec();
654 <        }
551 <        else {
552 <            inactivate();
553 <            eventCount = pool.sync(this, eventCount);
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  
557    // scanning for and stealing tasks
558
659      /**
660 <     * Computes next value for random victim probe. Scans don't
661 <     * require a very high quality generator, but also not a crummy
562 <     * one. Marsaglia xor-shift is cheap and works well.
563 <     *
564 <     * This is currently unused, and manually inlined
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 static int xorShift(int r) {
664 <        r ^= r << 1;
665 <        r ^= r >>> 3;
666 <        r ^= r << 10;
570 <        return r;
663 >    final int getAndClearStealCount() {
664 >        int sc = stealCount;
665 >        stealCount = 0;
666 >        return sc;
667      }
668  
669      /**
670 <     * Tries to steal a task from another worker and/or, if enabled,
671 <     * submission queue. Starts at a random index of workers array,
672 <     * and probes workers until finding one with non-empty queue or
673 <     * finding that all are empty.  It randomly selects the first n-1
674 <     * probes. If these are empty, it resorts to full circular
675 <     * traversal, which is necessary to accurately set active status
676 <     * by caller. Also restarts if pool barrier has tripped since last
677 <     * scan, which forces refresh of workers array, in case barrier
678 <     * was associated with resize.
679 <     *
680 <     * This method must be both fast and quiet -- usually avoiding
681 <     * memory accesses that could disrupt cache sharing etc other than
586 <     * those needed to check for and take tasks. This accounts for,
587 <     * among other things, updating random seed in place without
588 <     * storing it until exit. (Note that we only need to store it if
589 <     * we found a task; otherwise it doesn't matter if we start at the
590 <     * same place next time.)
591 <     *
592 <     * @param joinMe if non null; exit early if done
593 <     * @param checkSubmissions true if OK to take submissions
594 <     * @return a task, or null if none found
595 <     */
596 <    private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe,
597 <                                 boolean checkSubmissions) {
598 <        ForkJoinPool p = pool;
599 <        if (p == null)                    // Never null, but avoids
600 <            return null;                  //   implicit nullchecks below
601 <        int r = randomVictimSeed;         // extract once to keep scan quiet
602 <        restart:                          // outer loop refreshes ws array
603 <        while (joinMe == null || joinMe.status >= 0) {
604 <            int mask;
605 <            ForkJoinWorkerThread[] ws = p.workers;
606 <            if (ws != null && (mask = ws.length - 1) > 0) {
607 <                int probes = -mask;       // use random index while negative
608 <                int idx = r;
609 <                for (;;) {
610 <                    ForkJoinWorkerThread v;
611 <                    // inlined xorshift to update seed
612 <                    r ^= r << 1;  r ^= r >>> 3; r ^= r << 10;
613 <                    if ((v = ws[mask & idx]) != null && v.sp != v.base) {
614 <                        ForkJoinTask<?> t;
615 <                        activate();
616 <                        if ((joinMe == null || joinMe.status >= 0) &&
617 <                            (t = v.deqTask()) != null) {
618 <                            randomVictimSeed = r;
619 <                            ++stealCount;
620 <                            return t;
621 <                        }
622 <                        continue restart; // restart on contention
623 <                    }
624 <                    if ((probes >> 1) <= mask) // n-1 random then circular
625 <                        idx = (probes++ < 0)? r : (idx + 1);
626 <                    else
627 <                        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              }
630            if (checkSubmissions && p.hasQueuedSubmissions()) {
631                activate();
632                ForkJoinTask<?> t = p.pollSubmission();
633                if (t != null)
634                    return t;
635            }
636            else {
637                long ec = eventCount;     // restart on pool event
638                if ((eventCount = p.getEventCount()) == ec)
639                    break;
640            }
641        }
642        return null;
643    }
644
645    /**
646     * Callback from pool.sync to rescan before blocking.  If a
647     * task is found, it is pushed so it can be executed upon return.
648     * @return true if found and pushed a task
649     */
650    final boolean prescan() {
651        ForkJoinTask<?> t = scan(null, true);
652        if (t != null) {
653            pushTask(t);
654            return true;
655        }
656        else {
657            inactivate();
658            return false;
659        }
660    }
661
662    /**
663     * Implements ForkJoinTask.helpJoin
664     */
665    final int helpJoinTask(ForkJoinTask<?> joinMe) {
666        ForkJoinTask<?> t = null;
667        int s;
668        while ((s = joinMe.status) >= 0) {
669            if (t == null) {
670                if ((t = scan(joinMe, false)) == null)  // block if no work
671                    return joinMe.awaitDone(this, false);
672                // else recheck status before exec
673            }
674            else {
675                t.quietlyExec();
676                t = null;
677            }
684          }
685 <        if (t != null) // unsteal
680 <            pushTask(t);
681 <        return s;
685 >        return false;
686      }
687  
688 <    // Support for public static and/or ForkJoinTask methods
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;
692 <        return n <= 0? 0 : n; // suppress momentarily negative values
693 <    }
694 <
695 <    /**
696 <     * Runs one popped task, if available
697 <     * @return true if ran a task
698 <     */
699 <    private boolean runLocalTask() {
700 <        ForkJoinTask<?> t = popTask();
701 <        if (t == null)
702 <            return false;
703 <        t.quietlyExec();
704 <        return true;
705 <    }
706 <
707 <    /**
708 <     * Pops or steals a task
709 <     * @return task, or null if none available
710 <     */
711 <    private ForkJoinTask<?> getLocalOrStolenTask() {
712 <        ForkJoinTask<?> t = popTask();
713 <        return t != null? t : scan(null, false);
714 <    }
715 <
716 <    /**
717 <     * Runs a popped or stolen task, if available
718 <     * @return true if ran a task
719 <     */
720 <    private boolean runLocalOrStolenTask() {
721 <        ForkJoinTask<?> t = getLocalOrStolenTask();
722 <        if (t == null)
723 <            return false;
724 <        t.quietlyExec();
725 <        return true;
726 <    }
727 <
728 <    /**
729 <     * Runs tasks until pool isQuiescent
730 <     */
731 <    final void helpQuiescePool() {
732 <        activate();
733 <        for (;;) {
734 <            if (!runLocalOrStolenTask()) {
735 <                inactivate();
736 <                if (pool.isQuiescent()) {
737 <                    activate(); // re-activate on exit
738 <                    break;
739 <                }
740 <            }
741 <        }
694 >        int n = sp - base;
695 >        return n < 0? 0 : n; // suppress momentarily negative values
696      }
697  
698      /**
# Line 746 | 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  
752    // Public methods on current thread
753
707      /**
708 <     * Returns the pool hosting the current task execution.
756 <     * @return the pool
708 >     * Scans, returning early if joinMe done
709       */
710 <    public static ForkJoinPool getPool() {
711 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pool;
712 <    }
713 <
714 <    /**
715 <     * Returns the index number of the current worker thread in its
716 <     * pool.  The returned value ranges from zero to the maximum
765 <     * number of threads (minus one) that have ever been created in
766 <     * the pool.  This method may be useful for applications that
767 <     * track status or collect results per-worker rather than
768 <     * per-task.
769 <     * @return the index number.
770 <     */
771 <    public static int getPoolIndex() {
772 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex;
773 <    }
774 <
775 <    /**
776 <     * Returns an estimate of the number of tasks waiting to be run by
777 <     * the current worker thread. This value may be useful for
778 <     * heuristic decisions about whether to fork other tasks.
779 <     * @return the number of tasks
780 <     */
781 <    public static int getLocalQueueSize() {
782 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
783 <            getQueueSize();
784 <    }
785 <
786 <    /**
787 <     * Returns, but does not remove or execute, the next task locally
788 <     * queued for execution by the current worker thread. There is no
789 <     * guarantee that this task will be the next one actually returned
790 <     * or executed from other polling or execution methods.
791 <     * @return the next task or null if none
792 <     */
793 <    public static ForkJoinTask<?> peekLocalTask() {
794 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
795 <    }
796 <
797 <    /**
798 <     * Removes and returns, without executing, the next task queued
799 <     * for execution in the current worker thread's local queue.
800 <     * @return the next task to execute, or null if none
801 <     */
802 <    public static ForkJoinTask<?> pollLocalTask() {
803 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask();
804 <    }
805 <
806 <    /**
807 <     * Execute the next task locally queued by the current worker, if
808 <     * one is available.
809 <     * @return true if a task was run; a false return indicates
810 <     * that no task was available.
811 <     */
812 <    public static boolean executeLocalTask() {
813 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
814 <            runLocalTask();
815 <    }
816 <
817 <    /**
818 <     * Removes and returns, without executing, the next task queued
819 <     * for execution in the current worker thread's local queue or if
820 <     * none, a task stolen from another worker, if one is available.
821 <     * A null return does not necessarily imply that all tasks are
822 <     * completed, only that there are currently none available.
823 <     * @return the next task to execute, or null if none
824 <     */
825 <    public static ForkJoinTask<?> pollTask() {
826 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
827 <            getLocalOrStolenTask();
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 <     * Helps this program complete by processing a local or stolen
832 <     * task, if one is available.  This method may be useful when
833 <     * several tasks are forked, and only one of them must be joined,
834 <     * as in:
835 <     *
836 <     * <pre>
837 <     *   while (!t1.isDone() &amp;&amp; !t2.isDone())
838 <     *     ForkJoinWorkerThread.executeTask();
839 <     * </pre>
840 <     *
841 <     * @return true if a task was run; a false return indicates
842 <     * that no task was available.
720 >     * Runs tasks until pool isQuiescent.
721       */
722 <    public static boolean executeTask() {
845 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
846 <            runLocalOrStolenTask();
847 <    }
848 <
849 <    // Per-worker exported random numbers
850 <
851 <    // Same constants as java.util.Random
852 <    final static long JURandomMultiplier = 0x5DEECE66DL;
853 <    final static long JURandomAddend = 0xBL;
854 <    final static long JURandomMask = (1L << 48) - 1;
855 <
856 <    private final int nextJURandom(int bits) {
857 <        long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) &
858 <            JURandomMask;
859 <        juRandomSeed = next;
860 <        return (int)(next >>> (48 - bits));
861 <    }
862 <
863 <    private final int nextJURandomInt(int n) {
864 <        if (n <= 0)
865 <            throw new IllegalArgumentException("n must be positive");
866 <        int bits = nextJURandom(31);
867 <        if ((n & -n) == n)
868 <            return (int)((n * (long)bits) >> 31);
869 <
722 >    final void helpQuiescePool() {
723          for (;;) {
724 <            int val = bits % n;
725 <            if (bits - val + (n-1) >= 0)
726 <                return val;
727 <            bits = nextJURandom(31);
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 <    private final long nextJURandomLong() {
734 <        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
735 <    }
736 <
737 <    private final long nextJURandomLong(long n) {
738 <        if (n <= 0)
739 <            throw new IllegalArgumentException("n must be positive");
740 <        long offset = 0;
741 <        while (n >= Integer.MAX_VALUE) { // randomly pick half range
742 <            int bits = nextJURandom(2); // 2nd bit for odd vs even split
743 <            long half = n >>> 1;
744 <            long nextn = ((bits & 2) == 0)? half : n - half;
745 <            if ((bits & 1) == 0)
746 <                offset += n - nextn;
892 <            n = nextn;
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          }
894        return offset + nextJURandomInt((int)n);
748      }
749  
750 <    private final double nextJURandomDouble() {
751 <        return (((long)(nextJURandom(26)) << 27) + nextJURandom(27))
752 <            / (double)(1L << 53);
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 integer using a per-worker random
759 <     * number generator with the same properties as
760 <     * {@link java.util.Random#nextInt}
906 <     * @return the next pseudorandom, uniformly distributed {@code int}
907 <     *         value from this worker's random number generator's sequence
908 <     */
909 <    public static int nextRandomInt() {
910 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
911 <            nextJURandom(32);
757 >    private static long fieldOffset(String fieldName)
758 >            throws NoSuchFieldException {
759 >        return UNSAFE.objectFieldOffset
760 >            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
761      }
762  
763 <    /**
915 <     * Returns a random integer using a per-worker random
916 <     * number generator with the same properties as
917 <     * {@link java.util.Random#nextInt(int)}
918 <     * @param n the bound on the random number to be returned.  Must be
919 <     *        positive.
920 <     * @return the next pseudorandom, uniformly distributed {@code int}
921 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
922 <     *         from this worker's random number generator's sequence
923 <     * @throws IllegalArgumentException if n is not positive
924 <     */
925 <    public static int nextRandomInt(int n) {
926 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
927 <            nextJURandomInt(n);
928 <    }
929 <
930 <    /**
931 <     * Returns a random long using a per-worker random
932 <     * number generator with the same properties as
933 <     * {@link java.util.Random#nextLong}
934 <     * @return the next pseudorandom, uniformly distributed {@code long}
935 <     *         value from this worker's random number generator's sequence
936 <     */
937 <    public static long nextRandomLong() {
938 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
939 <            nextJURandomLong();
940 <    }
941 <
942 <    /**
943 <     * Returns a random integer using a per-worker random
944 <     * number generator with the same properties as
945 <     * {@link java.util.Random#nextInt(int)}
946 <     * @param n the bound on the random number to be returned.  Must be
947 <     *        positive.
948 <     * @return the next pseudorandom, uniformly distributed {@code int}
949 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
950 <     *         from this worker's random number generator's sequence
951 <     * @throws IllegalArgumentException if n is not positive
952 <     */
953 <    public static long nextRandomLong(long n) {
954 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
955 <            nextJURandomLong(n);
956 <    }
957 <
958 <    /**
959 <     * Returns a random double using a per-worker random
960 <     * number generator with the same properties as
961 <     * {@link java.util.Random#nextDouble}
962 <     * @return the next pseudorandom, uniformly distributed {@code double}
963 <     *         value between {@code 0.0} and {@code 1.0} from this
964 <     *         worker's random number generator's sequence
965 <     */
966 <    public static double nextRandomDouble() {
967 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
968 <            nextJURandomDouble();
969 <    }
970 <
971 <    // Temporary Unsafe mechanics for preliminary release
972 <
973 <    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;
978    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
987 <                _unsafe = Unsafe.getUnsafe();
988 <            baseOffset = _unsafe.objectFieldOffset
989 <                (ForkJoinWorkerThread.class.getDeclaredField("base"));
990 <            spOffset = _unsafe.objectFieldOffset
991 <                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
992 <            runStateOffset = _unsafe.objectFieldOffset
993 <                (ForkJoinWorkerThread.class.getDeclaredField("runState"));
994 <            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
995 <            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