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.2 by dl, Sun Oct 28 22:35:45 2012 UTC vs.
Revision 1.15 by jsr166, Mon Jul 22 16:52:31 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 Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
138   * may be of use in constructing custom subclasses for problems that
139 < * are not statically structured as DAGs. To support such usages a
139 > * are not statically structured as DAGs. To support such usages, a
140   * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
141   * value using {@link #setForkJoinTaskTag} or {@link
142   * #compareAndSetForkJoinTaskTag} and checked using {@link
# Line 285 | Line 285 | public abstract class ForkJoinTask<V> im
285       */
286      private int externalAwaitDone() {
287          int s;
288 <        boolean interrupted = false;
289 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
290 <            s = doExec();
291 <        while (s >= 0) {
292 <            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293 <                synchronized (this) {
294 <                    if (status >= 0) {
295 <                        try {
296 <                            wait();
297 <                        } catch (InterruptedException ie) {
298 <                            interrupted = true;
288 >        ForkJoinPool cp = ForkJoinPool.common;
289 >        if ((s = status) >= 0) {
290 >            if (cp != null) {
291 >                if (this instanceof CountedCompleter)
292 >                    s = cp.externalHelpComplete((CountedCompleter<?>)this);
293 >                else if (cp.tryExternalUnpush(this))
294 >                    s = doExec();
295 >            }
296 >            if (s >= 0 && (s = status) >= 0) {
297 >                boolean interrupted = false;
298 >                do {
299 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
300 >                        synchronized (this) {
301 >                            if (status >= 0) {
302 >                                try {
303 >                                    wait();
304 >                                } catch (InterruptedException ie) {
305 >                                    interrupted = true;
306 >                                }
307 >                            }
308 >                            else
309 >                                notifyAll();
310                          }
311                      }
312 <                    else
313 <                        notifyAll();
314 <                }
312 >                } while ((s = status) >= 0);
313 >                if (interrupted)
314 >                    Thread.currentThread().interrupt();
315              }
305            s = status;
316          }
307        if (interrupted)
308            Thread.currentThread().interrupt();
317          return s;
318      }
319  
# Line 313 | Line 321 | public abstract class ForkJoinTask<V> im
321       * Blocks a non-worker-thread until completion or interruption.
322       */
323      private int externalInterruptibleAwaitDone() throws InterruptedException {
324 +        int s;
325 +        ForkJoinPool cp = ForkJoinPool.common;
326          if (Thread.interrupted())
327              throw new InterruptedException();
328 <        int s;
329 <        if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this))
330 <            s = doExec();
331 <        while (s >= 0) {
328 >        if ((s = status) >= 0 && cp != null) {
329 >            if (this instanceof CountedCompleter)
330 >                cp.externalHelpComplete((CountedCompleter<?>)this);
331 >            else if (cp.tryExternalUnpush(this))
332 >                doExec();
333 >        }
334 >        while ((s = status) >= 0) {
335              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
336                  synchronized (this) {
337                      if (status >= 0)
# Line 327 | Line 340 | public abstract class ForkJoinTask<V> im
340                          notifyAll();
341                  }
342              }
330            s = status;
343          }
344          return s;
345      }
346  
347 +
348      /**
349       * Implementation for join, get, quietlyJoin. Directly handles
350       * only cases of already-completed, external wait, and
# Line 438 | Line 451 | public abstract class ForkJoinTask<V> im
451      }
452  
453      /**
454 <     * Records exception and possibly propagates
454 >     * Records exception and possibly propagates.
455       *
456       * @return status on exit
457       */
# Line 471 | Line 484 | public abstract class ForkJoinTask<V> im
484      }
485  
486      /**
487 <     * Removes exception node and clears status
487 >     * Removes exception node and clears status.
488       */
489      private void clearExceptionalCompletion() {
490          int h = System.identityHashCode(this);
# Line 601 | Line 614 | public abstract class ForkJoinTask<V> im
614      }
615  
616      /**
617 +     * A version of "sneaky throw" to relay exceptions
618 +     */
619 +    static void rethrow(Throwable ex) {
620 +        if (ex != null)
621 +            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
622 +    }
623 +
624 +    /**
625 +     * The sneaky part of sneaky throw, relying on generics
626 +     * limitations to evade compiler complaints about rethrowing
627 +     * unchecked exceptions
628 +     */
629 +    @SuppressWarnings("unchecked") static <T extends Throwable>
630 +        void uncheckedThrow(Throwable t) throws T {
631 +        throw (T)t; // rely on vacuous cast
632 +    }
633 +
634 +    /**
635       * Throws exception, if any, associated with the given status.
636       */
637      private void reportException(int s) {
638 <        Throwable ex = ((s == CANCELLED) ?  new CancellationException() :
639 <                        (s == EXCEPTIONAL) ? getThrowableException() :
640 <                        null);
641 <        if (ex != null)
611 <            U.throwException(ex);
638 >        if (s == CANCELLED)
639 >            throw new CancellationException();
640 >        if (s == EXCEPTIONAL)
641 >            rethrow(getThrowableException());
642      }
643  
644      // public methods
# Line 616 | Line 646 | public abstract class ForkJoinTask<V> im
646      /**
647       * Arranges to asynchronously execute this task in the pool the
648       * current task is running in, if applicable, or using the {@link
649 <     * ForkJoinPool#commonPool} if not {@link #inForkJoinPool}.  While
649 >     * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}.  While
650       * it is not necessarily enforced, it is a usage error to fork a
651       * task more than once unless it has completed and been
652       * reinitialized.  Subsequent modifications to the state of this
# Line 633 | Line 663 | public abstract class ForkJoinTask<V> im
663          if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
664              ((ForkJoinWorkerThread)t).workQueue.push(this);
665          else
666 <            ForkJoinPool.submitToCommonPool(this);
666 >            ForkJoinPool.common.externalPush(this);
667          return this;
668      }
669  
# Line 735 | Line 765 | public abstract class ForkJoinTask<V> im
765              }
766          }
767          if (ex != null)
768 <            U.throwException(ex);
768 >            rethrow(ex);
769      }
770  
771      /**
# Line 752 | Line 782 | public abstract class ForkJoinTask<V> im
782       * unprocessed.
783       *
784       * @param tasks the collection of tasks
785 +     * @param <T> the type of the values returned from the tasks
786       * @return the tasks argument, to simplify usage
787       * @throws NullPointerException if tasks or any element are null
788       */
# Line 786 | Line 817 | public abstract class ForkJoinTask<V> im
817              }
818          }
819          if (ex != null)
820 <            U.throwException(ex);
820 >            rethrow(ex);
821          return tasks;
822      }
823  
# Line 809 | Line 840 | public abstract class ForkJoinTask<V> im
840       * <p>This method is designed to be invoked by <em>other</em>
841       * tasks. To terminate the current task, you can just return or
842       * throw an unchecked exception from its computation method, or
843 <     * invoke {@link #completeExceptionally}.
843 >     * invoke {@link #completeExceptionally(Throwable)}.
844       *
845       * @param mayInterruptIfRunning this value has no effect in the
846       * default implementation because interrupts are not used to
# Line 959 | Line 990 | public abstract class ForkJoinTask<V> im
990          if (Thread.interrupted())
991              throw new InterruptedException();
992          // Messy in part because we measure in nanosecs, but wait in millisecs
993 <        int s; long ns, ms;
994 <        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
993 >        int s; long ms;
994 >        long ns = unit.toNanos(timeout);
995 >        ForkJoinPool cp;
996 >        if ((s = status) >= 0 && ns > 0L) {
997              long deadline = System.nanoTime() + ns;
998              ForkJoinPool p = null;
999              ForkJoinPool.WorkQueue w = null;
# Line 969 | Line 1002 | public abstract class ForkJoinTask<V> im
1002                  ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
1003                  p = wt.pool;
1004                  w = wt.workQueue;
1005 <                s = p.helpJoinOnce(w, this); // no retries on failure
1005 >                p.helpJoinOnce(w, this); // no retries on failure
1006 >            }
1007 >            else if ((cp = ForkJoinPool.common) != null) {
1008 >                if (this instanceof CountedCompleter)
1009 >                    cp.externalHelpComplete((CountedCompleter<?>)this);
1010 >                else if (cp.tryExternalUnpush(this))
1011 >                    doExec();
1012              }
1013              boolean canBlock = false;
1014              boolean interrupted = false;
1015              try {
1016                  while ((s = status) >= 0) {
1017 <                    if (w != null && w.runState < 0)
1017 >                    if (w != null && w.qlock < 0)
1018                          cancelIgnoringExceptions(this);
1019                      else if (!canBlock) {
1020 <                        if (p == null || p.tryCompensate(this, null))
1020 >                        if (p == null || p.tryCompensate(p.ctl))
1021                              canBlock = true;
1022                      }
1023                      else {
# Line 1054 | Line 1093 | public abstract class ForkJoinTask<V> im
1093              wt.pool.helpQuiescePool(wt.workQueue);
1094          }
1095          else
1096 <            ForkJoinPool.externalHelpQuiescePool();
1096 >            ForkJoinPool.quiesceCommonPool();
1097      }
1098  
1099      /**
# Line 1117 | Line 1156 | public abstract class ForkJoinTask<V> im
1156       */
1157      public boolean tryUnfork() {
1158          Thread t;
1159 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1160 <            ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1161 <            ForkJoinPool.tryUnsubmitFromCommonPool(this);
1159 >        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1160 >                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1161 >                ForkJoinPool.common.tryExternalUnpush(this));
1162      }
1163  
1164      /**
# Line 1131 | Line 1170 | public abstract class ForkJoinTask<V> im
1170       * @return the number of tasks
1171       */
1172      public static int getQueuedTaskCount() {
1173 <        Thread t;
1174 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1175 <            ((ForkJoinWorkerThread)t).workQueue.queueSize() :
1176 <            ForkJoinPool.getEstimatedSubmitterQueueLength();
1173 >        Thread t; ForkJoinPool.WorkQueue q;
1174 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1175 >            q = ((ForkJoinWorkerThread)t).workQueue;
1176 >        else
1177 >            q = ForkJoinPool.commonSubmitterQueue();
1178 >        return (q == null) ? 0 : q.queueSize();
1179      }
1180  
1181      /**
# Line 1151 | Line 1192 | public abstract class ForkJoinTask<V> im
1192       * @return the surplus number of tasks, which may be negative
1193       */
1194      public static int getSurplusQueuedTaskCount() {
1195 <        /*
1155 <         * The aim of this method is to return a cheap heuristic guide
1156 <         * for task partitioning when programmers, frameworks, tools,
1157 <         * or languages have little or no idea about task granularity.
1158 <         * In essence by offering this method, we ask users only about
1159 <         * tradeoffs in overhead vs expected throughput and its
1160 <         * variance, rather than how finely to partition tasks.
1161 <         *
1162 <         * In a steady state strict (tree-structured) computation,
1163 <         * each thread makes available for stealing enough tasks for
1164 <         * other threads to remain active. Inductively, if all threads
1165 <         * play by the same rules, each thread should make available
1166 <         * only a constant number of tasks.
1167 <         *
1168 <         * The minimum useful constant is just 1. But using a value of
1169 <         * 1 would require immediate replenishment upon each steal to
1170 <         * maintain enough tasks, which is infeasible.  Further,
1171 <         * partitionings/granularities of offered tasks should
1172 <         * minimize steal rates, which in general means that threads
1173 <         * nearer the top of computation tree should generate more
1174 <         * than those nearer the bottom. In perfect steady state, each
1175 <         * thread is at approximately the same level of computation
1176 <         * tree. However, producing extra tasks amortizes the
1177 <         * uncertainty of progress and diffusion assumptions.
1178 <         *
1179 <         * So, users will want to use values larger, but not much
1180 <         * larger than 1 to both smooth over transient shortages and
1181 <         * hedge against uneven progress; as traded off against the
1182 <         * cost of extra task overhead. We leave the user to pick a
1183 <         * threshold value to compare with the results of this call to
1184 <         * guide decisions, but recommend values such as 3.
1185 <         *
1186 <         * When all threads are active, it is on average OK to
1187 <         * estimate surplus strictly locally. In steady-state, if one
1188 <         * thread is maintaining say 2 surplus tasks, then so are
1189 <         * others. So we can just use estimated queue length.
1190 <         * However, this strategy alone leads to serious mis-estimates
1191 <         * in some non-steady-state conditions (ramp-up, ramp-down,
1192 <         * other stalls). We can detect many of these by further
1193 <         * considering the number of "idle" threads, that are known to
1194 <         * have zero queued tasks, so compensate by a factor of
1195 <         * (#idle/#active) threads.
1196 <         */
1197 <        Thread t; ForkJoinWorkerThread wt;
1198 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1199 <            (wt = (ForkJoinWorkerThread)t).workQueue.queueSize() - wt.pool.idlePerActive() :
1200 <            0;
1195 >        return ForkJoinPool.getSurplusQueuedTaskCount();
1196      }
1197  
1198      // Extension methods
# Line 1241 | Line 1236 | public abstract class ForkJoinTask<V> im
1236      /**
1237       * Returns, but does not unschedule or execute, a task queued by
1238       * the current thread but not yet executed, if one is immediately
1239 <     * available and the current thread is operating in a
1240 <     * ForkJoinPool. There is no guarantee that this task will
1241 <     * actually be polled or executed next. Conversely, this method
1242 <     * may return null even if a task exists but cannot be accessed
1248 <     * without contention with other threads.  This method is designed
1239 >     * available. There is no guarantee that this task will actually
1240 >     * be polled or executed next. Conversely, this method may return
1241 >     * null even if a task exists but cannot be accessed without
1242 >     * contention with other threads.  This method is designed
1243       * primarily to support extensions, and is unlikely to be useful
1244       * otherwise.
1245       *
1246       * @return the next task, or {@code null} if none are available
1247       */
1248      protected static ForkJoinTask<?> peekNextLocalTask() {
1249 <        Thread t;
1250 <        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1251 <            ((ForkJoinWorkerThread)t).workQueue.peek() :
1252 <            null;
1249 >        Thread t; ForkJoinPool.WorkQueue q;
1250 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1251 >            q = ((ForkJoinWorkerThread)t).workQueue;
1252 >        else
1253 >            q = ForkJoinPool.commonSubmitterQueue();
1254 >        return (q == null) ? null : q.peek();
1255      }
1256  
1257      /**
# Line 1331 | Line 1327 | public abstract class ForkJoinTask<V> im
1327       *
1328       * @param e the expected tag value
1329       * @param tag the new tag value
1330 <     * @return true if successful; i.e., the current value was
1330 >     * @return {@code true} if successful; i.e., the current value was
1331       * equal to e and is now tag.
1332       * @since 1.8
1333       */
# Line 1384 | Line 1380 | public abstract class ForkJoinTask<V> im
1380      }
1381  
1382      /**
1383 +     * Adaptor for Runnables in which failure forces worker exception
1384 +     */
1385 +    static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1386 +        final Runnable runnable;
1387 +        RunnableExecuteAction(Runnable runnable) {
1388 +            if (runnable == null) throw new NullPointerException();
1389 +            this.runnable = runnable;
1390 +        }
1391 +        public final Void getRawResult() { return null; }
1392 +        public final void setRawResult(Void v) { }
1393 +        public final boolean exec() { runnable.run(); return true; }
1394 +        void internalPropagateException(Throwable ex) {
1395 +            rethrow(ex); // rethrow outside exec() catches.
1396 +        }
1397 +        private static final long serialVersionUID = 5232453952276885070L;
1398 +    }
1399 +
1400 +    /**
1401       * Adaptor for Callables
1402       */
1403      static final class AdaptedCallable<T> extends ForkJoinTask<T>
# Line 1431 | Line 1445 | public abstract class ForkJoinTask<V> im
1445       *
1446       * @param runnable the runnable action
1447       * @param result the result upon completion
1448 +     * @param <T> the type of the result
1449       * @return the task
1450       */
1451      public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
# Line 1444 | Line 1459 | public abstract class ForkJoinTask<V> im
1459       * encountered into {@code RuntimeException}.
1460       *
1461       * @param callable the callable action
1462 +     * @param <T> the type of the callable's result
1463       * @return the task
1464       */
1465      public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
# Line 1457 | Line 1473 | public abstract class ForkJoinTask<V> im
1473      /**
1474       * Saves this task to a stream (that is, serializes it).
1475       *
1476 +     * @param s the stream
1477 +     * @throws java.io.IOException if an I/O error occurs
1478       * @serialData the current run status and the exception thrown
1479       * during execution, or {@code null} if none
1480       */
# Line 1468 | Line 1486 | public abstract class ForkJoinTask<V> im
1486  
1487      /**
1488       * Reconstitutes this task from a stream (that is, deserializes it).
1489 +     * @param s the stream
1490 +     * @throws ClassNotFoundException if the class of a serialized object
1491 +     *         could not be found
1492 +     * @throws java.io.IOException if an I/O error occurs
1493       */
1494      private void readObject(java.io.ObjectInputStream s)
1495          throws java.io.IOException, ClassNotFoundException {
# Line 1480 | Line 1502 | public abstract class ForkJoinTask<V> im
1502      // Unsafe mechanics
1503      private static final sun.misc.Unsafe U;
1504      private static final long STATUS;
1505 +
1506      static {
1507          exceptionTableLock = new ReentrantLock();
1508          exceptionTableRefQueue = new ReferenceQueue<Object>();
1509          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1510          try {
1511              U = getUnsafe();
1512 +            Class<?> k = ForkJoinTask.class;
1513              STATUS = U.objectFieldOffset
1514 <                (ForkJoinTask.class.getDeclaredField("status"));
1514 >                (k.getDeclaredField("status"));
1515          } catch (Exception e) {
1516              throw new Error(e);
1517          }
# Line 1503 | Line 1527 | public abstract class ForkJoinTask<V> im
1527      private static sun.misc.Unsafe getUnsafe() {
1528          try {
1529              return sun.misc.Unsafe.getUnsafe();
1530 <        } catch (SecurityException se) {
1531 <            try {
1532 <                return java.security.AccessController.doPrivileged
1533 <                    (new java.security
1534 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1535 <                        public sun.misc.Unsafe run() throws Exception {
1536 <                            java.lang.reflect.Field f = sun.misc
1537 <                                .Unsafe.class.getDeclaredField("theUnsafe");
1538 <                            f.setAccessible(true);
1539 <                            return (sun.misc.Unsafe) f.get(null);
1540 <                        }});
1541 <            } catch (java.security.PrivilegedActionException e) {
1542 <                throw new RuntimeException("Could not initialize intrinsics",
1543 <                                           e.getCause());
1544 <            }
1530 >        } catch (SecurityException tryReflectionInstead) {}
1531 >        try {
1532 >            return java.security.AccessController.doPrivileged
1533 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1534 >                public sun.misc.Unsafe run() throws Exception {
1535 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
1536 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
1537 >                        f.setAccessible(true);
1538 >                        Object x = f.get(null);
1539 >                        if (k.isInstance(x))
1540 >                            return k.cast(x);
1541 >                    }
1542 >                    throw new NoSuchFieldError("the Unsafe");
1543 >                }});
1544 >        } catch (java.security.PrivilegedActionException e) {
1545 >            throw new RuntimeException("Could not initialize intrinsics",
1546 >                                       e.getCause());
1547          }
1548      }
1549   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines