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.5 by jsr166, Thu Mar 19 05:10:42 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 22 | Line 20 | import java.lang.reflect.*;
20   * <p> A "main" ForkJoinTask begins execution when submitted to a
21   * {@link ForkJoinPool}. Once started, it will usually in turn start
22   * other subtasks.  As indicated by the name of this class, many
23 < * programs using ForkJoinTasks employ only methods <code>fork</code>
24 < * and <code>join</code>, or derivatives such as
25 < * <code>invokeAll</code>.  However, this class also provides a number
23 > * programs using ForkJoinTasks employ only methods {@code fork}
24 > * and {@code join}, or derivatives such as
25 > * {@code invokeAll}.  However, this class also provides a number
26   * of other methods that can come into play in advanced usages, as
27   * well as extension mechanics that allow support of new forms of
28   * fork/join processing.
# Line 36 | Line 34 | import java.lang.reflect.*;
34   * operating on purely isolated objects.  The primary coordination
35   * mechanisms are {@link #fork}, that arranges asynchronous execution,
36   * and {@link #join}, that doesn't proceed until the task's result has
37 < * been computed.  Computations should avoid <code>synchronized</code>
37 > * been computed.  Computations should avoid {@code synchronized}
38   * methods or blocks, and should minimize other blocking
39   * synchronization apart from joining other tasks or using
40   * synchronizers such as Phasers that are advertised to cooperate with
# Line 48 | Line 46 | import java.lang.reflect.*;
46   * performance, and the potential to indefinitely stall if the number
47   * of threads not waiting for IO or other external synchronization
48   * becomes exhausted. This usage restriction is in part enforced by
49 < * not permitting checked exceptions such as <code>IOExceptions</code>
49 > * not permitting checked exceptions such as {@code IOExceptions}
50   * to be thrown. However, computations may still encounter unchecked
51   * exceptions, that are rethrown to callers attempting join
52   * them. These exceptions may additionally include
# Line 58 | Line 56 | import java.lang.reflect.*;
56   * <p>The primary method for awaiting completion and extracting
57   * results of a task is {@link #join}, but there are several variants:
58   * The {@link Future#get} methods support interruptible and/or timed
59 < * waits for completion and report results using <code>Future</code>
59 > * waits for completion and report results using {@code Future}
60   * conventions. Method {@link #helpJoin} enables callers to actively
61   * execute other tasks while awaiting joins, which is sometimes more
62   * efficient but only applies when all subtasks are known to be
63   * strictly tree-structured. Method {@link #invoke} is semantically
64 < * equivalent to <code>fork(); join()</code> but always attempts to
64 > * equivalent to {@code fork(); join()} but always attempts to
65   * begin execution in the current thread. The "<em>quiet</em>" forms
66   * of these methods do not extract results or report exceptions. These
67   * may be useful when a set of tasks are being executed, and you need
68   * to delay processing of results or exceptions until all complete.
69 < * Method <code>invokeAll</code> (available in multiple versions)
69 > * Method {@code invokeAll} (available in multiple versions)
70   * performs the most common form of parallel invocation: forking a set
71   * of tasks and joining them all.
72   *
# Line 76 | Line 74 | import java.lang.reflect.*;
74   * Instead, you subclass one of the abstract classes that support a
75   * particular style of fork/join processing.  Normally, a concrete
76   * ForkJoinTask subclass declares fields comprising its parameters,
77 < * established in a constructor, and then defines a <code>compute</code>
77 > * established in a constructor, and then defines a {@code compute}
78   * method that somehow uses the control methods supplied by this base
79 < * class. While these methods have <code>public</code> access (to allow
79 > * class. While these methods have {@code public} access (to allow
80   * instances of different task subclasses to call each others
81   * methods), some of them may only be called from within other
82 < * ForkJoinTasks. Attempts to invoke them in other contexts result in
83 < * exceptions or errors possibly including ClassCastException.
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
85 > * ClassCastException.
86   *
87 < * <p>Most base support methods are <code>final</code> because their
87 > * <p>Most base support methods are {@code final} because their
88   * implementations are intrinsically tied to the underlying
89   * lightweight task scheduling framework, and so cannot be overridden.
90   * Developers creating new basic styles of fork/join processing should
91 < * minimally implement <code>protected</code> methods
92 < * <code>exec</code>, <code>setRawResult</code>, and
93 < * <code>getRawResult</code>, while also introducing an abstract
91 > * minimally implement {@code protected} methods
92 > * {@code exec}, {@code setRawResult}, and
93 > * {@code getRawResult}, while also introducing an abstract
94   * computational method that can be implemented in its subclasses,
95 < * possibly relying on other <code>protected</code> methods provided
95 > * possibly relying on other {@code protected} methods provided
96   * by this class.
97   *
98   * <p>ForkJoinTasks should perform relatively small amounts of
99 < * computations, othewise splitting into smaller tasks. As a very
99 > * computations, otherwise splitting into smaller tasks. As a very
100   * rough rule of thumb, a task should perform more than 100 and less
101   * than 10000 basic computational steps. If tasks are too big, then
102 < * parellelism cannot improve throughput. If too small, then memory
102 > * parallelism cannot improve throughput. If too small, then memory
103   * and internal task maintenance overhead may overwhelm processing.
104   *
105 < * <p>ForkJoinTasks are <code>Serializable</code>, which enables them
105 > * <p>ForkJoinTasks are {@code Serializable}, which enables them
106   * to be used in extensions such as remote execution frameworks. It is
107   * in general sensible to serialize tasks only before or after, but
108   * not during execution. Serialization is not relied on during
109   * execution itself.
110 + *
111 + * @since 1.7
112 + * @author Doug Lea
113   */
114   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
115  
# Line 128 | Line 131 | public abstract class ForkJoinTask<V> im
131       * currently unused. Also value 0x80000000 is available as spare
132       * completion value.
133       */
134 <    volatile int status; // accessed directy by pool and workers
134 >    volatile int status; // accessed directly by pool and workers
135  
136      static final int COMPLETION_MASK      = 0xe0000000;
137      static final int NORMAL               = 0xe0000000; // == mask
# Line 141 | Line 144 | public abstract class ForkJoinTask<V> im
144      /**
145       * Table of exceptions thrown by tasks, to enable reporting by
146       * callers. Because exceptions are rare, we don't directly keep
147 <     * them with task objects, but instead us a weak ref table.  Note
147 >     * them with task objects, but instead use a weak ref table.  Note
148       * that cancellation exceptions don't appear in the table, but are
149       * instead recorded as status values.
150 <     * Todo: Use ConcurrentReferenceHashMap
150 >     * TODO: Use ConcurrentReferenceHashMap
151       */
152      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
153          Collections.synchronizedMap
# Line 153 | Line 156 | public abstract class ForkJoinTask<V> im
156      // within-package utilities
157  
158      /**
159 <     * Get current worker thread, or null if not a worker thread
159 >     * Gets current worker thread, or null if not a worker thread.
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) {
168 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
168 >        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
169      }
170  
171      /**
# Line 170 | Line 173 | public abstract class ForkJoinTask<V> im
173       */
174      static void rethrowException(Throwable ex) {
175          if (ex != null)
176 <            _unsafe.throwException(ex);
176 >            UNSAFE.throwException(ex);
177      }
178  
179      // Setting completion status
180  
181      /**
182 <     * Mark completion and wake up threads waiting to join this task.
182 >     * Marks completion and wakes up threads waiting to join this task.
183 >     *
184       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
185       */
186      final void setCompletion(int completion) {
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 201 | 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.
218          // Manually expand casStatus to improve chances of inlining it
219 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
219 >        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
220              setCompletion(NORMAL);
221      }
222  
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 255 | Line 259 | public abstract class ForkJoinTask<V> im
259      /**
260       * Sets status to indicate there is joiner, then waits for join,
261       * surrounded with pool notifications.
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 274 | 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 297 | Line 304 | public abstract class ForkJoinTask<V> im
304      }
305  
306      /**
307 <     * Notify pool that thread is unblocked. Called by signalled
307 >     * Notifies pool that thread is unblocked. Called by signalled
308       * threads when woken by non-FJ threads (which is atypical).
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      }
316  
317      /**
318 <     * Notify pool to adjust counts on cancelled or timed out wait
318 >     * Notifies pool to adjust counts on cancelled or timed out wait.
319       */
320      private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
321          if (pool != null) {
# Line 323 | Line 330 | public abstract class ForkJoinTask<V> im
330      }
331  
332      /**
333 <     * Handle interruptions during waits.
333 >     * Handles interruptions during waits.
334       */
335      private void onInterruptedWait() {
336          ForkJoinWorkerThread w = getWorker();
# Line 342 | Line 349 | public abstract class ForkJoinTask<V> im
349      }
350  
351      /**
352 <     * Throws the exception associated with status s;
352 >     * Throws the exception associated with status s.
353 >     *
354       * @throws the exception
355       */
356      private void reportException(int s) {
# Line 355 | Line 363 | public abstract class ForkJoinTask<V> im
363      }
364  
365      /**
366 <     * Returns result or throws exception using j.u.c.Future conventions
367 <     * Only call when isDone known to be true.
366 >     * Returns result or throws exception using j.u.c.Future conventions.
367 >     * Only call when {@code isDone} known to be true.
368       */
369      private V reportFutureResult()
370          throws ExecutionException, InterruptedException {
# Line 375 | Line 383 | public abstract class ForkJoinTask<V> im
383  
384      /**
385       * Returns result or throws exception using j.u.c.Future conventions
386 <     * with timeouts
386 >     * with timeouts.
387       */
388      private V reportTimedFutureResult()
389          throws InterruptedException, ExecutionException, TimeoutException {
# Line 396 | Line 404 | public abstract class ForkJoinTask<V> im
404  
405      /**
406       * Calls exec, recording completion, and rethrowing exception if
407 <     * encountered. Caller should normally check status before calling
407 >     * encountered. Caller should normally check status before calling.
408 >     *
409       * @return true if completed normally
410       */
411      private boolean tryExec() {
# Line 414 | Line 423 | public abstract class ForkJoinTask<V> im
423  
424      /**
425       * Main execution method used by worker threads. Invokes
426 <     * base computation unless already complete
426 >     * base computation unless already complete.
427       */
428      final void quietlyExec() {
429          if (status >= 0) {
430              try {
431                  if (!exec())
432                      return;
433 <            } catch(Throwable rex) {
433 >            } catch (Throwable rex) {
434                  setDoneExceptionally(rex);
435                  return;
436              }
# Line 430 | Line 439 | public abstract class ForkJoinTask<V> im
439      }
440  
441      /**
442 <     * Calls exec, recording but not rethrowing exception
443 <     * Caller should normally check status before calling
442 >     * Calls exec(), recording but not rethrowing exception.
443 >     * Caller should normally check status before calling.
444 >     *
445       * @return true if completed normally
446       */
447      private boolean tryQuietlyInvoke() {
# Line 447 | Line 457 | public abstract class ForkJoinTask<V> im
457      }
458  
459      /**
460 <     * Cancel, ignoring any exceptions it throws
460 >     * Cancels, ignoring any exceptions it throws.
461       */
462      final void cancelIgnoringExceptions() {
463          try {
464              cancel(false);
465 <        } catch(Throwable ignore) {
465 >        } catch (Throwable ignore) {
466          }
467      }
468  
# Line 464 | 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 474 | Line 484 | public abstract class ForkJoinTask<V> im
484       * necessarily enforced, it is a usage error to fork a task more
485       * than once unless it has completed and been reinitialized.  This
486       * method may be invoked only from within ForkJoinTask
487 <     * computations. Attempts to invoke in other contexts result in
488 <     * exceptions or errors possibly including ClassCastException.
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.
490       */
491      public final void fork() {
492 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
492 >        ((ForkJoinWorkerThread) Thread.currentThread())
493 >            .pushTask(this);
494      }
495  
496      /**
497       * Returns the result of the computation when it is ready.
498 <     * This method differs from <code>get</code> in that abnormal
498 >     * This method differs from {@code get} in that abnormal
499       * completion results in RuntimeExceptions or Errors, not
500       * ExecutionExceptions.
501       *
# Line 499 | Line 511 | public abstract class ForkJoinTask<V> im
511      /**
512       * Commences performing this task, awaits its completion if
513       * necessary, and return its result.
514 +     *
515       * @throws Throwable (a RuntimeException, Error, or unchecked
516 <     * exception) if the underlying computation did so.
516 >     * exception) if the underlying computation did so
517       * @return the computed result
518       */
519      public final V invoke() {
# Line 511 | Line 524 | public abstract class ForkJoinTask<V> im
524      }
525  
526      /**
527 <     * Forks both tasks, returning when <code>isDone</code> holds for
527 >     * Forks both tasks, returning when {@code isDone} holds for
528       * both of them or an exception is encountered. This method may be
529 <     * invoked only from within ForkJoinTask computations. Attempts to
530 <     * invoke in other contexts result in exceptions or errors
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,
532       * possibly including ClassCastException.
533 +     *
534       * @param t1 one task
535       * @param t2 the other task
536       * @throws NullPointerException if t1 or t2 are null
537 <     * @throws RuntimeException or Error if either task did so.
537 >     * @throws RuntimeException or Error if either task did so
538       */
539      public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
540          t2.fork();
# Line 528 | Line 543 | public abstract class ForkJoinTask<V> im
543      }
544  
545      /**
546 <     * Forks the given tasks, returning when <code>isDone</code> holds
546 >     * Forks the given tasks, returning when {@code isDone} holds
547       * for all of them. If any task encounters an exception, others
548       * may be cancelled.  This method may be invoked only from within
549 <     * ForkJoinTask computations. Attempts to invoke in other contexts
550 <     * result in exceptions or errors possibly including ClassCastException.
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
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.
555 >     * @throws NullPointerException if tasks or any element are null
556 >     * @throws RuntimeException or Error if any task did so
557       */
558      public static void invokeAll(ForkJoinTask<?>... tasks) {
559          Throwable ex = null;
# Line 572 | Line 590 | public abstract class ForkJoinTask<V> im
590  
591      /**
592       * Forks all tasks in the collection, returning when
593 <     * <code>isDone</code> holds for all of them. If any task
593 >     * {@code isDone} holds for all of them. If any task
594       * encounters an exception, others may be cancelled.  This method
595 <     * may be invoked only from within ForkJoinTask
596 <     * computations. Attempts to invoke in other contexts resul!t in
597 <     * exceptions or errors possibly including ClassCastException.
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 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.
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 623 | Line 644 | public abstract class ForkJoinTask<V> im
644      /**
645       * Returns true if the computation performed by this task has
646       * completed (or has been cancelled).
647 +     *
648       * @return true if this computation has completed
649       */
650      public final boolean isDone() {
# Line 631 | Line 653 | public abstract class ForkJoinTask<V> im
653  
654      /**
655       * Returns true if this task was cancelled.
656 +     *
657       * @return true if this task was cancelled
658       */
659      public final boolean isCancelled() {
# Line 639 | Line 662 | public abstract class ForkJoinTask<V> im
662  
663      /**
664       * Asserts that the results of this task's computation will not be
665 <     * used. If a cancellation occurs before atempting to execute this
666 <     * task, then execution will be suppressed, <code>isCancelled</code>
667 <     * will report true, and <code>join</code> will result in a
668 <     * <code>CancellationException</code> being thrown. Otherwise, when
665 >     * used. If a cancellation occurs before attempting to execute this
666 >     * task, then execution will be suppressed, {@code isCancelled}
667 >     * will report true, and {@code join} will result in a
668 >     * {@code CancellationException} being thrown. Otherwise, when
669       * cancellation races with completion, there are no guarantees
670 <     * about whether <code>isCancelled</code> will report true, whether
671 <     * <code>join</code> will return normally or via an exception, or
670 >     * about whether {@code isCancelled} will report true, whether
671 >     * {@code join} will return normally or via an exception, or
672       * whether these behaviors will remain consistent upon repeated
673       * invocation.
674       *
# Line 656 | Line 679 | public abstract class ForkJoinTask<V> im
679       * <p> This method is designed to be invoked by <em>other</em>
680       * tasks. To terminate the current task, you can just return or
681       * throw an unchecked exception from its computation method, or
682 <     * invoke <code>completeExceptionally</code>.
682 >     * invoke {@code completeExceptionally}.
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 670 | Line 693 | public abstract class ForkJoinTask<V> im
693      }
694  
695      /**
696 <     * Returns true if this task threw an exception or was cancelled
696 >     * Returns true if this task threw an exception or was cancelled.
697 >     *
698       * @return true if this task threw an exception or was cancelled
699       */
700      public final boolean isCompletedAbnormally() {
# Line 681 | Line 705 | public abstract class ForkJoinTask<V> im
705       * Returns the exception thrown by the base computation, or a
706       * CancellationException if cancelled, or null if none or if the
707       * method has not yet completed.
708 +     *
709       * @return the exception, or null if none
710       */
711      public final Throwable getException() {
# Line 695 | Line 720 | public abstract class ForkJoinTask<V> im
720      /**
721       * Completes this task abnormally, and if not already aborted or
722       * cancelled, causes it to throw the given exception upon
723 <     * <code>join</code> and related operations. This method may be used
723 >     * {@code join} and related operations. This method may be used
724       * to induce exceptions in asynchronous tasks, or to force
725       * completion of tasks that would not otherwise complete.  Its use
726       * in other situations is likely to be wrong.  This method is
727 <     * overridable, but overridden versions must invoke <code>super</code>
727 >     * overridable, but overridden versions must invoke {@code super}
728       * implementation to maintain guarantees.
729       *
730       * @param ex the exception to throw. If this exception is
# Line 708 | 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  
740      /**
741       * Completes this task, and if not already aborted or cancelled,
742 <     * returning a <code>null</code> result upon <code>join</code> and related
742 >     * returning a {@code null} result upon {@code join} and related
743       * operations. This method may be used to provide results for
744       * asynchronous tasks, or to provide alternative handling for
745       * tasks that would not otherwise complete normally. Its use in
746       * other situations is likely to be wrong. This method is
747 <     * overridable, but overridden versions must invoke <code>super</code>
747 >     * overridable, but overridden versions must invoke {@code super}
748       * implementation to maintain guarantees.
749       *
750 <     * @param value the result value for this task.
750 >     * @param value the result value for this task
751       */
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 752 | Line 777 | public abstract class ForkJoinTask<V> im
777      /**
778       * Possibly executes other tasks until this task is ready, then
779       * returns the result of the computation.  This method may be more
780 <     * efficient than <code>join</code>, but is only applicable when
781 <     * there are no potemtial dependencies between continuation of the
780 >     * efficient than {@code join}, but is only applicable when
781 >     * there are no potential dependencies between continuation of the
782       * current task and that of any other task that might be executed
783       * while helping. (This usually holds for pure divide-and-conquer
784       * tasks). This method may be invoked only from within
785 <     * ForkJoinTask computations. Attempts to invoke in other contexts
786 <     * resul!t in exceptions or errors possibly including ClassCastException.
785 >     * ForkJoinTask computations (as may be determined using method
786 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
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 771 | Line 799 | public abstract class ForkJoinTask<V> im
799      /**
800       * Possibly executes other tasks until this task is ready.  This
801       * method may be invoked only from within ForkJoinTask
802 <     * computations. Attempts to invoke in other contexts resul!t in
803 <     * exceptions or errors possibly including ClassCastException.
802 >     * computations (as may be determined using method {@link
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 816 | 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      /**
853       * Resets the internal bookkeeping state of this task, allowing a
854 <     * subsequent <code>fork</code>. This method allows repeated reuse of
854 >     * subsequent {@code fork}. This method allows repeated reuse of
855       * this task, but only if reuse occurs when this task has either
856       * never been forked, or has been forked, then completed and all
857       * outstanding joins of this task have also completed. Effects
# Line 838 | Line 867 | public abstract class ForkJoinTask<V> im
867  
868      /**
869       * Returns the pool hosting the current task execution, or null
870 <     * if this task is executing outside of any pool.
871 <     * @return the pool, or null if none.
870 >     * if this task is executing outside of any ForkJoinPool.
871 >     *
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 {@code true} if the current thread is executing as a
882 >     * ForkJoinPool computation.
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() {
888 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
889      }
890  
891      /**
# Line 854 | Line 895 | public abstract class ForkJoinTask<V> im
895       * another thread.  This method may be useful when arranging
896       * alternative local processing of tasks that could have been, but
897       * were not, stolen. This method may be invoked only from within
898 <     * ForkJoinTask computations. Attempts to invoke in other contexts
899 <     * result in exceptions or errors possibly including ClassCastException.
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
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 867 | Line 912 | public abstract class ForkJoinTask<V> im
912       * forked by the current worker thread but not yet executed. This
913       * value may be useful for heuristic decisions about whether to
914       * fork other tasks.
915 +     *
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      /**
924 <     * Returns a estimate of how many more locally queued tasks are
924 >     * Returns an estimate of how many more locally queued tasks are
925       * held by the current worker thread than there are other worker
926       * threads that might steal them.  This value may be useful for
927       * heuristic decisions about whether to fork other tasks. In many
# Line 883 | Line 929 | public abstract class ForkJoinTask<V> im
929       * aim to maintain a small constant surplus (for example, 3) of
930       * tasks, and to process computations locally if this threshold is
931       * exceeded.
932 +     *
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  
940      // Extension methods
941  
942      /**
943 <     * Returns the result that would be returned by <code>join</code>,
943 >     * Returns the result that would be returned by {@code join},
944       * even if this task completed abnormally, or null if this task is
945       * not known to have been completed.  This method is designed to
946       * aid debugging, as well as to support extensions. Its use in any
947       * other context is discouraged.
948       *
949 <     * @return the result, or null if not completed.
949 >     * @return the result, or null if not completed
950       */
951      public abstract V getRawResult();
952  
# Line 918 | Line 965 | public abstract class ForkJoinTask<V> im
965       * called otherwise. The return value controls whether this task
966       * is considered to be done normally. It may return false in
967       * asynchronous actions that require explicit invocations of
968 <     * <code>complete</code> to become joinable. It may throw exceptions
968 >     * {@code complete} to become joinable. It may throw exceptions
969       * to indicate abnormal exit.
970 +     *
971       * @return true if completed normally
972       * @throws Error or RuntimeException if encountered during computation
973       */
974      protected abstract boolean exec();
975  
976      /**
977 <     * Returns, but does not unschedule or execute, the task most
978 <     * recently forked by the current thread but not yet executed, if
979 <     * one is available. There is no guarantee that this task will
980 <     * actually be polled or executed next.
981 <     * This method is designed primarily to support extensions,
982 <     * and is unlikely to be useful otherwise.
983 <     * This method may be invoked only from within
984 <     * ForkJoinTask computations. Attempts to invoke in other contexts
985 <     * result in exceptions or errors possibly including ClassCastException.
977 >     * Returns, but does not unschedule or execute, the task queued by
978 >     * the current thread but not yet executed, if one is
979 >     * available. There is no guarantee that this task will actually
980 >     * be polled or executed next.  This method is designed primarily
981 >     * to support extensions, and is unlikely to be useful otherwise.
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.
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      /**
995 <     * Unschedules and returns, without executing, the task most
996 <     * recently forked by the current thread but not yet executed.
997 <     * This method is designed primarily to support extensions,
998 <     * and is unlikely to be useful otherwise.
999 <     * This method may be invoked only from within
1000 <     * ForkJoinTask computations. Attempts to invoke in other contexts
1001 <     * result in exceptions or errors possibly including ClassCastException.
995 >     * Unschedules and returns, without executing, the next task
996 >     * queued by the current thread but not yet executed.  This method
997 >     * is designed primarily to support extensions, and is unlikely to
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
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())).popTask();
1007 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1008 >            .pollLocalTask();
1009      }
1010  
1011      /**
1012 <     * Unschedules and returns, without executing, the task most
1013 <     * recently forked by the current thread but not yet executed, if
1014 <     * one is available, or if not available, a task that was forked
1015 <     * by some other thread, if available. Availability may be
1016 <     * transient, so a <code>null</code> result does not necessarily
1017 <     * imply quiecence of the pool this task is operating in.
1018 <     * This method is designed primarily to support extensions,
1019 <     * and is unlikely to be useful otherwise.
1020 <     * This method may be invoked only from within
1021 <     * ForkJoinTask computations. Attempts to invoke in other contexts
1022 <     * result in exceptions or errors possibly including ClassCastException.
1012 >     * Unschedules and returns, without executing, the next task
1013 >     * queued by the current thread but not yet executed, if one is
1014 >     * available, or if not available, a task that was forked by some
1015 >     * other thread, if available. Availability may be transient, so a
1016 >     * {@code null} result does not necessarily imply quiescence
1017 >     * of the pool this task is operating in.  This method is designed
1018 >     * primarily to support extensions, and is unlikely to be useful
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
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 985 | Line 1037 | public abstract class ForkJoinTask<V> im
1037       * Save the state to a stream.
1038       *
1039       * @serialData the current run status and the exception thrown
1040 <     * during execution, or null if none.
1040 >     * during execution, or null if none
1041       * @param s the stream
1042       */
1043      private void writeObject(java.io.ObjectOutputStream s)
# Line 996 | Line 1048 | public abstract class ForkJoinTask<V> im
1048  
1049      /**
1050       * Reconstitute the instance from a stream.
1051 +     *
1052       * @param s the stream
1053       */
1054      private void readObject(java.io.ObjectInputStream s)
# Line 1005 | 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);
1087 >        return (sun.misc.Unsafe) f.get(null);
1088      }
1089  
1090 <    private static long fieldOffset(String fieldName)
1036 <            throws NoSuchFieldException {
1037 <        return _unsafe.objectFieldOffset
1038 <            (ForkJoinTask.class.getDeclaredField(fieldName));
1039 <    }
1040 <
1041 <    static final Unsafe _unsafe;
1042 <    static final long statusOffset;
1043 <
1044 <    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