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.12 by jsr166, Wed Jul 22 01:36:51 2009 UTC vs.
Revision 1.17 by jsr166, Sat Jul 25 00:34:00 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 81 | Line 84 | import java.lang.reflect.*;
84   * class. While these methods have {@code public} access (to allow
85   * instances of different task subclasses to call each others
86   * methods), some of them may only be called from within other
87 < * ForkJoinTasks. Attempts to invoke them in other contexts result in
88 < * exceptions or errors possibly including ClassCastException.
87 > * ForkJoinTasks (as may be determined using method {@link
88 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
89 > * result in exceptions or errors, possibly including
90 > * ClassCastException.
91   *
92   * <p>Most base support methods are {@code final} because their
93   * implementations are intrinsically tied to the underlying
# Line 160 | Line 165 | public abstract class ForkJoinTask<V> im
165       */
166      static ForkJoinWorkerThread getWorker() {
167          Thread t = Thread.currentThread();
168 <        return ((t instanceof ForkJoinWorkerThread)?
169 <                (ForkJoinWorkerThread)t : null);
168 >        return ((t instanceof ForkJoinWorkerThread) ?
169 >                (ForkJoinWorkerThread) t : null);
170      }
171  
172      final boolean casStatus(int cmp, int val) {
# Line 187 | Line 192 | public abstract class ForkJoinTask<V> im
192          ForkJoinPool pool = getPool();
193          if (pool != null) {
194              int s; // Clear signal bits while setting completion status
195 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
195 >            do {} while ((s = status) >= 0 && !casStatus(s, completion));
196  
197              if ((s & SIGNAL_MASK) != 0) {
198                  if ((s &= INTERNAL_SIGNAL_MASK) != 0)
199                      pool.updateRunningCount(s);
200 <                synchronized(this) { notifyAll(); }
200 >                synchronized (this) { notifyAll(); }
201              }
202          }
203          else
# Line 205 | Line 210 | public abstract class ForkJoinTask<V> im
210       */
211      private void externallySetCompletion(int completion) {
212          int s;
213 <        do;while ((s = status) >= 0 &&
214 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
215 <        synchronized(this) { notifyAll(); }
213 >        do {} while ((s = status) >= 0 &&
214 >                     !casStatus(s, (s & SIGNAL_MASK) | completion));
215 >        synchronized (this) { notifyAll(); }
216      }
217  
218      /**
219 <     * Sets status to indicate normal completion
219 >     * Sets status to indicate normal completion.
220       */
221      final void setNormalCompletion() {
222          // Try typical fast case -- single CAS, no signal, not already done.
# Line 223 | Line 228 | public abstract class ForkJoinTask<V> im
228      // internal waiting and notification
229  
230      /**
231 <     * Performs the actual monitor wait for awaitDone
231 >     * Performs the actual monitor wait for awaitDone.
232       */
233      private void doAwaitDone() {
234          // Minimize lock bias and in/de-flation effects by maximizing
235          // chances of waiting inside sync
236          try {
237              while (status >= 0)
238 <                synchronized(this) { if (status >= 0) wait(); }
238 >                synchronized (this) { if (status >= 0) wait(); }
239          } catch (InterruptedException ie) {
240              onInterruptedWait();
241          }
242      }
243  
244      /**
245 <     * Performs the actual monitor wait for awaitDone
245 >     * Performs the actual timed monitor wait for awaitDone.
246       */
247      private void doAwaitDone(long startTime, long nanos) {
248 <        synchronized(this) {
248 >        synchronized (this) {
249              try {
250                  while (status >= 0) {
251                      long nt = nanos - System.nanoTime() - startTime;
252                      if (nt <= 0)
253                          break;
254 <                    wait(nt / 1000000, (int)(nt % 1000000));
254 >                    wait(nt / 1000000, (int) (nt % 1000000));
255                  }
256              } catch (InterruptedException ie) {
257                  onInterruptedWait();
# Line 262 | Line 267 | public abstract class ForkJoinTask<V> im
267       *
268       * @return status upon exit
269       */
270 <    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
271 <        ForkJoinPool pool = w == null? null : w.pool;
270 >    private int awaitDone(ForkJoinWorkerThread w,
271 >                          boolean maintainParallelism) {
272 >        ForkJoinPool pool = (w == null) ? null : w.pool;
273          int s;
274          while ((s = status) >= 0) {
275 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
275 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
276                  if (pool == null || !pool.preJoin(this, maintainParallelism))
277                      doAwaitDone();
278                  if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
# Line 279 | Line 285 | public abstract class ForkJoinTask<V> im
285  
286      /**
287       * Timed version of awaitDone
288 +     *
289       * @return status upon exit
290       */
291      private int awaitDone(ForkJoinWorkerThread w, long nanos) {
292 <        ForkJoinPool pool = w == null? null : w.pool;
292 >        ForkJoinPool pool = (w == null) ? null : w.pool;
293          int s;
294          while ((s = status) >= 0) {
295 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
295 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
296                  long startTime = System.nanoTime();
297                  if (pool == null || !pool.preJoin(this, false))
298                      doAwaitDone(startTime, nanos);
# Line 307 | Line 314 | public abstract class ForkJoinTask<V> im
314       */
315      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
316          int s;
317 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
317 >        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
318          if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
319              pool.updateRunningCount(s);
320      }
# Line 362 | Line 369 | public abstract class ForkJoinTask<V> im
369  
370      /**
371       * Returns result or throws exception using j.u.c.Future conventions.
372 <     * Only call when isDone known to be true.
372 >     * Only call when {@code isDone} known to be true.
373       */
374      private V reportFutureResult()
375          throws ExecutionException, InterruptedException {
# Line 428 | Line 435 | public abstract class ForkJoinTask<V> im
435              try {
436                  if (!exec())
437                      return;
438 <            } catch(Throwable rex) {
438 >            } catch (Throwable rex) {
439                  setDoneExceptionally(rex);
440                  return;
441              }
# Line 460 | Line 467 | public abstract class ForkJoinTask<V> im
467      final void cancelIgnoringExceptions() {
468          try {
469              cancel(false);
470 <        } catch(Throwable ignore) {
470 >        } catch (Throwable ignore) {
471          }
472      }
473  
# Line 472 | Line 479 | public abstract class ForkJoinTask<V> im
479          ForkJoinTask<?> t;
480          while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
481              t.quietlyExec();
482 <        return (s >= 0)? awaitDone(w, false) : s; // block if no work
482 >        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
483      }
484  
485      // public methods
# Line 482 | Line 489 | public abstract class ForkJoinTask<V> im
489       * necessarily enforced, it is a usage error to fork a task more
490       * than once unless it has completed and been reinitialized.  This
491       * method may be invoked only from within ForkJoinTask
492 <     * computations. Attempts to invoke in other contexts result in
493 <     * exceptions or errors possibly including ClassCastException.
492 >     * computations (as may be determined using method {@link
493 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
494 >     * in exceptions or errors, possibly including ClassCastException.
495       */
496      public final void fork() {
497 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
497 >        ((ForkJoinWorkerThread) Thread.currentThread())
498 >            .pushTask(this);
499      }
500  
501      /**
# Line 522 | Line 531 | public abstract class ForkJoinTask<V> im
531      /**
532       * Forks both tasks, returning when {@code isDone} holds for
533       * both of them or an exception is encountered. This method may be
534 <     * invoked only from within ForkJoinTask computations. Attempts to
535 <     * invoke in other contexts result in exceptions or errors
534 >     * invoked only from within ForkJoinTask computations (as may be
535 >     * determined using method {@link #inForkJoinPool}). Attempts to
536 >     * invoke in other contexts result in exceptions or errors,
537       * possibly including ClassCastException.
538       *
539       * @param t1 one task
# Line 541 | Line 551 | public abstract class ForkJoinTask<V> im
551       * Forks the given tasks, returning when {@code isDone} holds
552       * for all of them. If any task encounters an exception, others
553       * may be cancelled.  This method may be invoked only from within
554 <     * ForkJoinTask computations. Attempts to invoke in other contexts
555 <     * result in exceptions or errors possibly including ClassCastException.
554 >     * ForkJoinTask computations (as may be determined using method
555 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
556 >     * result in exceptions or errors, possibly including
557 >     * ClassCastException.
558       *
559       * @param tasks the array of tasks
560       * @throws NullPointerException if tasks or any element are null
# Line 585 | Line 597 | public abstract class ForkJoinTask<V> im
597       * Forks all tasks in the collection, returning when
598       * {@code isDone} holds for all of them. If any task
599       * encounters an exception, others may be cancelled.  This method
600 <     * may be invoked only from within ForkJoinTask
601 <     * computations. Attempts to invoke in other contexts result in
602 <     * exceptions or errors possibly including ClassCastException.
600 >     * may be invoked only from within ForkJoinTask computations (as
601 >     * may be determined using method {@link
602 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
603 >     * in exceptions or errors, possibly including ClassCastException.
604       *
605       * @param tasks the collection of tasks
606       * @throws NullPointerException if tasks or any element are null
607       * @throws RuntimeException or Error if any task did so
608       */
609      public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
610 <        if (!(tasks instanceof List)) {
611 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
610 >        if (!(tasks instanceof List<?>)) {
611 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
612              return;
613          }
614 +        @SuppressWarnings("unchecked")
615          List<? extends ForkJoinTask<?>> ts =
616 <            (List<? extends ForkJoinTask<?>>)tasks;
616 >            (List<? extends ForkJoinTask<?>>) tasks;
617          Throwable ex = null;
618          int last = ts.size() - 1;
619          for (int i = last; i >= 0; --i) {
# Line 674 | Line 688 | public abstract class ForkJoinTask<V> im
688       *
689       * @param mayInterruptIfRunning this value is ignored in the
690       * default implementation because tasks are not in general
691 <     * cancelled via interruption.
691 >     * cancelled via interruption
692       *
693       * @return true if this task is now cancelled
694       */
# Line 724 | Line 738 | public abstract class ForkJoinTask<V> im
738       */
739      public void completeExceptionally(Throwable ex) {
740          setDoneExceptionally((ex instanceof RuntimeException) ||
741 <                             (ex instanceof Error)? ex :
741 >                             (ex instanceof Error) ? ex :
742                               new RuntimeException(ex));
743      }
744  
# Line 743 | Line 757 | public abstract class ForkJoinTask<V> im
757      public void complete(V value) {
758          try {
759              setRawResult(value);
760 <        } catch(Throwable rex) {
760 >        } catch (Throwable rex) {
761              setDoneExceptionally(rex);
762              return;
763          }
# Line 773 | Line 787 | public abstract class ForkJoinTask<V> im
787       * current task and that of any other task that might be executed
788       * while helping. (This usually holds for pure divide-and-conquer
789       * tasks). This method may be invoked only from within
790 <     * ForkJoinTask computations. Attempts to invoke in other contexts
791 <     * result in exceptions or errors possibly including ClassCastException.
790 >     * ForkJoinTask computations (as may be determined using method
791 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
792 >     * result in exceptions or errors, possibly including
793 >     * ClassCastException.
794       *
795       * @return the computed result
796       */
797      public final V helpJoin() {
798 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
798 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
799          if (status < 0 || !w.unpushTask(this) || !tryExec())
800              reportException(busyJoin(w));
801          return getRawResult();
# Line 788 | Line 804 | public abstract class ForkJoinTask<V> im
804      /**
805       * Possibly executes other tasks until this task is ready.  This
806       * method may be invoked only from within ForkJoinTask
807 <     * computations. Attempts to invoke in other contexts result in
808 <     * exceptions or errors possibly including ClassCastException.
807 >     * computations (as may be determined using method {@link
808 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
809 >     * in exceptions or errors, possibly including ClassCastException.
810       */
811      public final void quietlyHelpJoin() {
812          if (status >= 0) {
813              ForkJoinWorkerThread w =
814 <                (ForkJoinWorkerThread)(Thread.currentThread());
814 >                (ForkJoinWorkerThread) Thread.currentThread();
815              if (!w.unpushTask(this) || !tryQuietlyInvoke())
816                  busyJoin(w);
817          }
# Line 833 | Line 850 | public abstract class ForkJoinTask<V> im
850       * joined, instead executing them until all are processed.
851       */
852      public static void helpQuiesce() {
853 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
854 <            helpQuiescePool();
853 >        ((ForkJoinWorkerThread) Thread.currentThread())
854 >            .helpQuiescePool();
855      }
856  
857      /**
# Line 855 | Line 872 | public abstract class ForkJoinTask<V> im
872  
873      /**
874       * Returns the pool hosting the current task execution, or null
875 <     * if this task is executing outside of any pool.
875 >     * if this task is executing outside of any ForkJoinPool.
876       *
877       * @return the pool, or null if none
878       */
879      public static ForkJoinPool getPool() {
880          Thread t = Thread.currentThread();
881 <        return ((t instanceof ForkJoinWorkerThread)?
882 <                ((ForkJoinWorkerThread)t).pool : null);
881 >        return (t instanceof ForkJoinWorkerThread) ?
882 >            ((ForkJoinWorkerThread) t).pool : null;
883 >    }
884 >
885 >    /**
886 >     * Returns {@code true} if the current thread is executing as a
887 >     * ForkJoinPool computation.
888 >     *
889 >     * @return {@code true} if the current thread is executing as a
890 >     * ForkJoinPool computation, or false otherwise
891 >     */
892 >    public static boolean inForkJoinPool() {
893 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
894      }
895  
896      /**
# Line 872 | Line 900 | public abstract class ForkJoinTask<V> im
900       * another thread.  This method may be useful when arranging
901       * alternative local processing of tasks that could have been, but
902       * were not, stolen. This method may be invoked only from within
903 <     * ForkJoinTask computations. Attempts to invoke in other contexts
904 <     * result in exceptions or errors possibly including ClassCastException.
903 >     * ForkJoinTask computations (as may be determined using method
904 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
905 >     * result in exceptions or errors, possibly including
906 >     * ClassCastException.
907       *
908       * @return true if unforked
909       */
910      public boolean tryUnfork() {
911 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
911 >        return ((ForkJoinWorkerThread) Thread.currentThread())
912 >            .unpushTask(this);
913      }
914  
915      /**
# Line 890 | Line 921 | public abstract class ForkJoinTask<V> im
921       * @return the number of tasks
922       */
923      public static int getQueuedTaskCount() {
924 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
925 <            getQueueSize();
924 >        return ((ForkJoinWorkerThread) Thread.currentThread())
925 >            .getQueueSize();
926      }
927  
928      /**
# Line 907 | Line 938 | public abstract class ForkJoinTask<V> im
938       * @return the surplus number of tasks, which may be negative
939       */
940      public static int getSurplusQueuedTaskCount() {
941 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
941 >        return ((ForkJoinWorkerThread) Thread.currentThread())
942              .getEstimatedSurplusTaskCount();
943      }
944  
# Line 954 | Line 985 | public abstract class ForkJoinTask<V> im
985       * be polled or executed next.  This method is designed primarily
986       * to support extensions, and is unlikely to be useful otherwise.
987       * This method may be invoked only from within ForkJoinTask
988 <     * computations. Attempts to invoke in other contexts result in
989 <     * exceptions or errors possibly including ClassCastException.
988 >     * computations (as may be determined using method {@link
989 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
990 >     * in exceptions or errors, possibly including ClassCastException.
991       *
992       * @return the next task, or null if none are available
993       */
994      protected static ForkJoinTask<?> peekNextLocalTask() {
995 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
995 >        return ((ForkJoinWorkerThread) Thread.currentThread())
996 >            .peekTask();
997      }
998  
999      /**
# Line 968 | Line 1001 | public abstract class ForkJoinTask<V> im
1001       * queued by the current thread but not yet executed.  This method
1002       * is designed primarily to support extensions, and is unlikely to
1003       * be useful otherwise.  This method may be invoked only from
1004 <     * within ForkJoinTask computations. Attempts to invoke in other
1005 <     * contexts result in exceptions or errors possibly including
1004 >     * within ForkJoinTask computations (as may be determined using
1005 >     * method {@link #inForkJoinPool}). Attempts to invoke in other
1006 >     * contexts result in exceptions or errors, possibly including
1007       * ClassCastException.
1008       *
1009       * @return the next task, or null if none are available
1010       */
1011      protected static ForkJoinTask<?> pollNextLocalTask() {
1012 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
1012 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1013 >            .pollLocalTask();
1014      }
1015  
1016      /**
# Line 987 | Line 1022 | public abstract class ForkJoinTask<V> im
1022       * of the pool this task is operating in.  This method is designed
1023       * primarily to support extensions, and is unlikely to be useful
1024       * otherwise.  This method may be invoked only from within
1025 <     * ForkJoinTask computations. Attempts to invoke in other contexts
1026 <     * result in exceptions or errors possibly including
1025 >     * ForkJoinTask computations (as may be determined using method
1026 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1027 >     * result in exceptions or errors, possibly including
1028       * ClassCastException.
1029       *
1030       * @return a task, or null if none are available
1031       */
1032      protected static ForkJoinTask<?> pollTask() {
1033 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1034 <            pollTask();
1033 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1034 >            .pollTask();
1035      }
1036  
1037      // Serialization support
# Line 1027 | Line 1063 | public abstract class ForkJoinTask<V> im
1063          status |= EXTERNAL_SIGNAL; // conservatively set external signal
1064          Object ex = s.readObject();
1065          if (ex != null)
1066 <            setDoneExceptionally((Throwable)ex);
1066 >            setDoneExceptionally((Throwable) ex);
1067      }
1068  
1069 <    // Temporary Unsafe mechanics for preliminary release
1070 <    private static Unsafe getUnsafe() throws Throwable {
1069 >    // Unsafe mechanics for jsr166y 3rd party package.
1070 >    private static sun.misc.Unsafe getUnsafe() {
1071          try {
1072 <            return Unsafe.getUnsafe();
1072 >            return sun.misc.Unsafe.getUnsafe();
1073          } catch (SecurityException se) {
1074              try {
1075                  return java.security.AccessController.doPrivileged
1076 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1077 <                        public Unsafe run() throws Exception {
1078 <                            return getUnsafePrivileged();
1076 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1077 >                        public sun.misc.Unsafe run() throws Exception {
1078 >                            return getUnsafeByReflection();
1079                          }});
1080              } catch (java.security.PrivilegedActionException e) {
1081 <                throw e.getCause();
1081 >                throw new RuntimeException("Could not initialize intrinsics",
1082 >                                           e.getCause());
1083              }
1084          }
1085      }
1086  
1087 <    private static Unsafe getUnsafePrivileged()
1087 >    private static sun.misc.Unsafe getUnsafeByReflection()
1088              throws NoSuchFieldException, IllegalAccessException {
1089 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1089 >        java.lang.reflect.Field f =
1090 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1091          f.setAccessible(true);
1092 <        return (Unsafe) f.get(null);
1092 >        return (sun.misc.Unsafe) f.get(null);
1093      }
1094  
1095 <    private static long fieldOffset(String fieldName)
1058 <            throws NoSuchFieldException {
1059 <        return UNSAFE.objectFieldOffset
1060 <            (ForkJoinTask.class.getDeclaredField(fieldName));
1061 <    }
1062 <
1063 <    static final Unsafe UNSAFE;
1064 <    static final long statusOffset;
1065 <
1066 <    static {
1095 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
1096          try {
1097 <            UNSAFE = getUnsafe();
1098 <            statusOffset = fieldOffset("status");
1099 <        } catch (Throwable e) {
1100 <            throw new RuntimeException("Could not initialize intrinsics", e);
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 +
1110   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines