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.13 by dl, Wed Jul 22 19:04:11 2009 UTC vs.
Revision 1.16 by jsr166, Fri Jul 24 23:47:01 2009 UTC

# Line 9 | Line 9 | import java.io.Serializable;
9   import java.util.*;
10   import java.util.concurrent.*;
11   import java.util.concurrent.atomic.*;
12 import sun.misc.Unsafe;
13 import java.lang.reflect.*;
12  
13   /**
14   * Abstract base class for tasks that run within a {@link
# Line 83 | Line 81 | import java.lang.reflect.*;
81   * methods), some of them may only be called from within other
82   * ForkJoinTasks (as may be determined using method {@link
83   * #inForkJoinPool}).  Attempts to invoke them in other contexts
84 < * result in exceptions or errors possibly including
84 > * result in exceptions or errors, possibly including
85   * ClassCastException.
86   *
87   * <p>Most base support methods are {@code final} because their
# Line 162 | Line 160 | public abstract class ForkJoinTask<V> im
160       */
161      static ForkJoinWorkerThread getWorker() {
162          Thread t = Thread.currentThread();
163 <        return ((t instanceof ForkJoinWorkerThread)?
164 <                (ForkJoinWorkerThread)t : null);
163 >        return ((t instanceof ForkJoinWorkerThread) ?
164 >                (ForkJoinWorkerThread) t : null);
165      }
166  
167      final boolean casStatus(int cmp, int val) {
# Line 189 | Line 187 | public abstract class ForkJoinTask<V> im
187          ForkJoinPool pool = getPool();
188          if (pool != null) {
189              int s; // Clear signal bits while setting completion status
190 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
190 >            do {} while ((s = status) >= 0 && !casStatus(s, completion));
191  
192              if ((s & SIGNAL_MASK) != 0) {
193                  if ((s &= INTERNAL_SIGNAL_MASK) != 0)
194                      pool.updateRunningCount(s);
195 <                synchronized(this) { notifyAll(); }
195 >                synchronized (this) { notifyAll(); }
196              }
197          }
198          else
# Line 207 | Line 205 | public abstract class ForkJoinTask<V> im
205       */
206      private void externallySetCompletion(int completion) {
207          int s;
208 <        do;while ((s = status) >= 0 &&
209 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
210 <        synchronized(this) { notifyAll(); }
208 >        do {} while ((s = status) >= 0 &&
209 >                     !casStatus(s, (s & SIGNAL_MASK) | completion));
210 >        synchronized (this) { notifyAll(); }
211      }
212  
213      /**
214 <     * Sets status to indicate normal completion
214 >     * Sets status to indicate normal completion.
215       */
216      final void setNormalCompletion() {
217          // Try typical fast case -- single CAS, no signal, not already done.
# Line 225 | Line 223 | public abstract class ForkJoinTask<V> im
223      // internal waiting and notification
224  
225      /**
226 <     * Performs the actual monitor wait for awaitDone
226 >     * Performs the actual monitor wait for awaitDone.
227       */
228      private void doAwaitDone() {
229          // Minimize lock bias and in/de-flation effects by maximizing
230          // chances of waiting inside sync
231          try {
232              while (status >= 0)
233 <                synchronized(this) { if (status >= 0) wait(); }
233 >                synchronized (this) { if (status >= 0) wait(); }
234          } catch (InterruptedException ie) {
235              onInterruptedWait();
236          }
237      }
238  
239      /**
240 <     * Performs the actual monitor wait for awaitDone
240 >     * Performs the actual timed monitor wait for awaitDone.
241       */
242      private void doAwaitDone(long startTime, long nanos) {
243 <        synchronized(this) {
243 >        synchronized (this) {
244              try {
245                  while (status >= 0) {
246                      long nt = nanos - System.nanoTime() - startTime;
247                      if (nt <= 0)
248                          break;
249 <                    wait(nt / 1000000, (int)(nt % 1000000));
249 >                    wait(nt / 1000000, (int) (nt % 1000000));
250                  }
251              } catch (InterruptedException ie) {
252                  onInterruptedWait();
# Line 264 | Line 262 | public abstract class ForkJoinTask<V> im
262       *
263       * @return status upon exit
264       */
265 <    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
266 <        ForkJoinPool pool = w == null? null : w.pool;
265 >    private int awaitDone(ForkJoinWorkerThread w,
266 >                          boolean maintainParallelism) {
267 >        ForkJoinPool pool = (w == null) ? null : w.pool;
268          int s;
269          while ((s = status) >= 0) {
270 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
270 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
271                  if (pool == null || !pool.preJoin(this, maintainParallelism))
272                      doAwaitDone();
273                  if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
# Line 281 | Line 280 | public abstract class ForkJoinTask<V> im
280  
281      /**
282       * Timed version of awaitDone
283 +     *
284       * @return status upon exit
285       */
286      private int awaitDone(ForkJoinWorkerThread w, long nanos) {
287 <        ForkJoinPool pool = w == null? null : w.pool;
287 >        ForkJoinPool pool = (w == null) ? null : w.pool;
288          int s;
289          while ((s = status) >= 0) {
290 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
290 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
291                  long startTime = System.nanoTime();
292                  if (pool == null || !pool.preJoin(this, false))
293                      doAwaitDone(startTime, nanos);
# Line 309 | Line 309 | public abstract class ForkJoinTask<V> im
309       */
310      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
311          int s;
312 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
312 >        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
313          if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
314              pool.updateRunningCount(s);
315      }
# Line 364 | Line 364 | public abstract class ForkJoinTask<V> im
364  
365      /**
366       * Returns result or throws exception using j.u.c.Future conventions.
367 <     * Only call when isDone known to be true.
367 >     * Only call when {@code isDone} known to be true.
368       */
369      private V reportFutureResult()
370          throws ExecutionException, InterruptedException {
# Line 430 | Line 430 | public abstract class ForkJoinTask<V> im
430              try {
431                  if (!exec())
432                      return;
433 <            } catch(Throwable rex) {
433 >            } catch (Throwable rex) {
434                  setDoneExceptionally(rex);
435                  return;
436              }
# Line 462 | Line 462 | public abstract class ForkJoinTask<V> im
462      final void cancelIgnoringExceptions() {
463          try {
464              cancel(false);
465 <        } catch(Throwable ignore) {
465 >        } catch (Throwable ignore) {
466          }
467      }
468  
# Line 474 | Line 474 | public abstract class ForkJoinTask<V> im
474          ForkJoinTask<?> t;
475          while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
476              t.quietlyExec();
477 <        return (s >= 0)? awaitDone(w, false) : s; // block if no work
477 >        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
478      }
479  
480      // public methods
# Line 486 | Line 486 | public abstract class ForkJoinTask<V> im
486       * method may be invoked only from within ForkJoinTask
487       * computations (as may be determined using method {@link
488       * #inForkJoinPool}). Attempts to invoke in other contexts result
489 <     * in exceptions or errors possibly including ClassCastException.
489 >     * in exceptions or errors, possibly including ClassCastException.
490       */
491      public final void fork() {
492 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
492 >        ((ForkJoinWorkerThread) Thread.currentThread())
493 >            .pushTask(this);
494      }
495  
496      /**
# Line 527 | Line 528 | public abstract class ForkJoinTask<V> im
528       * both of them or an exception is encountered. This method may be
529       * invoked only from within ForkJoinTask computations (as may be
530       * determined using method {@link #inForkJoinPool}). Attempts to
531 <     * invoke in other contexts result in exceptions or errors
531 >     * invoke in other contexts result in exceptions or errors,
532       * possibly including ClassCastException.
533       *
534       * @param t1 one task
# Line 547 | Line 548 | public abstract class ForkJoinTask<V> im
548       * may be cancelled.  This method may be invoked only from within
549       * ForkJoinTask computations (as may be determined using method
550       * {@link #inForkJoinPool}). Attempts to invoke in other contexts
551 <     * result in exceptions or errors possibly including
551 >     * result in exceptions or errors, possibly including
552       * ClassCastException.
553 +     *
554       * @param tasks the array of tasks
555       * @throws NullPointerException if tasks or any element are null
556       * @throws RuntimeException or Error if any task did so
# Line 592 | Line 594 | public abstract class ForkJoinTask<V> im
594       * encounters an exception, others may be cancelled.  This method
595       * may be invoked only from within ForkJoinTask computations (as
596       * may be determined using method {@link
597 <     * #inForkJoinPool}). Attempts to invoke in other contexts resul!t
598 <     * in exceptions or errors possibly including ClassCastException.
597 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
598 >     * in exceptions or errors, possibly including ClassCastException.
599       *
600       * @param tasks the collection of tasks
601       * @throws NullPointerException if tasks or any element are null
602       * @throws RuntimeException or Error if any task did so
603       */
604      public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
605 <        if (!(tasks instanceof List)) {
606 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
605 >        if (!(tasks instanceof List<?>)) {
606 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
607              return;
608          }
609 +        @SuppressWarnings("unchecked")
610          List<? extends ForkJoinTask<?>> ts =
611 <            (List<? extends ForkJoinTask<?>>)tasks;
611 >            (List<? extends ForkJoinTask<?>>) tasks;
612          Throwable ex = null;
613          int last = ts.size() - 1;
614          for (int i = last; i >= 0; --i) {
# Line 680 | Line 683 | public abstract class ForkJoinTask<V> im
683       *
684       * @param mayInterruptIfRunning this value is ignored in the
685       * default implementation because tasks are not in general
686 <     * cancelled via interruption.
686 >     * cancelled via interruption
687       *
688       * @return true if this task is now cancelled
689       */
# Line 730 | Line 733 | public abstract class ForkJoinTask<V> im
733       */
734      public void completeExceptionally(Throwable ex) {
735          setDoneExceptionally((ex instanceof RuntimeException) ||
736 <                             (ex instanceof Error)? ex :
736 >                             (ex instanceof Error) ? ex :
737                               new RuntimeException(ex));
738      }
739  
# Line 749 | Line 752 | public abstract class ForkJoinTask<V> im
752      public void complete(V value) {
753          try {
754              setRawResult(value);
755 <        } catch(Throwable rex) {
755 >        } catch (Throwable rex) {
756              setDoneExceptionally(rex);
757              return;
758          }
# Line 781 | Line 784 | public abstract class ForkJoinTask<V> im
784       * tasks). This method may be invoked only from within
785       * ForkJoinTask computations (as may be determined using method
786       * {@link #inForkJoinPool}). Attempts to invoke in other contexts
787 <     * resul!t in exceptions or errors possibly including
787 >     * result in exceptions or errors, possibly including
788       * ClassCastException.
789       *
790       * @return the computed result
791       */
792      public final V helpJoin() {
793 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
793 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
794          if (status < 0 || !w.unpushTask(this) || !tryExec())
795              reportException(busyJoin(w));
796          return getRawResult();
# Line 797 | Line 800 | public abstract class ForkJoinTask<V> im
800       * Possibly executes other tasks until this task is ready.  This
801       * method may be invoked only from within ForkJoinTask
802       * computations (as may be determined using method {@link
803 <     * #inForkJoinPool}). Attempts to invoke in other contexts resul!t
804 <     * in exceptions or errors possibly including ClassCastException.
803 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
804 >     * in exceptions or errors, possibly including ClassCastException.
805       */
806      public final void quietlyHelpJoin() {
807          if (status >= 0) {
808              ForkJoinWorkerThread w =
809 <                (ForkJoinWorkerThread)(Thread.currentThread());
809 >                (ForkJoinWorkerThread) Thread.currentThread();
810              if (!w.unpushTask(this) || !tryQuietlyInvoke())
811                  busyJoin(w);
812          }
# Line 842 | Line 845 | public abstract class ForkJoinTask<V> im
845       * joined, instead executing them until all are processed.
846       */
847      public static void helpQuiesce() {
848 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
849 <            helpQuiescePool();
848 >        ((ForkJoinWorkerThread) Thread.currentThread())
849 >            .helpQuiescePool();
850      }
851  
852      /**
# Line 866 | Line 869 | public abstract class ForkJoinTask<V> im
869       * Returns the pool hosting the current task execution, or null
870       * if this task is executing outside of any ForkJoinPool.
871       *
872 <     * @return the pool, or null if none.
872 >     * @return the pool, or null if none
873       */
874      public static ForkJoinPool getPool() {
875          Thread t = Thread.currentThread();
876 <        return ((t instanceof ForkJoinWorkerThread)?
877 <                ((ForkJoinWorkerThread)t).pool : null);
876 >        return (t instanceof ForkJoinWorkerThread) ?
877 >            ((ForkJoinWorkerThread) t).pool : null;
878      }
879  
880      /**
881 <     * Returns true if the current thread is executing as a
881 >     * Returns {@code true} if the current thread is executing as a
882       * ForkJoinPool computation.
883 <     * @return <code>true</code> if the current thread is executing as a
883 >     *
884 >     * @return {@code true} if the current thread is executing as a
885       * ForkJoinPool computation, or false otherwise
886       */
887      public static boolean inForkJoinPool() {
# Line 893 | Line 897 | public abstract class ForkJoinTask<V> im
897       * were not, stolen. This method may be invoked only from within
898       * ForkJoinTask computations (as may be determined using method
899       * {@link #inForkJoinPool}). Attempts to invoke in other contexts
900 <     * result in exceptions or errors possibly including
900 >     * result in exceptions or errors, possibly including
901       * ClassCastException.
902       *
903       * @return true if unforked
904       */
905      public boolean tryUnfork() {
906 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
906 >        return ((ForkJoinWorkerThread) Thread.currentThread())
907 >            .unpushTask(this);
908      }
909  
910      /**
# Line 911 | Line 916 | public abstract class ForkJoinTask<V> im
916       * @return the number of tasks
917       */
918      public static int getQueuedTaskCount() {
919 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
920 <            getQueueSize();
919 >        return ((ForkJoinWorkerThread) Thread.currentThread())
920 >            .getQueueSize();
921      }
922  
923      /**
# Line 928 | Line 933 | public abstract class ForkJoinTask<V> im
933       * @return the surplus number of tasks, which may be negative
934       */
935      public static int getSurplusQueuedTaskCount() {
936 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
936 >        return ((ForkJoinWorkerThread) Thread.currentThread())
937              .getEstimatedSurplusTaskCount();
938      }
939  
# Line 977 | Line 982 | public abstract class ForkJoinTask<V> im
982       * This method may be invoked only from within ForkJoinTask
983       * computations (as may be determined using method {@link
984       * #inForkJoinPool}). Attempts to invoke in other contexts result
985 <     * in exceptions or errors possibly including ClassCastException.
985 >     * in exceptions or errors, possibly including ClassCastException.
986       *
987       * @return the next task, or null if none are available
988       */
989      protected static ForkJoinTask<?> peekNextLocalTask() {
990 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
990 >        return ((ForkJoinWorkerThread) Thread.currentThread())
991 >            .peekTask();
992      }
993  
994      /**
# Line 992 | Line 998 | public abstract class ForkJoinTask<V> im
998       * be useful otherwise.  This method may be invoked only from
999       * within ForkJoinTask computations (as may be determined using
1000       * method {@link #inForkJoinPool}). Attempts to invoke in other
1001 <     * contexts result in exceptions or errors possibly including
1001 >     * contexts result in exceptions or errors, possibly including
1002       * ClassCastException.
1003       *
1004       * @return the next task, or null if none are available
1005       */
1006      protected static ForkJoinTask<?> pollNextLocalTask() {
1007 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
1007 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1008 >            .pollLocalTask();
1009      }
1010  
1011      /**
# Line 1012 | Line 1019 | public abstract class ForkJoinTask<V> im
1019       * otherwise.  This method may be invoked only from within
1020       * ForkJoinTask computations (as may be determined using method
1021       * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1022 <     * result in exceptions or errors possibly including
1022 >     * result in exceptions or errors, possibly including
1023       * ClassCastException.
1024       *
1025       * @return a task, or null if none are available
1026       */
1027      protected static ForkJoinTask<?> pollTask() {
1028 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1029 <            pollTask();
1028 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1029 >            .pollTask();
1030      }
1031  
1032      // Serialization support
# Line 1051 | Line 1058 | public abstract class ForkJoinTask<V> im
1058          status |= EXTERNAL_SIGNAL; // conservatively set external signal
1059          Object ex = s.readObject();
1060          if (ex != null)
1061 <            setDoneExceptionally((Throwable)ex);
1061 >            setDoneExceptionally((Throwable) ex);
1062      }
1063  
1064 <    // Temporary Unsafe mechanics for preliminary release
1065 <    private static Unsafe getUnsafe() throws Throwable {
1064 >    // Unsafe mechanics for jsr166y 3rd party package.
1065 >    private static sun.misc.Unsafe getUnsafe() {
1066          try {
1067 <            return Unsafe.getUnsafe();
1067 >            return sun.misc.Unsafe.getUnsafe();
1068          } catch (SecurityException se) {
1069              try {
1070                  return java.security.AccessController.doPrivileged
1071 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1072 <                        public Unsafe run() throws Exception {
1073 <                            return getUnsafePrivileged();
1071 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1072 >                        public sun.misc.Unsafe run() throws Exception {
1073 >                            return getUnsafeByReflection();
1074                          }});
1075              } catch (java.security.PrivilegedActionException e) {
1076 <                throw e.getCause();
1076 >                throw new RuntimeException("Could not initialize intrinsics",
1077 >                                           e.getCause());
1078              }
1079          }
1080      }
1081  
1082 <    private static Unsafe getUnsafePrivileged()
1082 >    private static sun.misc.Unsafe getUnsafeByReflection()
1083              throws NoSuchFieldException, IllegalAccessException {
1084 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1084 >        java.lang.reflect.Field f =
1085 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1086          f.setAccessible(true);
1087 <        return (Unsafe) f.get(null);
1079 <    }
1080 <
1081 <    private static long fieldOffset(String fieldName)
1082 <            throws NoSuchFieldException {
1083 <        return UNSAFE.objectFieldOffset
1084 <            (ForkJoinTask.class.getDeclaredField(fieldName));
1087 >        return (sun.misc.Unsafe) f.get(null);
1088      }
1089  
1090 <    static final Unsafe UNSAFE;
1088 <    static final long statusOffset;
1089 <
1090 <    static {
1090 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
1091          try {
1092 <            UNSAFE = getUnsafe();
1093 <            statusOffset = fieldOffset("status");
1094 <        } catch (Throwable e) {
1095 <            throw new RuntimeException("Could not initialize intrinsics", e);
1092 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1093 >        } catch (NoSuchFieldException e) {
1094 >            // Convert Exception to Error
1095 >            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1096 >            error.initCause(e);
1097 >            throw error;
1098          }
1099      }
1100  
1101 +    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1102 +    static final long statusOffset =
1103 +        fieldOffset("status", ForkJoinTask.class);
1104 +
1105   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines