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

Comparing jsr166/src/jsr166e/ForkJoinTask.java (file contents):
Revision 1.3 by dl, Wed Oct 31 12:49:13 2012 UTC vs.
Revision 1.11 by jsr166, Sun Jan 20 03:44:14 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 134 | Line 134 | import java.lang.reflect.Constructor;
134   * (DAG). Otherwise, executions may encounter a form of deadlock as
135   * tasks cyclically wait for each other.  However, this framework
136   * supports other methods and techniques (for example the use of
137 < * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
137 > * {@link java.util.concurrent.Phaser}, {@link #helpQuiesce}, and
138 > * {@link #complete}) that
139   * may be of use in constructing custom subclasses for problems that
140   * are not statically structured as DAGs. To support such usages a
141   * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
# Line 285 | Line 286 | public abstract class ForkJoinTask<V> im
286       */
287      private int externalAwaitDone() {
288          int s;
289 +        ForkJoinPool.externalHelpJoin(this);
290          boolean interrupted = false;
291 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
290 <            s = doExec();
291 <        while (s >= 0) {
291 >        while ((s = status) >= 0) {
292              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293                  synchronized (this) {
294                      if (status >= 0) {
# Line 302 | Line 302 | public abstract class ForkJoinTask<V> im
302                          notifyAll();
303                  }
304              }
305            s = status;
305          }
306          if (interrupted)
307              Thread.currentThread().interrupt();
# Line 313 | Line 312 | public abstract class ForkJoinTask<V> im
312       * Blocks a non-worker-thread until completion or interruption.
313       */
314      private int externalInterruptibleAwaitDone() throws InterruptedException {
315 +        int s;
316          if (Thread.interrupted())
317              throw new InterruptedException();
318 <        int s;
319 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
320 <            s = doExec();
321 <        while (s >= 0) {
318 >        ForkJoinPool.externalHelpJoin(this);
319 >        while ((s = status) >= 0) {
320              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
321                  synchronized (this) {
322                      if (status >= 0)
# Line 327 | Line 325 | public abstract class ForkJoinTask<V> im
325                          notifyAll();
326                  }
327              }
330            s = status;
328          }
329          return s;
330      }
331  
332 +
333      /**
334       * Implementation for join, get, quietlyJoin. Directly handles
335       * only cases of already-completed, external wait, and
# Line 438 | Line 436 | public abstract class ForkJoinTask<V> im
436      }
437  
438      /**
439 <     * Records exception and possibly propagates
439 >     * Records exception and possibly propagates.
440       *
441       * @return status on exit
442       */
# Line 609 | Line 607 | public abstract class ForkJoinTask<V> im
607                  throw (Error)ex;
608              if (ex instanceof RuntimeException)
609                  throw (RuntimeException)ex;
610 <            throw uncheckedThrowable(ex, RuntimeException.class);
610 >            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
611          }
612      }
613  
# Line 619 | Line 617 | public abstract class ForkJoinTask<V> im
617       * unchecked exceptions
618       */
619      @SuppressWarnings("unchecked") static <T extends Throwable>
620 <        T uncheckedThrowable(final Throwable t, final Class<T> c) {
621 <        return (T)t; // rely on vacuous cast
620 >        void uncheckedThrow(Throwable t) throws T {
621 >        if (t != null)
622 >            throw (T)t; // rely on vacuous cast
623      }
624  
625      /**
# Line 638 | Line 637 | public abstract class ForkJoinTask<V> im
637      /**
638       * Arranges to asynchronously execute this task in the pool the
639       * current task is running in, if applicable, or using the {@link
640 <     * ForkJoinPool#commonPool} if not {@link #inForkJoinPool}.  While
640 >     * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}.  While
641       * it is not necessarily enforced, it is a usage error to fork a
642       * task more than once unless it has completed and been
643       * reinitialized.  Subsequent modifications to the state of this
# Line 655 | Line 654 | public abstract class ForkJoinTask<V> im
654          if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
655              ((ForkJoinWorkerThread)t).workQueue.push(this);
656          else
657 <            ForkJoinPool.submitToCommonPool(this);
657 >            ForkJoinPool.common.externalPush(this);
658          return this;
659      }
660  
# Line 981 | Line 980 | public abstract class ForkJoinTask<V> im
980          if (Thread.interrupted())
981              throw new InterruptedException();
982          // Messy in part because we measure in nanosecs, but wait in millisecs
983 <        int s; long ns, ms;
984 <        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
983 >        int s; long ms;
984 >        long ns = unit.toNanos(timeout);
985 >        if ((s = status) >= 0 && ns > 0L) {
986              long deadline = System.nanoTime() + ns;
987              ForkJoinPool p = null;
988              ForkJoinPool.WorkQueue w = null;
# Line 991 | Line 991 | public abstract class ForkJoinTask<V> im
991                  ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
992                  p = wt.pool;
993                  w = wt.workQueue;
994 <                s = p.helpJoinOnce(w, this); // no retries on failure
994 >                p.helpJoinOnce(w, this); // no retries on failure
995              }
996 +            else
997 +                ForkJoinPool.externalHelpJoin(this);
998              boolean canBlock = false;
999              boolean interrupted = false;
1000              try {
1001                  while ((s = status) >= 0) {
1002 <                    if (w != null && w.runState < 0)
1002 >                    if (w != null && w.qlock < 0)
1003                          cancelIgnoringExceptions(this);
1004                      else if (!canBlock) {
1005 <                        if (p == null || p.tryCompensate(this, null))
1005 >                        if (p == null || p.tryCompensate())
1006                              canBlock = true;
1007                      }
1008                      else {
# Line 1076 | Line 1078 | public abstract class ForkJoinTask<V> im
1078              wt.pool.helpQuiescePool(wt.workQueue);
1079          }
1080          else
1081 <            ForkJoinPool.externalHelpQuiescePool();
1081 >            ForkJoinPool.quiesceCommonPool();
1082      }
1083  
1084      /**
# Line 1139 | Line 1141 | public abstract class ForkJoinTask<V> im
1141       */
1142      public boolean tryUnfork() {
1143          Thread t;
1144 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1145 <            ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1146 <            ForkJoinPool.tryUnsubmitFromCommonPool(this);
1144 >        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1145 >                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1146 >                ForkJoinPool.tryExternalUnpush(this));
1147      }
1148  
1149      /**
# Line 1153 | Line 1155 | public abstract class ForkJoinTask<V> im
1155       * @return the number of tasks
1156       */
1157      public static int getQueuedTaskCount() {
1158 <        Thread t;
1159 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1160 <            ((ForkJoinWorkerThread)t).workQueue.queueSize() :
1161 <            ForkJoinPool.getEstimatedSubmitterQueueLength();
1158 >        Thread t; ForkJoinPool.WorkQueue q;
1159 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1160 >            q = ((ForkJoinWorkerThread)t).workQueue;
1161 >        else
1162 >            q = ForkJoinPool.commonSubmitterQueue();
1163 >        return (q == null) ? 0 : q.queueSize();
1164      }
1165  
1166      /**
# Line 1173 | Line 1177 | public abstract class ForkJoinTask<V> im
1177       * @return the surplus number of tasks, which may be negative
1178       */
1179      public static int getSurplusQueuedTaskCount() {
1180 <        /*
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;
1180 >        return ForkJoinPool.getSurplusQueuedTaskCount();
1181      }
1182  
1183      // Extension methods
# Line 1263 | Line 1221 | public abstract class ForkJoinTask<V> im
1221      /**
1222       * Returns, but does not unschedule or execute, a task queued by
1223       * the current thread but not yet executed, if one is immediately
1224 <     * available and the current thread is operating in a
1225 <     * ForkJoinPool. There is no guarantee that this task will
1226 <     * actually be polled or executed next. Conversely, this method
1227 <     * may return null even if a task exists but cannot be accessed
1270 <     * without contention with other threads.  This method is designed
1224 >     * available. There is no guarantee that this task will actually
1225 >     * be polled or executed next. Conversely, this method may return
1226 >     * null even if a task exists but cannot be accessed without
1227 >     * contention with other threads.  This method is designed
1228       * primarily to support extensions, and is unlikely to be useful
1229       * otherwise.
1230       *
1231       * @return the next task, or {@code null} if none are available
1232       */
1233      protected static ForkJoinTask<?> peekNextLocalTask() {
1234 <        Thread t;
1235 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1236 <            ((ForkJoinWorkerThread)t).workQueue.peek() :
1237 <            null;
1234 >        Thread t; ForkJoinPool.WorkQueue q;
1235 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1236 >            q = ((ForkJoinWorkerThread)t).workQueue;
1237 >        else
1238 >            q = ForkJoinPool.commonSubmitterQueue();
1239 >        return (q == null) ? null : q.peek();
1240      }
1241  
1242      /**
# Line 1502 | Line 1461 | public abstract class ForkJoinTask<V> im
1461      // Unsafe mechanics
1462      private static final sun.misc.Unsafe U;
1463      private static final long STATUS;
1464 +
1465      static {
1466          exceptionTableLock = new ReentrantLock();
1467          exceptionTableRefQueue = new ReferenceQueue<Object>();
1468          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1469          try {
1470              U = getUnsafe();
1471 +            Class<?> k = ForkJoinTask.class;
1472              STATUS = U.objectFieldOffset
1473 <                (ForkJoinTask.class.getDeclaredField("status"));
1473 >                (k.getDeclaredField("status"));
1474          } catch (Exception e) {
1475              throw new Error(e);
1476          }
# Line 1525 | Line 1486 | public abstract class ForkJoinTask<V> im
1486      private static sun.misc.Unsafe getUnsafe() {
1487          try {
1488              return sun.misc.Unsafe.getUnsafe();
1489 <        } catch (SecurityException se) {
1490 <            try {
1491 <                return java.security.AccessController.doPrivileged
1492 <                    (new java.security
1493 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1494 <                        public sun.misc.Unsafe run() throws Exception {
1495 <                            java.lang.reflect.Field f = sun.misc
1496 <                                .Unsafe.class.getDeclaredField("theUnsafe");
1497 <                            f.setAccessible(true);
1498 <                            return (sun.misc.Unsafe) f.get(null);
1499 <                        }});
1500 <            } catch (java.security.PrivilegedActionException e) {
1501 <                throw new RuntimeException("Could not initialize intrinsics",
1502 <                                           e.getCause());
1503 <            }
1489 >        } catch (SecurityException tryReflectionInstead) {}
1490 >        try {
1491 >            return java.security.AccessController.doPrivileged
1492 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1493 >                public sun.misc.Unsafe run() throws Exception {
1494 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
1495 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
1496 >                        f.setAccessible(true);
1497 >                        Object x = f.get(null);
1498 >                        if (k.isInstance(x))
1499 >                            return k.cast(x);
1500 >                    }
1501 >                    throw new NoSuchFieldError("the Unsafe");
1502 >                }});
1503 >        } catch (java.security.PrivilegedActionException e) {
1504 >            throw new RuntimeException("Could not initialize intrinsics",
1505 >                                       e.getCause());
1506          }
1507      }
1508   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines