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.8 by jsr166, Mon Jul 20 21:45:06 2009 UTC vs.
Revision 1.26 by dl, Sun Aug 2 11:54:31 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 < * 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.
16 > * are no overridable methods dealing with scheduling or execution.
17 > * However, you can override initialization and termination methods
18 > * surrounding the main task processing loop.  If you do create such a
19 > * subclass, you will also need to supply a custom {@link
20 > * ForkJoinPool.ForkJoinWorkerThreadFactory} to use it in a {@code
21 > * ForkJoinPool}.
22   *
23 + * @since 1.7
24 + * @author Doug Lea
25   */
26   public class ForkJoinWorkerThread extends Thread {
27      /*
# Line 44 | Line 45 | public class ForkJoinWorkerThread extend
45       * of tasks. To accomplish this, we shift the CAS arbitrating pop
46       * vs deq (steal) from being on the indices ("base" and "sp") to
47       * the slots themselves (mainly via method "casSlotNull()"). So,
48 <     * both a successful pop and deq mainly entail CAS'ing a nonnull
48 >     * both a successful pop and deq mainly entail CAS'ing a non-null
49       * slot to null.  Because we rely on CASes of references, we do
50       * not need tag bits on base or sp.  They are simple ints as used
51       * in any circular array-based queue (see for example ArrayDeque).
# Line 56 | Line 57 | public class ForkJoinWorkerThread extend
57       * considered individually, is not wait-free. One thief cannot
58       * successfully continue until another in-progress one (or, if
59       * previously empty, a push) completes.  However, in the
60 <     * aggregate, we ensure at least probablistic non-blockingness. If
60 >     * aggregate, we ensure at least probabilistic non-blockingness. If
61       * an attempted steal fails, a thief always chooses a different
62       * random victim target to try next. So, in order for one thief to
63       * progress, it suffices for any in-progress deq or new push on
# Line 65 | Line 66 | public class ForkJoinWorkerThread extend
66       * which gives threads a chance to activate if necessary before
67       * stealing (see below).
68       *
69 +     * This approach also enables support for "async mode" where local
70 +     * task processing is in FIFO, not LIFO order; simply by using a
71 +     * version of deq rather than pop when locallyFifo is true (as set
72 +     * by the ForkJoinPool).  This allows use in message-passing
73 +     * frameworks in which tasks are never joined.
74 +     *
75       * Efficient implementation of this approach currently relies on
76       * an uncomfortable amount of "Unsafe" mechanics. To maintain
77       * correct orderings, reads and writes of variable base require
# Line 75 | Line 82 | public class ForkJoinWorkerThread extend
82       * push) require store order and CASes (in pop and deq) require
83       * (volatile) CAS semantics. Since these combinations aren't
84       * supported using ordinary volatiles, the only way to accomplish
85 <     * these effciently is to use direct Unsafe calls. (Using external
85 >     * these efficiently is to use direct Unsafe calls. (Using external
86       * AtomicIntegers and AtomicReferenceArrays for the indices and
87       * array is significantly slower because of memory locality and
88       * indirection effects.) Further, performance on most platforms is
# Line 137 | Line 144 | public class ForkJoinWorkerThread extend
144      private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
145  
146      /**
147 <     * The pool this thread works in. Accessed directly by ForkJoinTask
147 >     * The pool this thread works in. Accessed directly by ForkJoinTask.
148       */
149      final ForkJoinPool pool;
150  
# Line 165 | Line 172 | public class ForkJoinWorkerThread extend
172       * Activity status. When true, this worker is considered active.
173       * Must be false upon construction. It must be true when executing
174       * tasks, and BEFORE stealing a task. It must be false before
175 <     * calling pool.sync
175 >     * calling pool.sync.
176       */
177      private boolean active;
178  
# Line 188 | Line 195 | public class ForkJoinWorkerThread extend
195  
196      /**
197       * Index of this worker in pool array. Set once by pool before
198 <     * running, and accessed directly by pool during cleanup etc
198 >     * running, and accessed directly by pool during cleanup etc.
199       */
200      int poolIndex;
201  
# Line 205 | Line 212 | public class ForkJoinWorkerThread extend
212  
213      /**
214       * Creates a ForkJoinWorkerThread operating in the given pool.
215 +     *
216       * @param pool the pool this thread works in
217       * @throws NullPointerException if pool is null
218       */
# Line 218 | Line 226 | public class ForkJoinWorkerThread extend
226      // Public access methods
227  
228      /**
229 <     * Returns the pool hosting this thread
229 >     * Returns the pool hosting this thread.
230 >     *
231       * @return the pool
232       */
233      public ForkJoinPool getPool() {
# Line 231 | Line 240 | public class ForkJoinWorkerThread extend
240       * threads (minus one) that have ever been created in the pool.
241       * This method may be useful for applications that track status or
242       * collect results per-worker rather than per-task.
243 <     * @return the index number.
243 >     *
244 >     * @return the index number
245       */
246      public int getPoolIndex() {
247          return poolIndex;
# Line 240 | Line 250 | public class ForkJoinWorkerThread extend
250      /**
251       * Establishes local first-in-first-out scheduling mode for forked
252       * tasks that are never joined.
253 +     *
254       * @param async if true, use locally FIFO scheduling
255       */
256      void setAsyncMode(boolean async) {
# Line 261 | Line 272 | public class ForkJoinWorkerThread extend
272      final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
273  
274      /**
275 <     * Transition to at least the given state. Return true if not
276 <     * already at least given state.
275 >     * Transitions to at least the given state.
276 >     *
277 >     * @return {@code true} if not already at least at given state
278       */
279      private boolean transitionRunStateTo(int state) {
280          for (;;) {
281              int s = runState;
282              if (s >= state)
283                  return false;
284 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
284 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, state))
285                  return true;
286          }
287      }
288  
289      /**
290 <     * Try to set status to active; fail on contention
290 >     * Tries to set status to active; fails on contention.
291       */
292      private boolean tryActivate() {
293          if (!active) {
# Line 287 | Line 299 | public class ForkJoinWorkerThread extend
299      }
300  
301      /**
302 <     * Try to set status to active; fail on contention
302 >     * Tries to set status to inactive; fails on contention.
303       */
304      private boolean tryInactivate() {
305          if (active) {
# Line 299 | Line 311 | public class ForkJoinWorkerThread extend
311      }
312  
313      /**
314 <     * Computes next value for random victim probe. Scans don't
314 >     * Computes next value for random victim probe.  Scans don't
315       * require a very high quality generator, but also not a crummy
316 <     * one. Marsaglia xor-shift is cheap and works well.
316 >     * one.  Marsaglia xor-shift is cheap and works well.
317       */
318      private static int xorShift(int r) {
319 <        r ^= r << 1;
320 <        r ^= r >>> 3;
321 <        r ^= r << 10;
310 <        return r;
319 >        r ^= (r << 13);
320 >        r ^= (r >>> 17);
321 >        return r ^ (r << 5);
322      }
323  
324      // Lifecycle methods
# Line 331 | Line 342 | public class ForkJoinWorkerThread extend
342      }
343  
344      /**
345 <     * Execute tasks until shut down.
345 >     * Executes tasks until shut down.
346       */
347      private void mainLoop() {
348          while (!isShutdown()) {
# Line 363 | Line 374 | public class ForkJoinWorkerThread extend
374      }
375  
376      /**
377 <     * Perform cleanup associated with termination of this worker
377 >     * Performs cleanup associated with termination of this worker
378       * thread.  If you override this method, you must invoke
379 <     * super.onTermination at the end of the overridden method.
379 >     * {@code super.onTermination} at the end of the overridden method.
380       *
381       * @param exception the exception causing this thread to abort due
382 <     * to an unrecoverable error, or null if completed normally.
382 >     * to an unrecoverable error, or {@code null} if completed normally
383       */
384      protected void onTermination(Throwable exception) {
385          // Execute remaining local tasks unless aborting or terminating
# Line 377 | Line 388 | public class ForkJoinWorkerThread extend
388                  ForkJoinTask<?> t = popTask();
389                  if (t != null)
390                      t.quietlyExec();
391 <            } catch(Throwable ex) {
391 >            } catch (Throwable ex) {
392                  exception = ex;
393              }
394          }
395          // Cancel other tasks, transition status, notify pool, and
396          // propagate exception to uncaught exception handler
397          try {
398 <            do;while (!tryInactivate()); // ensure inactive
398 >            do {} while (!tryInactivate()); // ensure inactive
399              cancelTasks();
400              runState = TERMINATED;
401              pool.workerTerminated(this);
# Line 400 | Line 411 | public class ForkJoinWorkerThread extend
411      // Intrinsics-based support for queue operations.
412  
413      /**
414 <     * Add in store-order the given task at given slot of q to
415 <     * null. Caller must ensure q is nonnull and index is in range.
414 >     * Adds in store-order the given task at given slot of q to null.
415 >     * Caller must ensure q is non-null and index is in range.
416       */
417      private static void setSlot(ForkJoinTask<?>[] q, int i,
418 <                                ForkJoinTask<?> t){
419 <        _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
418 >                                ForkJoinTask<?> t) {
419 >        UNSAFE.putOrderedObject(q, (i << qShift) + qBase, t);
420      }
421  
422      /**
423 <     * CAS given slot of q to null. Caller must ensure q is nonnull
423 >     * CAS given slot of q to null. Caller must ensure q is non-null
424       * and index is in range.
425       */
426      private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
427                                         ForkJoinTask<?> t) {
428 <        return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
428 >        return UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
429      }
430  
431      /**
432       * Sets sp in store-order.
433       */
434      private void storeSp(int s) {
435 <        _unsafe.putOrderedInt(this, spOffset, s);
435 >        UNSAFE.putOrderedInt(this, spOffset, s);
436      }
437  
438      // Main queue methods
439  
440      /**
441       * Pushes a task. Called only by current thread.
442 <     * @param t the task. Caller must ensure nonnull
442 >     *
443 >     * @param t the task. Caller must ensure non-null.
444       */
445      final void pushTask(ForkJoinTask<?> t) {
446          ForkJoinTask<?>[] q = queue;
# Line 445 | Line 457 | public class ForkJoinWorkerThread extend
457      /**
458       * Tries to take a task from the base of the queue, failing if
459       * either empty or contended.
460 <     * @return a task, or null if none or contended.
460 >     *
461 >     * @return a task, or null if none or contended
462       */
463      final ForkJoinTask<?> deqTask() {
464          ForkJoinTask<?> t;
# Line 463 | Line 476 | public class ForkJoinWorkerThread extend
476      }
477  
478      /**
479 +     * Tries to take a task from the base of own queue, activating if
480 +     * necessary, failing only if empty. Called only by current thread.
481 +     *
482 +     * @return a task, or null if none
483 +     */
484 +    final ForkJoinTask<?> locallyDeqTask() {
485 +        int b;
486 +        while (sp != (b = base)) {
487 +            if (tryActivate()) {
488 +                ForkJoinTask<?>[] q = queue;
489 +                int i = (q.length - 1) & b;
490 +                ForkJoinTask<?> t = q[i];
491 +                if (t != null && casSlotNull(q, i, t)) {
492 +                    base = b + 1;
493 +                    return t;
494 +                }
495 +            }
496 +        }
497 +        return null;
498 +    }
499 +
500 +    /**
501       * Returns a popped task, or null if empty. Ensures active status
502 <     * if nonnull. Called only by current thread.
502 >     * if non-null. Called only by current thread.
503       */
504      final ForkJoinTask<?> popTask() {
505          int s = sp;
# Line 487 | Line 522 | public class ForkJoinWorkerThread extend
522       * Specialized version of popTask to pop only if
523       * topmost element is the given task. Called only
524       * by current thread while active.
525 <     * @param t the task. Caller must ensure nonnull
525 >     *
526 >     * @param t the task. Caller must ensure non-null.
527       */
528      final boolean unpushTask(ForkJoinTask<?> t) {
529          ForkJoinTask<?>[] q = queue;
# Line 501 | Line 537 | public class ForkJoinWorkerThread extend
537      }
538  
539      /**
540 <     * Returns next task.
540 >     * Returns next task or null if empty or contended
541       */
542      final ForkJoinTask<?> peekTask() {
543          ForkJoinTask<?>[] q = queue;
544          if (q == null)
545              return null;
546          int mask = q.length - 1;
547 <        int i = locallyFifo? base : (sp - 1);
547 >        int i = locallyFifo ? base : (sp - 1);
548          return q[i & mask];
549      }
550  
# Line 571 | Line 607 | public class ForkJoinWorkerThread extend
607                      ForkJoinWorkerThread v = ws[mask & idx];
608                      if (v == null || v.sp == v.base) {
609                          if (probes <= mask)
610 <                            idx = (probes++ < 0)? r : (idx + 1);
610 >                            idx = (probes++ < 0) ? r : (idx + 1);
611                          else
612                              break;
613                      }
# Line 587 | Line 623 | public class ForkJoinWorkerThread extend
623      }
624  
625      /**
626 <     * gets and removes a local or stolen a task
626 >     * Gets and removes a local or stolen task.
627 >     *
628       * @return a task, if available
629       */
630      final ForkJoinTask<?> pollTask() {
631 <        ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
631 >        ForkJoinTask<?> t = locallyFifo ? locallyDeqTask() : popTask();
632          if (t == null && (t = scan()) != null)
633              ++stealCount;
634          return t;
635      }
636  
637      /**
638 <     * gets a local task
638 >     * Gets a local task.
639 >     *
640       * @return a task, if available
641       */
642      final ForkJoinTask<?> pollLocalTask() {
643 <        return locallyFifo? deqTask() : popTask();
643 >        return locallyFifo ? locallyDeqTask() : popTask();
644      }
645  
646      /**
647       * Returns a pool submission, if one exists, activating first.
648 +     *
649       * @return a submission, if available
650       */
651      private ForkJoinTask<?> pollSubmission() {
# Line 632 | Line 671 | public class ForkJoinWorkerThread extend
671      }
672  
673      /**
674 <     * Drains tasks to given collection c
674 >     * Drains tasks to given collection c.
675 >     *
676       * @return the number of tasks drained
677       */
678 <    final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
678 >    final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
679          int n = 0;
680          ForkJoinTask<?> t;
681          while (base != sp && (t = deqTask()) != null) {
# Line 646 | Line 686 | public class ForkJoinWorkerThread extend
686      }
687  
688      /**
689 <     * Get and clear steal count for accumulation by pool.  Called
689 >     * Gets and clears steal count for accumulation by pool.  Called
690       * only when known to be idle (in pool.sync and termination).
691       */
692      final int getAndClearStealCount() {
# Line 656 | Line 696 | public class ForkJoinWorkerThread extend
696      }
697  
698      /**
699 <     * Returns true if at least one worker in the given array appears
700 <     * to have at least one queued task.
699 >     * Returns {@code true} if at least one worker in the given array
700 >     * appears to have at least one queued task.
701 >     *
702       * @param ws array of workers
703       */
704      static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
# Line 680 | Line 721 | public class ForkJoinWorkerThread extend
721       * Returns an estimate of the number of tasks in the queue.
722       */
723      final int getQueueSize() {
724 <        int n = sp - base;
725 <        return n < 0? 0 : n; // suppress momentarily negative values
724 >        // suppress momentarily negative values
725 >        return Math.max(0, sp - base);
726      }
727  
728      /**
# Line 694 | Line 735 | public class ForkJoinWorkerThread extend
735      }
736  
737      /**
738 <     * Scan, returning early if joinMe done
738 >     * Scans, returning early if joinMe done.
739       */
740      final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
741          ForkJoinTask<?> t = pollTask();
# Line 706 | Line 747 | public class ForkJoinWorkerThread extend
747      }
748  
749      /**
750 <     * Runs tasks until pool isQuiescent
750 >     * Runs tasks until {@code pool.isQuiescent()}.
751       */
752      final void helpQuiescePool() {
753          for (;;) {
# Line 716 | Line 757 | public class ForkJoinWorkerThread extend
757              else if (tryInactivate() && pool.isQuiescent())
758                  break;
759          }
760 <        do;while (!tryActivate()); // re-activate on exit
760 >        do {} while (!tryActivate()); // re-activate on exit
761      }
762  
763 <    // Temporary Unsafe mechanics for preliminary release
764 <    private static Unsafe getUnsafe() throws Throwable {
763 >    // Unsafe mechanics
764 >
765 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
766 >    private static final long spOffset =
767 >        objectFieldOffset("sp", ForkJoinWorkerThread.class);
768 >    private static final long runStateOffset =
769 >        objectFieldOffset("runState", ForkJoinWorkerThread.class);
770 >    private static final long qBase;
771 >    private static final int qShift;
772 >
773 >    static {
774 >        qBase = UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
775 >        int s = UNSAFE.arrayIndexScale(ForkJoinTask[].class);
776 >        if ((s & (s-1)) != 0)
777 >            throw new Error("data type scale not a power of two");
778 >        qShift = 31 - Integer.numberOfLeadingZeros(s);
779 >    }
780 >
781 >    private static long objectFieldOffset(String field, Class<?> klazz) {
782          try {
783 <            return Unsafe.getUnsafe();
783 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
784 >        } catch (NoSuchFieldException e) {
785 >            // Convert Exception to corresponding Error
786 >            NoSuchFieldError error = new NoSuchFieldError(field);
787 >            error.initCause(e);
788 >            throw error;
789 >        }
790 >    }
791 >
792 >    /**
793 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
794 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
795 >     * into a jdk.
796 >     *
797 >     * @return a sun.misc.Unsafe
798 >     */
799 >    private static sun.misc.Unsafe getUnsafe() {
800 >        try {
801 >            return sun.misc.Unsafe.getUnsafe();
802          } catch (SecurityException se) {
803              try {
804                  return java.security.AccessController.doPrivileged
805 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
806 <                        public Unsafe run() throws Exception {
807 <                            return getUnsafePrivileged();
805 >                    (new java.security
806 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
807 >                        public sun.misc.Unsafe run() throws Exception {
808 >                            java.lang.reflect.Field f = sun.misc
809 >                                .Unsafe.class.getDeclaredField("theUnsafe");
810 >                            f.setAccessible(true);
811 >                            return (sun.misc.Unsafe) f.get(null);
812                          }});
813              } catch (java.security.PrivilegedActionException e) {
814 <                throw e.getCause();
814 >                throw new RuntimeException("Could not initialize intrinsics",
815 >                                           e.getCause());
816              }
817          }
818      }
738
739    private static Unsafe getUnsafePrivileged()
740            throws NoSuchFieldException, IllegalAccessException {
741        Field f = Unsafe.class.getDeclaredField("theUnsafe");
742        f.setAccessible(true);
743        return (Unsafe) f.get(null);
744    }
745
746    private static long fieldOffset(String fieldName)
747            throws NoSuchFieldException {
748        return _unsafe.objectFieldOffset
749            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
750    }
751
752    static final Unsafe _unsafe;
753    static final long baseOffset;
754    static final long spOffset;
755    static final long runStateOffset;
756    static final long qBase;
757    static final int qShift;
758    static {
759        try {
760            _unsafe = getUnsafe();
761            baseOffset = fieldOffset("base");
762            spOffset = fieldOffset("sp");
763            runStateOffset = fieldOffset("runState");
764            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
765            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
766            if ((s & (s-1)) != 0)
767                throw new Error("data type scale not a power of two");
768            qShift = 31 - Integer.numberOfLeadingZeros(s);
769        } catch (Throwable e) {
770            throw new RuntimeException("Could not initialize intrinsics", e);
771        }
772    }
819   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines