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.1 by dl, Mon Aug 13 15:52:33 2012 UTC vs.
Revision 1.12 by jsr166, Tue Feb 5 17:09:54 2013 UTC

# Line 30 | Line 30 | import java.lang.reflect.Constructor;
30   * subtasks may be hosted by a small number of actual threads in a
31   * ForkJoinPool, at the price of some usage limitations.
32   *
33 < * <p>A "main" {@code ForkJoinTask} begins execution when submitted
34 < * to a {@link ForkJoinPool}.  Once started, it will usually in turn
35 < * start other subtasks.  As indicated by the name of this class,
36 < * many programs using {@code ForkJoinTask} employ only methods
37 < * {@link #fork} and {@link #join}, or derivatives such as {@link
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
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
40 > * {@link #join}, or derivatives such as {@link
41   * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
42   * provides a number of other methods that can come into play in
43 < * advanced usages, as well as extension mechanics that allow
44 < * support of new forms of fork/join processing.
43 > * advanced usages, as well as extension mechanics that allow support
44 > * of new forms of fork/join processing.
45   *
46   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
47   * The efficiency of {@code ForkJoinTask}s stems from a set of
# Line 52 | 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 70 | 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 123 | Line 126 | import java.lang.reflect.Constructor;
126   * other actions.  Normally, a concrete ForkJoinTask subclass declares
127   * fields comprising its parameters, established in a constructor, and
128   * then defines a {@code compute} method that somehow uses the control
129 < * methods supplied by this base class. While these methods have
127 < * {@code public} access (to allow instances of different task
128 < * subclasses to call each other's methods), some of them may only be
129 < * called from within other ForkJoinTasks (as may be determined using
130 < * method {@link #inForkJoinPool}).  Attempts to invoke them in other
131 < * contexts result in exceptions or errors, possibly including {@code
132 < * ClassCastException}.
129 > * methods supplied by this base class.
130   *
131   * <p>Method {@link #join} and its variants are appropriate for use
132   * only when completion dependencies are acyclic; that is, the
# Line 137 | 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 287 | Line 285 | public abstract class ForkJoinTask<V> im
285       * @return status upon completion
286       */
287      private int externalAwaitDone() {
290        boolean interrupted = false;
288          int s;
289 +        ForkJoinPool.externalHelpJoin(this);
290 +        boolean interrupted = false;
291          while ((s = status) >= 0) {
292              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293                  synchronized (this) {
# Line 316 | Line 315 | public abstract class ForkJoinTask<V> im
315          int s;
316          if (Thread.interrupted())
317              throw new InterruptedException();
318 +        ForkJoinPool.externalHelpJoin(this);
319          while ((s = status) >= 0) {
320              if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
321                  synchronized (this) {
# Line 329 | Line 329 | public abstract class ForkJoinTask<V> im
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 338 | Line 339 | public abstract class ForkJoinTask<V> im
339       */
340      private int doJoin() {
341          int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
342 <        if ((s = status) >= 0) {
343 <            if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
344 <                if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
345 <                    tryUnpush(this) || (s = doExec()) >= 0)
346 <                    s = wt.pool.awaitJoin(w, this);
347 <            }
347 <            else
348 <                s = externalAwaitDone();
349 <        }
350 <        return s;
342 >        return (s = status) < 0 ? s :
343 >            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
344 >            (w = (wt = (ForkJoinWorkerThread)t).workQueue).
345 >            tryUnpush(this) && (s = doExec()) < 0 ? s :
346 >            wt.pool.awaitJoin(w, this) :
347 >            externalAwaitDone();
348      }
349  
350      /**
# Line 357 | Line 354 | public abstract class ForkJoinTask<V> im
354       */
355      private int doInvoke() {
356          int s; Thread t; ForkJoinWorkerThread wt;
357 <        if ((s = doExec()) >= 0) {
358 <            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
359 <                s = (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue,
360 <                                                                  this);
364 <            else
365 <                s = externalAwaitDone();
366 <        }
367 <        return s;
357 >        return (s = doExec()) < 0 ? s :
358 >            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
359 >            (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, this) :
360 >            externalAwaitDone();
361      }
362  
363      // Exception table support
# Line 443 | 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 476 | Line 469 | public abstract class ForkJoinTask<V> im
469      }
470  
471      /**
472 <     * Removes exception node and clears status
472 >     * Removes exception node and clears status.
473       */
474      private void clearExceptionalCompletion() {
475          int h = System.identityHashCode(this);
# Line 606 | Line 599 | public abstract class ForkJoinTask<V> im
599      }
600  
601      /**
602 +     * A version of "sneaky throw" to relay exceptions
603 +     */
604 +    static void rethrow(final Throwable ex) {
605 +        if (ex != null) {
606 +            if (ex instanceof Error)
607 +                throw (Error)ex;
608 +            if (ex instanceof RuntimeException)
609 +                throw (RuntimeException)ex;
610 +            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
611 +        }
612 +    }
613 +
614 +    /**
615 +     * The sneaky part of sneaky throw, relying on generics
616 +     * limitations to evade compiler complaints about rethrowing
617 +     * unchecked exceptions
618 +     */
619 +    @SuppressWarnings("unchecked") static <T extends Throwable>
620 +        void uncheckedThrow(Throwable t) throws T {
621 +        if (t != null)
622 +            throw (T)t; // rely on vacuous cast
623 +    }
624 +
625 +    /**
626       * Throws exception, if any, associated with the given status.
627       */
628      private void reportException(int s) {
629 <        Throwable ex = ((s == CANCELLED) ?  new CancellationException() :
630 <                        (s == EXCEPTIONAL) ? getThrowableException() :
631 <                        null);
632 <        if (ex != null)
616 <            U.throwException(ex);
629 >        if (s == CANCELLED)
630 >            throw new CancellationException();
631 >        if (s == EXCEPTIONAL)
632 >            rethrow(getThrowableException());
633      }
634  
635      // public methods
636  
637      /**
638 <     * Arranges to asynchronously execute this task.  While it is not
639 <     * necessarily enforced, it is a usage error to fork a task more
640 <     * than once unless it has completed and been reinitialized.
641 <     * Subsequent modifications to the state of this task or any data
642 <     * it operates on are not necessarily consistently observable by
643 <     * any thread other than the one executing it unless preceded by a
644 <     * call to {@link #join} or related methods, or a call to {@link
645 <     * #isDone} returning {@code true}.
646 <     *
647 <     * <p>This method may be invoked only from within {@code
648 <     * ForkJoinPool} computations (as may be determined using method
633 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
634 <     * result in exceptions or errors, possibly including {@code
635 <     * ClassCastException}.
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
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
644 >     * task or any data it operates on are not necessarily
645 >     * consistently observable by any thread other than the one
646 >     * executing it unless preceded by a call to {@link #join} or
647 >     * related methods, or a call to {@link #isDone} returning {@code
648 >     * true}.
649       *
650       * @return {@code this}, to simplify usage
651       */
652      public final ForkJoinTask<V> fork() {
653 <        ((ForkJoinWorkerThread)Thread.currentThread()).workQueue.push(this);
653 >        Thread t;
654 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
655 >            ((ForkJoinWorkerThread)t).workQueue.push(this);
656 >        else
657 >            ForkJoinPool.common.externalPush(this);
658          return this;
659      }
660  
# Line 687 | Line 704 | public abstract class ForkJoinTask<V> im
704       * cancelled, completed normally or exceptionally, or left
705       * unprocessed.
706       *
690     * <p>This method may be invoked only from within {@code
691     * ForkJoinPool} computations (as may be determined using method
692     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
693     * result in exceptions or errors, possibly including {@code
694     * ClassCastException}.
695     *
707       * @param t1 the first task
708       * @param t2 the second task
709       * @throws NullPointerException if any task is null
# Line 718 | Line 729 | public abstract class ForkJoinTask<V> im
729       * related methods to check if they have been cancelled, completed
730       * normally or exceptionally, or left unprocessed.
731       *
721     * <p>This method may be invoked only from within {@code
722     * ForkJoinPool} computations (as may be determined using method
723     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
724     * result in exceptions or errors, possibly including {@code
725     * ClassCastException}.
726     *
732       * @param tasks the tasks
733       * @throws NullPointerException if any task is null
734       */
# Line 751 | Line 756 | public abstract class ForkJoinTask<V> im
756              }
757          }
758          if (ex != null)
759 <            U.throwException(ex);
759 >            rethrow(ex);
760      }
761  
762      /**
# Line 767 | Line 772 | public abstract class ForkJoinTask<V> im
772       * cancelled, completed normally or exceptionally, or left
773       * unprocessed.
774       *
770     * <p>This method may be invoked only from within {@code
771     * ForkJoinPool} computations (as may be determined using method
772     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
773     * result in exceptions or errors, possibly including {@code
774     * ClassCastException}.
775     *
775       * @param tasks the collection of tasks
776       * @return the tasks argument, to simplify usage
777       * @throws NullPointerException if tasks or any element are null
# Line 808 | Line 807 | public abstract class ForkJoinTask<V> im
807              }
808          }
809          if (ex != null)
810 <            U.throwException(ex);
810 >            rethrow(ex);
811          return tasks;
812      }
813  
# 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 1068 | Line 1070 | public abstract class ForkJoinTask<V> im
1070       * be of use in designs in which many tasks are forked, but none
1071       * are explicitly joined, instead executing them until all are
1072       * processed.
1071     *
1072     * <p>This method may be invoked only from within {@code
1073     * ForkJoinPool} computations (as may be determined using method
1074     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1075     * result in exceptions or errors, possibly including {@code
1076     * ClassCastException}.
1073       */
1074      public static void helpQuiesce() {
1075 <        ForkJoinWorkerThread wt =
1076 <            (ForkJoinWorkerThread)Thread.currentThread();
1077 <        wt.pool.helpQuiescePool(wt.workQueue);
1075 >        Thread t;
1076 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
1077 >            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
1078 >            wt.pool.helpQuiescePool(wt.workQueue);
1079 >        }
1080 >        else
1081 >            ForkJoinPool.quiesceCommonPool();
1082      }
1083  
1084      /**
# Line 1131 | Line 1131 | public abstract class ForkJoinTask<V> im
1131  
1132      /**
1133       * Tries to unschedule this task for execution. This method will
1134 <     * typically succeed if this task is the most recently forked task
1135 <     * by the current thread, and has not commenced executing in
1136 <     * another thread.  This method may be useful when arranging
1137 <     * alternative local processing of tasks that could have been, but
1138 <     * were not, stolen.
1139 <     *
1140 <     * <p>This method may be invoked only from within {@code
1141 <     * ForkJoinPool} computations (as may be determined using method
1142 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1143 <     * result in exceptions or errors, possibly including {@code
1144 <     * ClassCastException}.
1134 >     * typically (but is not guaranteed to) succeed if this task is
1135 >     * the most recently forked task by the current thread, and has
1136 >     * not commenced executing in another thread.  This method may be
1137 >     * useful when arranging alternative local processing of tasks
1138 >     * that could have been, but were not, stolen.
1139       *
1140       * @return {@code true} if unforked
1141       */
1142      public boolean tryUnfork() {
1143 <        return ((ForkJoinWorkerThread)Thread.currentThread())
1144 <            .workQueue.tryUnpush(this);
1143 >        Thread t;
1144 >        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1145 >                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1146 >                ForkJoinPool.tryExternalUnpush(this));
1147      }
1148  
1149      /**
# Line 1156 | Line 1152 | public abstract class ForkJoinTask<V> im
1152       * value may be useful for heuristic decisions about whether to
1153       * fork other tasks.
1154       *
1159     * <p>This method may be invoked only from within {@code
1160     * ForkJoinPool} computations (as may be determined using method
1161     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1162     * result in exceptions or errors, possibly including {@code
1163     * ClassCastException}.
1164     *
1155       * @return the number of tasks
1156       */
1157      public static int getQueuedTaskCount() {
1158 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1159 <            .workQueue.queueSize();
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      /**
1167       * Returns an estimate of how many more locally queued tasks are
1168       * held by the current worker thread than there are other worker
1169 <     * threads that might steal them.  This value may be useful for
1169 >     * threads that might steal them, or zero if this thread is not
1170 >     * operating in a ForkJoinPool. This value may be useful for
1171       * heuristic decisions about whether to fork other tasks. In many
1172       * usages of ForkJoinTasks, at steady state, each worker should
1173       * aim to maintain a small constant surplus (for example, 3) of
1174       * tasks, and to process computations locally if this threshold is
1175       * exceeded.
1176       *
1182     * <p>This method may be invoked only from within {@code
1183     * ForkJoinPool} computations (as may be determined using method
1184     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1185     * result in exceptions or errors, possibly including {@code
1186     * ClassCastException}.
1187     *
1177       * @return the surplus number of tasks, which may be negative
1178       */
1179      public static int getSurplusQueuedTaskCount() {
1180 <        /*
1192 <         * The aim of this method is to return a cheap heuristic guide
1193 <         * for task partitioning when programmers, frameworks, tools,
1194 <         * or languages have little or no idea about task granularity.
1195 <         * In essence by offering this method, we ask users only about
1196 <         * tradeoffs in overhead vs expected throughput and its
1197 <         * variance, rather than how finely to partition tasks.
1198 <         *
1199 <         * In a steady state strict (tree-structured) computation,
1200 <         * each thread makes available for stealing enough tasks for
1201 <         * other threads to remain active. Inductively, if all threads
1202 <         * play by the same rules, each thread should make available
1203 <         * only a constant number of tasks.
1204 <         *
1205 <         * The minimum useful constant is just 1. But using a value of
1206 <         * 1 would require immediate replenishment upon each steal to
1207 <         * maintain enough tasks, which is infeasible.  Further,
1208 <         * partitionings/granularities of offered tasks should
1209 <         * minimize steal rates, which in general means that threads
1210 <         * nearer the top of computation tree should generate more
1211 <         * than those nearer the bottom. In perfect steady state, each
1212 <         * thread is at approximately the same level of computation
1213 <         * tree. However, producing extra tasks amortizes the
1214 <         * uncertainty of progress and diffusion assumptions.
1215 <         *
1216 <         * So, users will want to use values larger, but not much
1217 <         * larger than 1 to both smooth over transient shortages and
1218 <         * hedge against uneven progress; as traded off against the
1219 <         * cost of extra task overhead. We leave the user to pick a
1220 <         * threshold value to compare with the results of this call to
1221 <         * guide decisions, but recommend values such as 3.
1222 <         *
1223 <         * When all threads are active, it is on average OK to
1224 <         * estimate surplus strictly locally. In steady-state, if one
1225 <         * thread is maintaining say 2 surplus tasks, then so are
1226 <         * others. So we can just use estimated queue length.
1227 <         * However, this strategy alone leads to serious mis-estimates
1228 <         * in some non-steady-state conditions (ramp-up, ramp-down,
1229 <         * other stalls). We can detect many of these by further
1230 <         * considering the number of "idle" threads, that are known to
1231 <         * have zero queued tasks, so compensate by a factor of
1232 <         * (#idle/#active) threads.
1233 <         */
1234 <        ForkJoinWorkerThread wt =
1235 <            (ForkJoinWorkerThread)Thread.currentThread();
1236 <        return wt.workQueue.queueSize() - wt.pool.idlePerActive();
1180 >        return ForkJoinPool.getSurplusQueuedTaskCount();
1181      }
1182  
1183      // Extension methods
# Line 1284 | Line 1228 | public abstract class ForkJoinTask<V> im
1228       * primarily to support extensions, and is unlikely to be useful
1229       * otherwise.
1230       *
1287     * <p>This method may be invoked only from within {@code
1288     * ForkJoinPool} computations (as may be determined using method
1289     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1290     * result in exceptions or errors, possibly including {@code
1291     * ClassCastException}.
1292     *
1231       * @return the next task, or {@code null} if none are available
1232       */
1233      protected static ForkJoinTask<?> peekNextLocalTask() {
1234 <        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
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      /**
1243       * Unschedules and returns, without executing, the next task
1244 <     * queued by the current thread but not yet executed.  This method
1245 <     * is designed primarily to support extensions, and is unlikely to
1246 <     * be useful otherwise.
1247 <     *
1305 <     * <p>This method may be invoked only from within {@code
1306 <     * ForkJoinPool} computations (as may be determined using method
1307 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1308 <     * result in exceptions or errors, possibly including {@code
1309 <     * ClassCastException}.
1244 >     * queued by the current thread but not yet executed, if the
1245 >     * current thread is operating in a ForkJoinPool.  This method is
1246 >     * designed primarily to support extensions, and is unlikely to be
1247 >     * useful otherwise.
1248       *
1249       * @return the next task, or {@code null} if none are available
1250       */
1251      protected static ForkJoinTask<?> pollNextLocalTask() {
1252 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1253 <            .workQueue.nextLocalTask();
1252 >        Thread t;
1253 >        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1254 >            ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() :
1255 >            null;
1256      }
1257  
1258      /**
1259 <     * Unschedules and returns, without executing, the next task
1259 >     * If the current thread is operating in a ForkJoinPool,
1260 >     * unschedules and returns, without executing, the next task
1261       * queued by the current thread but not yet executed, if one is
1262       * available, or if not available, a task that was forked by some
1263       * other thread, if available. Availability may be transient, so a
1264 <     * {@code null} result does not necessarily imply quiescence
1265 <     * of the pool this task is operating in.  This method is designed
1264 >     * {@code null} result does not necessarily imply quiescence of
1265 >     * the pool this task is operating in.  This method is designed
1266       * primarily to support extensions, and is unlikely to be useful
1267       * otherwise.
1268       *
1328     * <p>This method may be invoked only from within {@code
1329     * ForkJoinPool} computations (as may be determined using method
1330     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1331     * result in exceptions or errors, possibly including {@code
1332     * ClassCastException}.
1333     *
1269       * @return a task, or {@code null} if none are available
1270       */
1271      protected static ForkJoinTask<?> pollTask() {
1272 <        ForkJoinWorkerThread wt =
1273 <            (ForkJoinWorkerThread)Thread.currentThread();
1274 <        return wt.pool.nextTaskFor(wt.workQueue);
1272 >        Thread t; ForkJoinWorkerThread wt;
1273 >        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1274 >            (wt = (ForkJoinWorkerThread)t).pool.nextTaskFor(wt.workQueue) :
1275 >            null;
1276      }
1277  
1278      // tag operations
# Line 1525 | 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 1548 | 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