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.17 by jsr166, Sat Jul 25 00:34:00 2009 UTC vs.
Revision 1.25 by dl, Fri Jul 31 16:27:08 2009 UTC

# Line 25 | Line 25 | import java.util.WeakHashMap;
25   * <p> A "main" ForkJoinTask begins execution when submitted to a
26   * {@link ForkJoinPool}. Once started, it will usually in turn start
27   * other subtasks.  As indicated by the name of this class, many
28 < * programs using ForkJoinTasks employ only methods {@code fork}
29 < * and {@code join}, or derivatives such as
30 < * {@code invokeAll}.  However, this class also provides a number
31 < * of other methods that can come into play in advanced usages, as
32 < * well as extension mechanics that allow support of new forms of
33 < * fork/join processing.
28 > * programs using ForkJoinTasks employ only methods {@code fork} and
29 > * {@code join}, or derivatives such as {@code invokeAll}.  However,
30 > * this class also provides a number of other methods that can come
31 > * into play in advanced usages, as well as extension mechanics that
32 > * allow support of new forms of fork/join processing.
33   *
34   * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
35   * efficiency of ForkJoinTasks stems from a set of restrictions (that
# Line 94 | Line 93 | import java.util.WeakHashMap;
93   * lightweight task scheduling framework, and so cannot be overridden.
94   * Developers creating new basic styles of fork/join processing should
95   * minimally implement {@code protected} methods
96 < * {@code exec}, {@code setRawResult}, and
97 < * {@code getRawResult}, while also introducing an abstract
96 > * {@link #exec}, {@link #setRawResult}, and
97 > * {@link #getRawResult}, while also introducing an abstract
98   * computational method that can be implemented in its subclasses,
99   * possibly relying on other {@code protected} methods provided
100   * by this class.
# Line 248 | Line 247 | public abstract class ForkJoinTask<V> im
247          synchronized (this) {
248              try {
249                  while (status >= 0) {
250 <                    long nt = nanos - System.nanoTime() - startTime;
250 >                    long nt = nanos - (System.nanoTime() - startTime);
251                      if (nt <= 0)
252                          break;
253                      wait(nt / 1000000, (int) (nt % 1000000));
# Line 492 | Line 491 | public abstract class ForkJoinTask<V> im
491       * computations (as may be determined using method {@link
492       * #inForkJoinPool}). Attempts to invoke in other contexts result
493       * in exceptions or errors, possibly including ClassCastException.
494 +     *
495 +     * @return {@code this}, to simplify usage.
496       */
497 <    public final void fork() {
497 >    public final ForkJoinTask<V> fork() {
498          ((ForkJoinWorkerThread) Thread.currentThread())
499              .pushTask(this);
500 +        return this;
501      }
502  
503      /**
# Line 603 | Line 605 | public abstract class ForkJoinTask<V> im
605       * in exceptions or errors, possibly including ClassCastException.
606       *
607       * @param tasks the collection of tasks
608 +     * @return the tasks argument, to simplify usage
609       * @throws NullPointerException if tasks or any element are null
610       * @throws RuntimeException or Error if any task did so
611       */
612 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
612 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
613          if (!(tasks instanceof List<?>)) {
614              invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
615 <            return;
615 >            return tasks;
616          }
617          @SuppressWarnings("unchecked")
618          List<? extends ForkJoinTask<?>> ts =
# Line 644 | Line 647 | public abstract class ForkJoinTask<V> im
647          }
648          if (ex != null)
649              rethrowException(ex);
650 +        return tasks;
651      }
652  
653      /**
654 <     * Returns true if the computation performed by this task has
655 <     * completed (or has been cancelled).
654 >     * Returns {@code true} if the computation performed by this task
655 >     * has completed (or has been cancelled).
656       *
657 <     * @return true if this computation has completed
657 >     * @return {@code true} if this computation has completed
658       */
659      public final boolean isDone() {
660          return status < 0;
661      }
662  
663      /**
664 <     * Returns true if this task was cancelled.
664 >     * Returns {@code true} if this task was cancelled.
665       *
666 <     * @return true if this task was cancelled
666 >     * @return {@code true} if this task was cancelled
667       */
668      public final boolean isCancelled() {
669          return (status & COMPLETION_MASK) == CANCELLED;
# Line 668 | Line 672 | public abstract class ForkJoinTask<V> im
672      /**
673       * Asserts that the results of this task's computation will not be
674       * used. If a cancellation occurs before attempting to execute this
675 <     * task, then execution will be suppressed, {@code isCancelled}
676 <     * will report true, and {@code join} will result in a
675 >     * task, execution will be suppressed, {@link #isCancelled}
676 >     * will report true, and {@link #join} will result in a
677       * {@code CancellationException} being thrown. Otherwise, when
678       * cancellation races with completion, there are no guarantees
679 <     * about whether {@code isCancelled} will report true, whether
680 <     * {@code join} will return normally or via an exception, or
681 <     * whether these behaviors will remain consistent upon repeated
679 >     * about whether {@code isCancelled} will report {@code true},
680 >     * whether {@code join} will return normally or via an exception,
681 >     * or whether these behaviors will remain consistent upon repeated
682       * invocation.
683       *
684       * <p>This method may be overridden in subclasses, but if so, must
# Line 684 | Line 688 | public abstract class ForkJoinTask<V> im
688       * <p> This method is designed to be invoked by <em>other</em>
689       * tasks. To terminate the current task, you can just return or
690       * throw an unchecked exception from its computation method, or
691 <     * invoke {@code completeExceptionally}.
691 >     * invoke {@link #completeExceptionally}.
692       *
693       * @param mayInterruptIfRunning this value is ignored in the
694       * default implementation because tasks are not in general
695       * cancelled via interruption
696       *
697 <     * @return true if this task is now cancelled
697 >     * @return {@code true} if this task is now cancelled
698       */
699      public boolean cancel(boolean mayInterruptIfRunning) {
700          setCompletion(CANCELLED);
# Line 698 | Line 702 | public abstract class ForkJoinTask<V> im
702      }
703  
704      /**
705 <     * Returns true if this task threw an exception or was cancelled.
705 >     * Returns {@code true} if this task threw an exception or was cancelled.
706       *
707 <     * @return true if this task threw an exception or was cancelled
707 >     * @return {@code true} if this task threw an exception or was cancelled
708       */
709      public final boolean isCompletedAbnormally() {
710          return (status & COMPLETION_MASK) < NORMAL;
# Line 711 | Line 715 | public abstract class ForkJoinTask<V> im
715       * CancellationException if cancelled, or null if none or if the
716       * method has not yet completed.
717       *
718 <     * @return the exception, or null if none
718 >     * @return the exception, or {@code null} if none
719       */
720      public final Throwable getException() {
721          int s = status & COMPLETION_MASK;
# Line 773 | Line 777 | public abstract class ForkJoinTask<V> im
777  
778      public final V get(long timeout, TimeUnit unit)
779          throws InterruptedException, ExecutionException, TimeoutException {
780 +        long nanos = unit.toNanos(timeout);
781          ForkJoinWorkerThread w = getWorker();
782          if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
783 <            awaitDone(w, unit.toNanos(timeout));
783 >            awaitDone(w, nanos);
784          return reportTimedFutureResult();
785      }
786  
# Line 874 | Line 879 | public abstract class ForkJoinTask<V> im
879       * Returns the pool hosting the current task execution, or null
880       * if this task is executing outside of any ForkJoinPool.
881       *
882 <     * @return the pool, or null if none
882 >     * @return the pool, or {@code null} if none
883       */
884      public static ForkJoinPool getPool() {
885          Thread t = Thread.currentThread();
# Line 905 | Line 910 | public abstract class ForkJoinTask<V> im
910       * result in exceptions or errors, possibly including
911       * ClassCastException.
912       *
913 <     * @return true if unforked
913 >     * @return {@code true} if unforked
914       */
915      public boolean tryUnfork() {
916          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 945 | Line 950 | public abstract class ForkJoinTask<V> im
950      // Extension methods
951  
952      /**
953 <     * Returns the result that would be returned by {@code join},
954 <     * even if this task completed abnormally, or null if this task is
955 <     * not known to have been completed.  This method is designed to
956 <     * aid debugging, as well as to support extensions. Its use in any
957 <     * other context is discouraged.
953 >     * Returns the result that would be returned by {@link #join}, even
954 >     * if this task completed abnormally, or {@code null} if this task
955 >     * is not known to have been completed.  This method is designed
956 >     * to aid debugging, as well as to support extensions. Its use in
957 >     * any other context is discouraged.
958       *
959 <     * @return the result, or null if not completed
959 >     * @return the result, or {@code null} if not completed
960       */
961      public abstract V getRawResult();
962  
# Line 970 | Line 975 | public abstract class ForkJoinTask<V> im
975       * called otherwise. The return value controls whether this task
976       * is considered to be done normally. It may return false in
977       * asynchronous actions that require explicit invocations of
978 <     * {@code complete} to become joinable. It may throw exceptions
978 >     * {@link #complete} to become joinable. It may throw exceptions
979       * to indicate abnormal exit.
980       *
981 <     * @return true if completed normally
981 >     * @return {@code true} if completed normally
982       * @throws Error or RuntimeException if encountered during computation
983       */
984      protected abstract boolean exec();
985  
986      /**
987 <     * Returns, but does not unschedule or execute, the task queued by
988 <     * the current thread but not yet executed, if one is
987 >     * Returns, but does not unschedule or execute, a task queued by
988 >     * the current thread but not yet executed, if one is immediately
989       * available. There is no guarantee that this task will actually
990 <     * be polled or executed next.  This method is designed primarily
991 <     * to support extensions, and is unlikely to be useful otherwise.
992 <     * This method may be invoked only from within ForkJoinTask
993 <     * computations (as may be determined using method {@link
994 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
995 <     * in exceptions or errors, possibly including ClassCastException.
990 >     * be polled or executed next. Conversely, this method may return
991 >     * null even if a task exists but cannot be accessed without
992 >     * contention with other threads.  This method is designed
993 >     * primarily to support extensions, and is unlikely to be useful
994 >     * otherwise.  This method may be invoked only from within
995 >     * ForkJoinTask computations (as may be determined using method
996 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
997 >     * result in exceptions or errors, possibly including
998 >     * ClassCastException.
999       *
1000 <     * @return the next task, or null if none are available
1000 >     * @return the next task, or {@code null} if none are available
1001       */
1002      protected static ForkJoinTask<?> peekNextLocalTask() {
1003          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1006 | Line 1014 | public abstract class ForkJoinTask<V> im
1014       * contexts result in exceptions or errors, possibly including
1015       * ClassCastException.
1016       *
1017 <     * @return the next task, or null if none are available
1017 >     * @return the next task, or {@code null} if none are available
1018       */
1019      protected static ForkJoinTask<?> pollNextLocalTask() {
1020          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1027 | Line 1035 | public abstract class ForkJoinTask<V> im
1035       * result in exceptions or errors, possibly including
1036       * ClassCastException.
1037       *
1038 <     * @return a task, or null if none are available
1038 >     * @return a task, or {@code null} if none are available
1039       */
1040      protected static ForkJoinTask<?> pollTask() {
1041          return ((ForkJoinWorkerThread) Thread.currentThread())
1042              .pollTask();
1043      }
1044  
1045 +    /**
1046 +     * Adaptor for Runnables. This implements RunnableFuture
1047 +     * to be compliant with AbstractExecutorService constraints
1048 +     * when used in ForkJoinPool.
1049 +     */
1050 +    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1051 +        implements RunnableFuture<T> {
1052 +        final Runnable runnable;
1053 +        final T resultOnCompletion;
1054 +        T result;
1055 +        AdaptedRunnable(Runnable runnable, T result) {
1056 +            if (runnable == null) throw new NullPointerException();
1057 +            this.runnable = runnable;
1058 +            this.resultOnCompletion = result;
1059 +        }
1060 +        public T getRawResult() { return result; }
1061 +        public void setRawResult(T v) { result = v; }
1062 +        public boolean exec() {
1063 +            runnable.run();
1064 +            result = resultOnCompletion;
1065 +            return true;
1066 +        }
1067 +        public void run() { invoke(); }
1068 +        private static final long serialVersionUID = 5232453952276885070L;
1069 +    }
1070 +
1071 +    /**
1072 +     * Adaptor for Callables
1073 +     */
1074 +    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1075 +        implements RunnableFuture<T> {
1076 +        final Callable<T> callable;
1077 +        T result;
1078 +        AdaptedCallable(Callable<T> callable) {
1079 +            if (callable == null) throw new NullPointerException();
1080 +            this.callable = callable;
1081 +        }
1082 +        public T getRawResult() { return result; }
1083 +        public void setRawResult(T v) { result = v; }
1084 +        public boolean exec() {
1085 +            try {
1086 +                result = callable.call();
1087 +                return true;
1088 +            } catch (Error err) {
1089 +                throw err;
1090 +            } catch (RuntimeException rex) {
1091 +                throw rex;
1092 +            } catch (Exception ex) {
1093 +                throw new RuntimeException(ex);
1094 +            }
1095 +        }
1096 +        public void run() { invoke(); }
1097 +        private static final long serialVersionUID = 2838392045355241008L;
1098 +    }
1099 +
1100 +    /**
1101 +     * Returns a new ForkJoinTask that performs the {@code run}
1102 +     * method of the given Runnable as its action, and returns a null
1103 +     * result upon {@code join}.
1104 +     *
1105 +     * @param runnable the runnable action
1106 +     * @return the task
1107 +     */
1108 +    public static ForkJoinTask<Void> adapt(Runnable runnable) {
1109 +        return new AdaptedRunnable<Void>(runnable, null);
1110 +    }
1111 +
1112 +    /**
1113 +     * Returns a new ForkJoinTask that performs the {@code run}
1114 +     * method of the given Runnable as its action, and returns the
1115 +     * given result upon {@code join}.
1116 +     *
1117 +     * @param runnable the runnable action
1118 +     * @param result the result upon completion
1119 +     * @return the task
1120 +     */
1121 +    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1122 +        return new AdaptedRunnable<T>(runnable, result);
1123 +    }
1124 +
1125 +    /**
1126 +     * Returns a new ForkJoinTask that performs the {@code call}
1127 +     * method of the given Callable as its action, and returns its
1128 +     * result upon {@code join}, translating any checked
1129 +     * exceptions encountered into {@code RuntimeException}.
1130 +     *
1131 +     * @param callable the callable action
1132 +     * @return the task
1133 +     */
1134 +    public static <T> ForkJoinTask<T> adapt(Callable<T> callable) {
1135 +        return new AdaptedCallable<T>(callable);
1136 +    }
1137 +
1138      // Serialization support
1139  
1140      private static final long serialVersionUID = -7721805057305804111L;
# Line 1042 | Line 1143 | public abstract class ForkJoinTask<V> im
1143       * Save the state to a stream.
1144       *
1145       * @serialData the current run status and the exception thrown
1146 <     * during execution, or null if none
1146 >     * during execution, or {@code null} if none
1147       * @param s the stream
1148       */
1149      private void writeObject(java.io.ObjectOutputStream s)
# Line 1066 | Line 1167 | public abstract class ForkJoinTask<V> im
1167              setDoneExceptionally((Throwable) ex);
1168      }
1169  
1170 <    // Unsafe mechanics for jsr166y 3rd party package.
1170 >    // Unsafe mechanics
1171 >
1172 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1173 >    private static final long statusOffset =
1174 >        objectFieldOffset("status", ForkJoinTask.class);
1175 >
1176 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1177 >        try {
1178 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1179 >        } catch (NoSuchFieldException e) {
1180 >            // Convert Exception to corresponding Error
1181 >            NoSuchFieldError error = new NoSuchFieldError(field);
1182 >            error.initCause(e);
1183 >            throw error;
1184 >        }
1185 >    }
1186 >
1187 >    /**
1188 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1189 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1190 >     * into a jdk.
1191 >     *
1192 >     * @return a sun.misc.Unsafe
1193 >     */
1194      private static sun.misc.Unsafe getUnsafe() {
1195          try {
1196              return sun.misc.Unsafe.getUnsafe();
1197          } catch (SecurityException se) {
1198              try {
1199                  return java.security.AccessController.doPrivileged
1200 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1200 >                    (new java.security
1201 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1202                          public sun.misc.Unsafe run() throws Exception {
1203 <                            return getUnsafeByReflection();
1203 >                            java.lang.reflect.Field f = sun.misc
1204 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1205 >                            f.setAccessible(true);
1206 >                            return (sun.misc.Unsafe) f.get(null);
1207                          }});
1208              } catch (java.security.PrivilegedActionException e) {
1209                  throw new RuntimeException("Could not initialize intrinsics",
# Line 1083 | Line 1211 | public abstract class ForkJoinTask<V> im
1211              }
1212          }
1213      }
1086
1087    private static sun.misc.Unsafe getUnsafeByReflection()
1088            throws NoSuchFieldException, IllegalAccessException {
1089        java.lang.reflect.Field f =
1090            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1091        f.setAccessible(true);
1092        return (sun.misc.Unsafe) f.get(null);
1093    }
1094
1095    private static long fieldOffset(String fieldName, Class<?> klazz) {
1096        try {
1097            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1098        } catch (NoSuchFieldException e) {
1099            // Convert Exception to Error
1100            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1101            error.initCause(e);
1102            throw error;
1103        }
1104    }
1105
1106    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1107    static final long statusOffset =
1108        fieldOffset("status", ForkJoinTask.class);
1109
1214   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines