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

Comparing jsr166/src/jsr166y/ForkJoinTask.java (file contents):
Revision 1.92 by dl, Wed Oct 31 12:49:24 2012 UTC vs.
Revision 1.100 by jsr166, Tue Feb 5 17:09:54 2013 UTC

# Line 33 | Line 33 | import java.lang.reflect.Constructor;
33   * <p>A "main" {@code ForkJoinTask} begins execution when it is
34   * explicitly submitted to a {@link ForkJoinPool}, or, if not already
35   * engaged in a ForkJoin computation, commenced in the {@link
36 < * ForkJoinPool#commonPool} via {@link #fork}, {@link #invoke}, or
36 > * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or
37   * related methods.  Once started, it will usually in turn start other
38   * subtasks.  As indicated by the name of this class, many programs
39   * using {@code ForkJoinTask} employ only methods {@link #fork} and
# Line 55 | Line 55 | import java.lang.reflect.Constructor;
55   * minimize other blocking synchronization apart from joining other
56   * tasks or using synchronizers such as Phasers that are advertised to
57   * cooperate with fork/join scheduling. Subdividable tasks should also
58 < * not perform blocking IO, and should ideally access variables that
58 > * not perform blocking I/O, and should ideally access variables that
59   * are completely independent of those accessed by other running
60   * tasks. These guidelines are loosely enforced by not permitting
61   * checked exceptions such as {@code IOExceptions} to be
# Line 73 | Line 73 | import java.lang.reflect.Constructor;
73   * <p>It is possible to define and use ForkJoinTasks that may block,
74   * but doing do requires three further considerations: (1) Completion
75   * of few if any <em>other</em> tasks should be dependent on a task
76 < * that blocks on external synchronization or IO. Event-style async
76 > * that blocks on external synchronization or I/O. Event-style async
77   * tasks that are never joined (for example, those subclassing {@link
78   * CountedCompleter}) often fall into this category.  (2) To minimize
79   * resource impact, tasks should be small; ideally performing only the
# Line 285 | Line 285 | public abstract class ForkJoinTask<V> im
285       */
286      private int externalAwaitDone() {
287          int s;
288 +        ForkJoinPool.externalHelpJoin(this);
289          boolean interrupted = false;
290 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
290 <            s = doExec();
291 <        while (s >= 0) {
290 >        while ((s = status) >= 0) {
291              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
292                  synchronized (this) {
293                      if (status >= 0) {
# Line 302 | Line 301 | public abstract class ForkJoinTask<V> im
301                          notifyAll();
302                  }
303              }
305            s = status;
304          }
305          if (interrupted)
306              Thread.currentThread().interrupt();
# Line 313 | Line 311 | public abstract class ForkJoinTask<V> im
311       * Blocks a non-worker-thread until completion or interruption.
312       */
313      private int externalInterruptibleAwaitDone() throws InterruptedException {
314 +        int s;
315          if (Thread.interrupted())
316              throw new InterruptedException();
317 <        int s;
318 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
320 <            s = doExec();
321 <        while (s >= 0) {
317 >        ForkJoinPool.externalHelpJoin(this);
318 >        while ((s = status) >= 0) {
319              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
320                  synchronized (this) {
321                      if (status >= 0)
# Line 327 | Line 324 | public abstract class ForkJoinTask<V> im
324                          notifyAll();
325                  }
326              }
330            s = status;
327          }
328          return s;
329      }
330  
331 +
332      /**
333       * Implementation for join, get, quietlyJoin. Directly handles
334       * only cases of already-completed, external wait, and
# Line 438 | Line 435 | public abstract class ForkJoinTask<V> im
435      }
436  
437      /**
438 <     * Records exception and possibly propagates
438 >     * Records exception and possibly propagates.
439       *
440       * @return status on exit
441       */
# Line 471 | Line 468 | public abstract class ForkJoinTask<V> im
468      }
469  
470      /**
471 <     * Removes exception node and clears status
471 >     * Removes exception node and clears status.
472       */
473      private void clearExceptionalCompletion() {
474          int h = System.identityHashCode(this);
# Line 609 | Line 606 | public abstract class ForkJoinTask<V> im
606                  throw (Error)ex;
607              if (ex instanceof RuntimeException)
608                  throw (RuntimeException)ex;
609 <            throw uncheckedThrowable(ex, RuntimeException.class);
609 >            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
610          }
611      }
612  
# Line 619 | Line 616 | public abstract class ForkJoinTask<V> im
616       * unchecked exceptions
617       */
618      @SuppressWarnings("unchecked") static <T extends Throwable>
619 <        T uncheckedThrowable(final Throwable t, final Class<T> c) {
620 <        return (T)t; // rely on vacuous cast
619 >        void uncheckedThrow(Throwable t) throws T {
620 >        if (t != null)
621 >            throw (T)t; // rely on vacuous cast
622      }
623  
624      /**
# Line 638 | Line 636 | public abstract class ForkJoinTask<V> im
636      /**
637       * Arranges to asynchronously execute this task in the pool the
638       * current task is running in, if applicable, or using the {@link
639 <     * ForkJoinPool#commonPool} if not {@link #inForkJoinPool}.  While
639 >     * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}.  While
640       * it is not necessarily enforced, it is a usage error to fork a
641       * task more than once unless it has completed and been
642       * reinitialized.  Subsequent modifications to the state of this
# Line 655 | Line 653 | public abstract class ForkJoinTask<V> im
653          if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
654              ((ForkJoinWorkerThread)t).workQueue.push(this);
655          else
656 <            ForkJoinPool.submitToCommonPool(this);
656 >            ForkJoinPool.common.externalPush(this);
657          return this;
658      }
659  
# Line 981 | Line 979 | public abstract class ForkJoinTask<V> im
979          if (Thread.interrupted())
980              throw new InterruptedException();
981          // Messy in part because we measure in nanosecs, but wait in millisecs
982 <        int s; long ns, ms;
983 <        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
982 >        int s; long ms;
983 >        long ns = unit.toNanos(timeout);
984 >        if ((s = status) >= 0 && ns > 0L) {
985              long deadline = System.nanoTime() + ns;
986              ForkJoinPool p = null;
987              ForkJoinPool.WorkQueue w = null;
# Line 991 | Line 990 | public abstract class ForkJoinTask<V> im
990                  ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
991                  p = wt.pool;
992                  w = wt.workQueue;
993 <                s = p.helpJoinOnce(w, this); // no retries on failure
993 >                p.helpJoinOnce(w, this); // no retries on failure
994              }
995 +            else
996 +                ForkJoinPool.externalHelpJoin(this);
997              boolean canBlock = false;
998              boolean interrupted = false;
999              try {
1000                  while ((s = status) >= 0) {
1001 <                    if (w != null && w.runState < 0)
1001 >                    if (w != null && w.qlock < 0)
1002                          cancelIgnoringExceptions(this);
1003                      else if (!canBlock) {
1004 <                        if (p == null || p.tryCompensate(this, null))
1004 >                        if (p == null || p.tryCompensate())
1005                              canBlock = true;
1006                      }
1007                      else {
# Line 1076 | Line 1077 | public abstract class ForkJoinTask<V> im
1077              wt.pool.helpQuiescePool(wt.workQueue);
1078          }
1079          else
1080 <            ForkJoinPool.externalHelpQuiescePool();
1080 >            ForkJoinPool.quiesceCommonPool();
1081      }
1082  
1083      /**
# Line 1139 | Line 1140 | public abstract class ForkJoinTask<V> im
1140       */
1141      public boolean tryUnfork() {
1142          Thread t;
1143 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1144 <            ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1145 <            ForkJoinPool.tryUnsubmitFromCommonPool(this);
1143 >        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1144 >                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1145 >                ForkJoinPool.tryExternalUnpush(this));
1146      }
1147  
1148      /**
# Line 1153 | Line 1154 | public abstract class ForkJoinTask<V> im
1154       * @return the number of tasks
1155       */
1156      public static int getQueuedTaskCount() {
1157 <        Thread t;
1158 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1159 <            ((ForkJoinWorkerThread)t).workQueue.queueSize() :
1160 <            ForkJoinPool.getEstimatedSubmitterQueueLength();
1157 >        Thread t; ForkJoinPool.WorkQueue q;
1158 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1159 >            q = ((ForkJoinWorkerThread)t).workQueue;
1160 >        else
1161 >            q = ForkJoinPool.commonSubmitterQueue();
1162 >        return (q == null) ? 0 : q.queueSize();
1163      }
1164  
1165      /**
# Line 1173 | Line 1176 | public abstract class ForkJoinTask<V> im
1176       * @return the surplus number of tasks, which may be negative
1177       */
1178      public static int getSurplusQueuedTaskCount() {
1179 <        /*
1177 <         * The aim of this method is to return a cheap heuristic guide
1178 <         * for task partitioning when programmers, frameworks, tools,
1179 <         * or languages have little or no idea about task granularity.
1180 <         * In essence by offering this method, we ask users only about
1181 <         * tradeoffs in overhead vs expected throughput and its
1182 <         * variance, rather than how finely to partition tasks.
1183 <         *
1184 <         * In a steady state strict (tree-structured) computation,
1185 <         * each thread makes available for stealing enough tasks for
1186 <         * other threads to remain active. Inductively, if all threads
1187 <         * play by the same rules, each thread should make available
1188 <         * only a constant number of tasks.
1189 <         *
1190 <         * The minimum useful constant is just 1. But using a value of
1191 <         * 1 would require immediate replenishment upon each steal to
1192 <         * maintain enough tasks, which is infeasible.  Further,
1193 <         * partitionings/granularities of offered tasks should
1194 <         * minimize steal rates, which in general means that threads
1195 <         * nearer the top of computation tree should generate more
1196 <         * than those nearer the bottom. In perfect steady state, each
1197 <         * thread is at approximately the same level of computation
1198 <         * tree. However, producing extra tasks amortizes the
1199 <         * uncertainty of progress and diffusion assumptions.
1200 <         *
1201 <         * So, users will want to use values larger, but not much
1202 <         * larger than 1 to both smooth over transient shortages and
1203 <         * hedge against uneven progress; as traded off against the
1204 <         * cost of extra task overhead. We leave the user to pick a
1205 <         * threshold value to compare with the results of this call to
1206 <         * guide decisions, but recommend values such as 3.
1207 <         *
1208 <         * When all threads are active, it is on average OK to
1209 <         * estimate surplus strictly locally. In steady-state, if one
1210 <         * thread is maintaining say 2 surplus tasks, then so are
1211 <         * others. So we can just use estimated queue length.
1212 <         * However, this strategy alone leads to serious mis-estimates
1213 <         * in some non-steady-state conditions (ramp-up, ramp-down,
1214 <         * other stalls). We can detect many of these by further
1215 <         * considering the number of "idle" threads, that are known to
1216 <         * have zero queued tasks, so compensate by a factor of
1217 <         * (#idle/#active) threads.
1218 <         */
1219 <        Thread t; ForkJoinWorkerThread wt;
1220 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1221 <            (wt = (ForkJoinWorkerThread)t).workQueue.queueSize() - wt.pool.idlePerActive() :
1222 <            0;
1179 >        return ForkJoinPool.getSurplusQueuedTaskCount();
1180      }
1181  
1182      // Extension methods
# Line 1263 | Line 1220 | public abstract class ForkJoinTask<V> im
1220      /**
1221       * Returns, but does not unschedule or execute, a task queued by
1222       * the current thread but not yet executed, if one is immediately
1223 <     * available and the current thread is operating in a
1224 <     * ForkJoinPool. There is no guarantee that this task will
1225 <     * actually be polled or executed next. Conversely, this method
1226 <     * may return null even if a task exists but cannot be accessed
1270 <     * without contention with other threads.  This method is designed
1223 >     * available. There is no guarantee that this task will actually
1224 >     * be polled or executed next. Conversely, this method may return
1225 >     * null even if a task exists but cannot be accessed without
1226 >     * contention with other threads.  This method is designed
1227       * primarily to support extensions, and is unlikely to be useful
1228       * otherwise.
1229       *
1230       * @return the next task, or {@code null} if none are available
1231       */
1232      protected static ForkJoinTask<?> peekNextLocalTask() {
1233 <        Thread t;
1234 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1235 <            ((ForkJoinWorkerThread)t).workQueue.peek() :
1236 <            null;
1233 >        Thread t; ForkJoinPool.WorkQueue q;
1234 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1235 >            q = ((ForkJoinWorkerThread)t).workQueue;
1236 >        else
1237 >            q = ForkJoinPool.commonSubmitterQueue();
1238 >        return (q == null) ? null : q.peek();
1239      }
1240  
1241      /**
# Line 1502 | Line 1460 | public abstract class ForkJoinTask<V> im
1460      // Unsafe mechanics
1461      private static final sun.misc.Unsafe U;
1462      private static final long STATUS;
1463 +
1464      static {
1465          exceptionTableLock = new ReentrantLock();
1466          exceptionTableRefQueue = new ReferenceQueue<Object>();
1467          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1468          try {
1469              U = getUnsafe();
1470 +            Class<?> k = ForkJoinTask.class;
1471              STATUS = U.objectFieldOffset
1472 <                (ForkJoinTask.class.getDeclaredField("status"));
1472 >                (k.getDeclaredField("status"));
1473          } catch (Exception e) {
1474              throw new Error(e);
1475          }
# Line 1525 | Line 1485 | public abstract class ForkJoinTask<V> im
1485      private static sun.misc.Unsafe getUnsafe() {
1486          try {
1487              return sun.misc.Unsafe.getUnsafe();
1488 <        } catch (SecurityException se) {
1489 <            try {
1490 <                return java.security.AccessController.doPrivileged
1491 <                    (new java.security
1492 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1493 <                        public sun.misc.Unsafe run() throws Exception {
1494 <                            java.lang.reflect.Field f = sun.misc
1495 <                                .Unsafe.class.getDeclaredField("theUnsafe");
1496 <                            f.setAccessible(true);
1497 <                            return (sun.misc.Unsafe) f.get(null);
1498 <                        }});
1499 <            } catch (java.security.PrivilegedActionException e) {
1500 <                throw new RuntimeException("Could not initialize intrinsics",
1501 <                                           e.getCause());
1502 <            }
1488 >        } catch (SecurityException tryReflectionInstead) {}
1489 >        try {
1490 >            return java.security.AccessController.doPrivileged
1491 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1492 >                public sun.misc.Unsafe run() throws Exception {
1493 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
1494 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
1495 >                        f.setAccessible(true);
1496 >                        Object x = f.get(null);
1497 >                        if (k.isInstance(x))
1498 >                            return k.cast(x);
1499 >                    }
1500 >                    throw new NoSuchFieldError("the Unsafe");
1501 >                }});
1502 >        } catch (java.security.PrivilegedActionException e) {
1503 >            throw new RuntimeException("Could not initialize intrinsics",
1504 >                                       e.getCause());
1505          }
1506      }
1507   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines