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.15 by jsr166, Fri Jul 24 22:05:22 2009 UTC vs.
Revision 1.24 by jsr166, Mon Jul 27 21:41:53 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.io.Serializable;
9 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import sun.misc.Unsafe;
12 < import java.lang.reflect.*;
10 >
11 > import java.io.Serializable;
12 > import java.util.Collection;
13 > import java.util.Collections;
14 > import java.util.List;
15 > import java.util.Map;
16 > import java.util.WeakHashMap;
17  
18   /**
19   * Abstract base class for tasks that run within a {@link
# Line 22 | Line 25 | import java.lang.reflect.*;
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
30 < * 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 91 | Line 93 | import java.lang.reflect.*;
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 489 | 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 600 | 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 641 | 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 665 | 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 681 | 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 695 | 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 708 | 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 871 | Line 878 | public abstract class ForkJoinTask<V> im
878       * Returns the pool hosting the current task execution, or null
879       * if this task is executing outside of any ForkJoinPool.
880       *
881 <     * @return the pool, or null if none
881 >     * @return the pool, or {@code null} if none
882       */
883      public static ForkJoinPool getPool() {
884          Thread t = Thread.currentThread();
# Line 902 | Line 909 | public abstract class ForkJoinTask<V> im
909       * result in exceptions or errors, possibly including
910       * ClassCastException.
911       *
912 <     * @return true if unforked
912 >     * @return {@code true} if unforked
913       */
914      public boolean tryUnfork() {
915          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 942 | Line 949 | public abstract class ForkJoinTask<V> im
949      // Extension methods
950  
951      /**
952 <     * Returns the result that would be returned by {@code join},
953 <     * even if this task completed abnormally, or null if this task is
954 <     * not known to have been completed.  This method is designed to
955 <     * aid debugging, as well as to support extensions. Its use in any
956 <     * other context is discouraged.
952 >     * Returns the result that would be returned by {@link #join}, even
953 >     * if this task completed abnormally, or {@code null} if this task
954 >     * is not known to have been completed.  This method is designed
955 >     * to aid debugging, as well as to support extensions. Its use in
956 >     * any other context is discouraged.
957       *
958 <     * @return the result, or null if not completed
958 >     * @return the result, or {@code null} if not completed
959       */
960      public abstract V getRawResult();
961  
# Line 967 | Line 974 | public abstract class ForkJoinTask<V> im
974       * called otherwise. The return value controls whether this task
975       * is considered to be done normally. It may return false in
976       * asynchronous actions that require explicit invocations of
977 <     * {@code complete} to become joinable. It may throw exceptions
977 >     * {@link #complete} to become joinable. It may throw exceptions
978       * to indicate abnormal exit.
979       *
980 <     * @return true if completed normally
980 >     * @return {@code true} if completed normally
981       * @throws Error or RuntimeException if encountered during computation
982       */
983      protected abstract boolean exec();
# Line 986 | Line 993 | public abstract class ForkJoinTask<V> im
993       * #inForkJoinPool}). Attempts to invoke in other contexts result
994       * in exceptions or errors, possibly including ClassCastException.
995       *
996 <     * @return the next task, or null if none are available
996 >     * @return the next task, or {@code null} if none are available
997       */
998      protected static ForkJoinTask<?> peekNextLocalTask() {
999          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1003 | Line 1010 | public abstract class ForkJoinTask<V> im
1010       * contexts result in exceptions or errors, possibly including
1011       * ClassCastException.
1012       *
1013 <     * @return the next task, or null if none are available
1013 >     * @return the next task, or {@code null} if none are available
1014       */
1015      protected static ForkJoinTask<?> pollNextLocalTask() {
1016          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1024 | Line 1031 | public abstract class ForkJoinTask<V> im
1031       * result in exceptions or errors, possibly including
1032       * ClassCastException.
1033       *
1034 <     * @return a task, or null if none are available
1034 >     * @return a task, or {@code null} if none are available
1035       */
1036      protected static ForkJoinTask<?> pollTask() {
1037          return ((ForkJoinWorkerThread) Thread.currentThread())
1038              .pollTask();
1039      }
1040  
1041 +    // adaptors
1042 +
1043 +    /**
1044 +     * Returns a new ForkJoinTask that performs the {@code run}
1045 +     * method of the given Runnable as its action, and returns a null
1046 +     * result upon {@code join}.
1047 +     *
1048 +     * @param runnable the runnable action
1049 +     * @return the task
1050 +     */
1051 +    public static ForkJoinTask<Void> adapt(Runnable runnable) {
1052 +        return new ForkJoinPool.AdaptedRunnable<Void>(runnable, null);
1053 +    }
1054 +
1055 +    /**
1056 +     * Returns a new ForkJoinTask that performs the {@code run}
1057 +     * method of the given Runnable as its action, and returns the
1058 +     * given result upon {@code join}.
1059 +     *
1060 +     * @param runnable the runnable action
1061 +     * @param result the result upon completion
1062 +     * @return the task
1063 +     */
1064 +    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1065 +        return new ForkJoinPool.AdaptedRunnable<T>(runnable, result);
1066 +    }
1067 +
1068 +    /**
1069 +     * Returns a new ForkJoinTask that performs the {@code call}
1070 +     * method of the given Callable as its action, and returns its
1071 +     * result upon {@code join}, translating any checked
1072 +     * exceptions encountered into {@code RuntimeException}.
1073 +     *
1074 +     * @param callable the callable action
1075 +     * @return the task
1076 +     */
1077 +    public static <T> ForkJoinTask<T> adapt(Callable<T> callable) {
1078 +        return new ForkJoinPool.AdaptedCallable<T>(callable);
1079 +    }
1080 +
1081      // Serialization support
1082  
1083      private static final long serialVersionUID = -7721805057305804111L;
# Line 1039 | Line 1086 | public abstract class ForkJoinTask<V> im
1086       * Save the state to a stream.
1087       *
1088       * @serialData the current run status and the exception thrown
1089 <     * during execution, or null if none
1089 >     * during execution, or {@code null} if none
1090       * @param s the stream
1091       */
1092      private void writeObject(java.io.ObjectOutputStream s)
# Line 1063 | Line 1110 | public abstract class ForkJoinTask<V> im
1110              setDoneExceptionally((Throwable) ex);
1111      }
1112  
1113 <    // Temporary Unsafe mechanics for preliminary release
1114 <    private static Unsafe getUnsafe() throws Throwable {
1113 >    // Unsafe mechanics
1114 >
1115 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1116 >    private static final long statusOffset =
1117 >        objectFieldOffset("status", ForkJoinTask.class);
1118 >
1119 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1120 >        try {
1121 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1122 >        } catch (NoSuchFieldException e) {
1123 >            // Convert Exception to corresponding Error
1124 >            NoSuchFieldError error = new NoSuchFieldError(field);
1125 >            error.initCause(e);
1126 >            throw error;
1127 >        }
1128 >    }
1129 >
1130 >    /**
1131 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1132 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1133 >     * into a jdk.
1134 >     *
1135 >     * @return a sun.misc.Unsafe
1136 >     */
1137 >    private static sun.misc.Unsafe getUnsafe() {
1138          try {
1139 <            return Unsafe.getUnsafe();
1139 >            return sun.misc.Unsafe.getUnsafe();
1140          } catch (SecurityException se) {
1141              try {
1142                  return java.security.AccessController.doPrivileged
1143 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1144 <                        public Unsafe run() throws Exception {
1145 <                            return getUnsafePrivileged();
1143 >                    (new java.security
1144 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1145 >                        public sun.misc.Unsafe run() throws Exception {
1146 >                            java.lang.reflect.Field f = sun.misc
1147 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1148 >                            f.setAccessible(true);
1149 >                            return (sun.misc.Unsafe) f.get(null);
1150                          }});
1151              } catch (java.security.PrivilegedActionException e) {
1152 <                throw e.getCause();
1152 >                throw new RuntimeException("Could not initialize intrinsics",
1153 >                                           e.getCause());
1154              }
1155          }
1156      }
1082
1083    private static Unsafe getUnsafePrivileged()
1084            throws NoSuchFieldException, IllegalAccessException {
1085        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1086        f.setAccessible(true);
1087        return (Unsafe) f.get(null);
1088    }
1089
1090    private static long fieldOffset(String fieldName)
1091            throws NoSuchFieldException {
1092        return UNSAFE.objectFieldOffset
1093            (ForkJoinTask.class.getDeclaredField(fieldName));
1094    }
1095
1096    static final Unsafe UNSAFE;
1097    static final long statusOffset;
1098
1099    static {
1100        try {
1101            UNSAFE = getUnsafe();
1102            statusOffset = fieldOffset("status");
1103        } catch (Throwable e) {
1104            throw new RuntimeException("Could not initialize intrinsics", e);
1105        }
1106    }
1107
1157   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines