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.3 by dl, Wed Jan 7 19:12:36 2009 UTC vs.
Revision 1.34 by dl, Tue Aug 4 11:44:33 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.RandomAccess;
16 > import java.util.Map;
17 > import java.util.WeakHashMap;
18  
19   /**
20 < * Abstract base class for tasks that run within a {@link
21 < * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
20 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
21 > * A {@code ForkJoinTask} is a thread-like entity that is much
22   * lighter weight than a normal thread.  Huge numbers of tasks and
23   * subtasks may be hosted by a small number of actual threads in a
24   * ForkJoinPool, at the price of some usage limitations.
25 < *
26 < * <p> A "main" ForkJoinTask begins execution when submitted to a
27 < * {@link ForkJoinPool}. Once started, it will usually in turn start
28 < * other subtasks.  As indicated by the name of this class, many
29 < * programs using ForkJoinTasks employ only methods <code>fork</code>
30 < * and <code>join</code>, or derivatives such as
31 < * <code>invokeAll</code>.  However, this class also provides a number
32 < * of other methods that can come into play in advanced usages, as
33 < * well as extension mechanics that allow support of new forms of
34 < * fork/join processing.
35 < *
36 < * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
37 < * efficiency of ForkJoinTasks stems from a set of restrictions (that
38 < * are only partially statically enforceable) reflecting their
39 < * intended use as computational tasks calculating pure functions or
40 < * operating on purely isolated objects.  The primary coordination
41 < * mechanisms are {@link #fork}, that arranges asynchronous execution,
42 < * and {@link #join}, that doesn't proceed until the task's result has
43 < * been computed.  Computations should avoid <code>synchronized</code>
44 < * methods or blocks, and should minimize other blocking
45 < * synchronization apart from joining other tasks or using
46 < * synchronizers such as Phasers that are advertised to cooperate with
47 < * fork/join scheduling. Tasks should also not perform blocking IO,
48 < * and should ideally access variables that are completely independent
49 < * of those accessed by other running tasks. Minor breaches of these
50 < * restrictions, for example using shared output streams, may be
51 < * tolerable in practice, but frequent use may result in poor
52 < * performance, and the potential to indefinitely stall if the number
53 < * of threads not waiting for IO or other external synchronization
54 < * becomes exhausted. This usage restriction is in part enforced by
55 < * not permitting checked exceptions such as <code>IOExceptions</code>
56 < * to be thrown. However, computations may still encounter unchecked
57 < * exceptions, that are rethrown to callers attempting join
58 < * them. These exceptions may additionally include
59 < * RejectedExecutionExceptions stemming from internal resource
60 < * exhaustion such as failure to allocate internal task queues.
25 > *
26 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
28 > * start other subtasks.  As indicated by the name of this class,
29 > * many programs using {@code ForkJoinTask} employ only methods
30 > * {@link #fork} and {@link #join}, or derivatives such as {@link
31 > * #invokeAll}.  However, this class also provides a number of other
32 > * methods that can come into play in advanced usages, as well as
33 > * extension mechanics that allow support of new forms of fork/join
34 > * processing.
35 > *
36 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37 > * The efficiency of {@code ForkJoinTask}s stems from a set of
38 > * restrictions (that are only partially statically enforceable)
39 > * reflecting their intended use as computational tasks calculating
40 > * pure functions or operating on purely isolated objects.  The
41 > * primary coordination mechanisms are {@link #fork}, that arranges
42 > * asynchronous execution, and {@link #join}, that doesn't proceed
43 > * until the task's result has been computed.  Computations should
44 > * avoid {@code synchronized} methods or blocks, and should minimize
45 > * other blocking synchronization apart from joining other tasks or
46 > * using synchronizers such as Phasers that are advertised to
47 > * cooperate with fork/join scheduling. Tasks should also not perform
48 > * blocking IO, and should ideally access variables that are
49 > * completely independent of those accessed by other running
50 > * tasks. Minor breaches of these restrictions, for example using
51 > * shared output streams, may be tolerable in practice, but frequent
52 > * use may result in poor performance, and the potential to
53 > * indefinitely stall if the number of threads not waiting for IO or
54 > * other external synchronization becomes exhausted. This usage
55 > * restriction is in part enforced by not permitting checked
56 > * exceptions such as {@code IOExceptions} to be thrown. However,
57 > * computations may still encounter unchecked exceptions, that are
58 > * rethrown to callers attempting to join them. These exceptions may
59 > * additionally include RejectedExecutionExceptions stemming from
60 > * internal resource exhaustion such as failure to allocate internal
61 > * task queues.
62   *
63   * <p>The primary method for awaiting completion and extracting
64   * results of a task is {@link #join}, but there are several variants:
65   * The {@link Future#get} methods support interruptible and/or timed
66 < * waits for completion and report results using <code>Future</code>
66 > * waits for completion and report results using {@code Future}
67   * conventions. Method {@link #helpJoin} enables callers to actively
68   * execute other tasks while awaiting joins, which is sometimes more
69   * efficient but only applies when all subtasks are known to be
70   * strictly tree-structured. Method {@link #invoke} is semantically
71 < * equivalent to <code>fork(); join()</code> but always attempts to
71 > * equivalent to {@code fork(); join()} but always attempts to
72   * begin execution in the current thread. The "<em>quiet</em>" forms
73   * of these methods do not extract results or report exceptions. These
74   * may be useful when a set of tasks are being executed, and you need
75   * to delay processing of results or exceptions until all complete.
76 < * Method <code>invokeAll</code> (available in multiple versions)
76 > * Method {@code invokeAll} (available in multiple versions)
77   * performs the most common form of parallel invocation: forking a set
78   * of tasks and joining them all.
79   *
80 < * <p> The ForkJoinTask class is not usually directly subclassed.
80 > * <p>The ForkJoinTask class is not usually directly subclassed.
81   * Instead, you subclass one of the abstract classes that support a
82 < * particular style of fork/join processing.  Normally, a concrete
82 > * particular style of fork/join processing, typically {@link
83 > * RecursiveAction} for computations that do not return results, or
84 > * {@link RecursiveTask} for those that do.  Normally, a concrete
85   * ForkJoinTask subclass declares fields comprising its parameters,
86 < * established in a constructor, and then defines a <code>compute</code>
86 > * established in a constructor, and then defines a {@code compute}
87   * method that somehow uses the control methods supplied by this base
88 < * class. While these methods have <code>public</code> access (to allow
89 < * instances of different task subclasses to call each others
88 > * class. While these methods have {@code public} access (to allow
89 > * instances of different task subclasses to call each other's
90   * methods), some of them may only be called from within other
91 < * ForkJoinTasks. Attempts to invoke them in other contexts result in
92 < * exceptions or errors including ClassCastException.
91 > * ForkJoinTasks (as may be determined using method {@link
92 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
93 > * result in exceptions or errors, possibly including
94 > * ClassCastException.
95   *
96 < * <p>Most base support methods are <code>final</code> because their
97 < * implementations are intrinsically tied to the underlying
98 < * lightweight task scheduling framework, and so cannot be overridden.
99 < * Developers creating new basic styles of fork/join processing should
100 < * minimally implement <code>protected</code> methods
101 < * <code>exec</code>, <code>setRawResult</code>, and
102 < * <code>getRawResult</code>, while also introducing an abstract
103 < * computational method that can be implemented in its subclasses,
104 < * possibly relying on other <code>protected</code> methods provided
96 < * by this class.
96 > * <p>Most base support methods are {@code final}, to prevent
97 > * overriding of implementations that are intrinsically tied to the
98 > * underlying lightweight task scheduling framework.  Developers
99 > * creating new basic styles of fork/join processing should minimally
100 > * implement {@code protected} methods {@link #exec}, {@link
101 > * #setRawResult}, and {@link #getRawResult}, while also introducing
102 > * an abstract computational method that can be implemented in its
103 > * subclasses, possibly relying on other {@code protected} methods
104 > * provided by this class.
105   *
106   * <p>ForkJoinTasks should perform relatively small amounts of
107 < * computations, othewise splitting into smaller tasks. As a very
108 < * rough rule of thumb, a task should perform more than 100 and less
109 < * than 10000 basic computational steps. If tasks are too big, then
110 < * parellelism cannot improve throughput. If too small, then memory
111 < * and internal task maintenance overhead may overwhelm processing.
107 > * computation. Large tasks should be split into smaller subtasks,
108 > * usually via recursive decomposition. As a very rough rule of thumb,
109 > * a task should perform more than 100 and less than 10000 basic
110 > * computational steps. If tasks are too big, then parallelism cannot
111 > * improve throughput. If too small, then memory and internal task
112 > * maintenance overhead may overwhelm processing.
113 > *
114 > * <p>This class provides {@code adapt} methods for {@link
115 > * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
116 > * may be of use when mixing execution of ForkJoinTasks with other
117 > * kinds of tasks. When all tasks are of this form, consider using a
118 > * pool in {@link ForkJoinPool#setAsyncMode async mode}.
119   *
120 < * <p>ForkJoinTasks are <code>Serializable</code>, which enables them
121 < * to be used in extensions such as remote execution frameworks. It is
122 < * in general sensible to serialize tasks only before or after, but
123 < * not during execution. Serialization is not relied on during
124 < * execution itself.
120 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
121 > * used in extensions such as remote execution frameworks. It is
122 > * sensible to serialize tasks only before or after, but not during,
123 > * execution. Serialization is not relied on during execution itself.
124 > *
125 > * @since 1.7
126 > * @author Doug Lea
127   */
128   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
129  
# Line 128 | Line 145 | public abstract class ForkJoinTask<V> im
145       * currently unused. Also value 0x80000000 is available as spare
146       * completion value.
147       */
148 <    volatile int status; // accessed directy by pool and workers
148 >    volatile int status; // accessed directly by pool and workers
149  
150      static final int COMPLETION_MASK      = 0xe0000000;
151      static final int NORMAL               = 0xe0000000; // == mask
# Line 141 | Line 158 | public abstract class ForkJoinTask<V> im
158      /**
159       * Table of exceptions thrown by tasks, to enable reporting by
160       * callers. Because exceptions are rare, we don't directly keep
161 <     * them with task objects, but instead us a weak ref table.  Note
161 >     * them with task objects, but instead use a weak ref table.  Note
162       * that cancellation exceptions don't appear in the table, but are
163       * instead recorded as status values.
164 <     * Todo: Use ConcurrentReferenceHashMap
164 >     * TODO: Use ConcurrentReferenceHashMap
165       */
166      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
167          Collections.synchronizedMap
# Line 153 | Line 170 | public abstract class ForkJoinTask<V> im
170      // within-package utilities
171  
172      /**
173 <     * Get current worker thread, or null if not a worker thread
173 >     * Gets current worker thread, or null if not a worker thread.
174       */
175      static ForkJoinWorkerThread getWorker() {
176          Thread t = Thread.currentThread();
177 <        return ((t instanceof ForkJoinWorkerThread)?
178 <                (ForkJoinWorkerThread)t : null);
177 >        return ((t instanceof ForkJoinWorkerThread) ?
178 >                (ForkJoinWorkerThread) t : null);
179      }
180  
181      final boolean casStatus(int cmp, int val) {
182 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
182 >        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
183      }
184  
185      /**
# Line 170 | Line 187 | public abstract class ForkJoinTask<V> im
187       */
188      static void rethrowException(Throwable ex) {
189          if (ex != null)
190 <            _unsafe.throwException(ex);
190 >            UNSAFE.throwException(ex);
191      }
192  
193      // Setting completion status
194  
195      /**
196 <     * Mark completion and wake up threads waiting to join this task.
196 >     * Marks completion and wakes up threads waiting to join this task.
197 >     *
198       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
199       */
200      final void setCompletion(int completion) {
201          ForkJoinPool pool = getPool();
202          if (pool != null) {
203              int s; // Clear signal bits while setting completion status
204 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
204 >            do {} while ((s = status) >= 0 && !casStatus(s, completion));
205  
206              if ((s & SIGNAL_MASK) != 0) {
207                  if ((s &= INTERNAL_SIGNAL_MASK) != 0)
208                      pool.updateRunningCount(s);
209 <                synchronized(this) { notifyAll(); }
209 >                synchronized (this) { notifyAll(); }
210              }
211          }
212          else
# Line 201 | Line 219 | public abstract class ForkJoinTask<V> im
219       */
220      private void externallySetCompletion(int completion) {
221          int s;
222 <        do;while ((s = status) >= 0 &&
223 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
224 <        synchronized(this) { notifyAll(); }
222 >        do {} while ((s = status) >= 0 &&
223 >                     !casStatus(s, (s & SIGNAL_MASK) | completion));
224 >        synchronized (this) { notifyAll(); }
225      }
226  
227      /**
228 <     * Sets status to indicate normal completion
228 >     * Sets status to indicate normal completion.
229       */
230      final void setNormalCompletion() {
231          // Try typical fast case -- single CAS, no signal, not already done.
232          // Manually expand casStatus to improve chances of inlining it
233 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
233 >        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
234              setCompletion(NORMAL);
235      }
236  
237      // internal waiting and notification
238  
239      /**
240 <     * Performs the actual monitor wait for awaitDone
240 >     * Performs the actual monitor wait for awaitDone.
241       */
242      private void doAwaitDone() {
243          // Minimize lock bias and in/de-flation effects by maximizing
244          // chances of waiting inside sync
245          try {
246              while (status >= 0)
247 <                synchronized(this) { if (status >= 0) wait(); }
247 >                synchronized (this) { if (status >= 0) wait(); }
248          } catch (InterruptedException ie) {
249              onInterruptedWait();
250          }
251      }
252  
253      /**
254 <     * Performs the actual monitor wait for awaitDone
254 >     * Performs the actual timed monitor wait for awaitDone.
255       */
256      private void doAwaitDone(long startTime, long nanos) {
257 <        synchronized(this) {
257 >        synchronized (this) {
258              try {
259                  while (status >= 0) {
260 <                    long nt = nanos - System.nanoTime() - startTime;
260 >                    long nt = nanos - (System.nanoTime() - startTime);
261                      if (nt <= 0)
262                          break;
263 <                    wait(nt / 1000000, (int)(nt % 1000000));
263 >                    wait(nt / 1000000, (int) (nt % 1000000));
264                  }
265              } catch (InterruptedException ie) {
266                  onInterruptedWait();
# Line 255 | Line 273 | public abstract class ForkJoinTask<V> im
273      /**
274       * Sets status to indicate there is joiner, then waits for join,
275       * surrounded with pool notifications.
276 +     *
277       * @return status upon exit
278       */
279 <    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
280 <        ForkJoinPool pool = w == null? null : w.pool;
279 >    private int awaitDone(ForkJoinWorkerThread w,
280 >                          boolean maintainParallelism) {
281 >        ForkJoinPool pool = (w == null) ? null : w.pool;
282          int s;
283          while ((s = status) >= 0) {
284 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
284 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
285                  if (pool == null || !pool.preJoin(this, maintainParallelism))
286                      doAwaitDone();
287                  if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
# Line 274 | Line 294 | public abstract class ForkJoinTask<V> im
294  
295      /**
296       * Timed version of awaitDone
297 +     *
298       * @return status upon exit
299       */
300      private int awaitDone(ForkJoinWorkerThread w, long nanos) {
301 <        ForkJoinPool pool = w == null? null : w.pool;
301 >        ForkJoinPool pool = (w == null) ? null : w.pool;
302          int s;
303          while ((s = status) >= 0) {
304 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
304 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
305                  long startTime = System.nanoTime();
306                  if (pool == null || !pool.preJoin(this, false))
307                      doAwaitDone(startTime, nanos);
# Line 297 | Line 318 | public abstract class ForkJoinTask<V> im
318      }
319  
320      /**
321 <     * Notify pool that thread is unblocked. Called by signalled
321 >     * Notifies pool that thread is unblocked. Called by signalled
322       * threads when woken by non-FJ threads (which is atypical).
323       */
324      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
325          int s;
326 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
326 >        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
327          if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
328              pool.updateRunningCount(s);
329      }
330  
331      /**
332 <     * Notify pool to adjust counts on cancelled or timed out wait
332 >     * Notifies pool to adjust counts on cancelled or timed out wait.
333       */
334      private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
335          if (pool != null) {
# Line 323 | Line 344 | public abstract class ForkJoinTask<V> im
344      }
345  
346      /**
347 <     * Handle interruptions during waits.
347 >     * Handles interruptions during waits.
348       */
349      private void onInterruptedWait() {
350          ForkJoinWorkerThread w = getWorker();
# Line 342 | Line 363 | public abstract class ForkJoinTask<V> im
363      }
364  
365      /**
366 <     * Throws the exception associated with status s;
366 >     * Throws the exception associated with status s.
367 >     *
368       * @throws the exception
369       */
370      private void reportException(int s) {
# Line 355 | Line 377 | public abstract class ForkJoinTask<V> im
377      }
378  
379      /**
380 <     * Returns result or throws exception using j.u.c.Future conventions
381 <     * Only call when isDone known to be true.
380 >     * Returns result or throws exception using j.u.c.Future conventions.
381 >     * Only call when {@code isDone} known to be true.
382       */
383      private V reportFutureResult()
384          throws ExecutionException, InterruptedException {
385 +        if (Thread.interrupted())
386 +            throw new InterruptedException();
387          int s = status & COMPLETION_MASK;
388          if (s < NORMAL) {
389              Throwable ex;
# Line 367 | Line 391 | public abstract class ForkJoinTask<V> im
391                  throw new CancellationException();
392              if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
393                  throw new ExecutionException(ex);
370            if (Thread.interrupted())
371                throw new InterruptedException();
394          }
395          return getRawResult();
396      }
397  
398      /**
399       * Returns result or throws exception using j.u.c.Future conventions
400 <     * with timeouts
400 >     * with timeouts.
401       */
402      private V reportTimedFutureResult()
403          throws InterruptedException, ExecutionException, TimeoutException {
404 +        if (Thread.interrupted())
405 +            throw new InterruptedException();
406          Throwable ex;
407          int s = status & COMPLETION_MASK;
408          if (s == NORMAL)
# Line 387 | Line 411 | public abstract class ForkJoinTask<V> im
411              throw new CancellationException();
412          if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
413              throw new ExecutionException(ex);
390        if (Thread.interrupted())
391            throw new InterruptedException();
414          throw new TimeoutException();
415      }
416  
# Line 396 | Line 418 | public abstract class ForkJoinTask<V> im
418  
419      /**
420       * Calls exec, recording completion, and rethrowing exception if
421 <     * encountered. Caller should normally check status before calling
421 >     * encountered. Caller should normally check status before calling.
422 >     *
423       * @return true if completed normally
424       */
425      private boolean tryExec() {
# Line 414 | Line 437 | public abstract class ForkJoinTask<V> im
437  
438      /**
439       * Main execution method used by worker threads. Invokes
440 <     * base computation unless already complete
440 >     * base computation unless already complete.
441       */
442      final void quietlyExec() {
443          if (status >= 0) {
444              try {
445                  if (!exec())
446                      return;
447 <            } catch(Throwable rex) {
447 >            } catch (Throwable rex) {
448                  setDoneExceptionally(rex);
449                  return;
450              }
# Line 430 | Line 453 | public abstract class ForkJoinTask<V> im
453      }
454  
455      /**
456 <     * Calls exec, recording but not rethrowing exception
457 <     * Caller should normally check status before calling
456 >     * Calls exec(), recording but not rethrowing exception.
457 >     * Caller should normally check status before calling.
458 >     *
459       * @return true if completed normally
460       */
461      private boolean tryQuietlyInvoke() {
# Line 447 | Line 471 | public abstract class ForkJoinTask<V> im
471      }
472  
473      /**
474 <     * Cancel, ignoring any exceptions it throws
474 >     * Cancels, ignoring any exceptions it throws.
475       */
476      final void cancelIgnoringExceptions() {
477          try {
478              cancel(false);
479 <        } catch(Throwable ignore) {
479 >        } catch (Throwable ignore) {
480          }
481      }
482  
# Line 464 | Line 488 | public abstract class ForkJoinTask<V> im
488          ForkJoinTask<?> t;
489          while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
490              t.quietlyExec();
491 <        return (s >= 0)? awaitDone(w, false) : s; // block if no work
491 >        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
492      }
493  
494      // public methods
# Line 472 | Line 496 | public abstract class ForkJoinTask<V> im
496      /**
497       * Arranges to asynchronously execute this task.  While it is not
498       * necessarily enforced, it is a usage error to fork a task more
499 <     * than once unless it has completed and been reinitialized.  This
500 <     * method may be invoked only from within ForkJoinTask
501 <     * computations. Attempts to invoke in other contexts result in
502 <     * exceptions or errors including ClassCastException.
499 >     * than once unless it has completed and been reinitialized.
500 >     *
501 >     * <p>This method may be invoked only from within {@code
502 >     * ForkJoinTask} computations (as may be determined using method
503 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
504 >     * result in exceptions or errors, possibly including {@code
505 >     * ClassCastException}.
506 >     *
507 >     * @return {@code this}, to simplify usage
508       */
509 <    public final void fork() {
510 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
509 >    public final ForkJoinTask<V> fork() {
510 >        ((ForkJoinWorkerThread) Thread.currentThread())
511 >            .pushTask(this);
512 >        return this;
513      }
514  
515      /**
516       * Returns the result of the computation when it is ready.
517 <     * This method differs from <code>get</code> in that abnormal
518 <     * completion results in RuntimeExceptions or Errors, not
519 <     * ExecutionExceptions.
517 >     * This method differs from {@link #get()} in that
518 >     * abnormal completion results in {@code RuntimeException} or
519 >     * {@code Error}, not {@code ExecutionException}.
520       *
521       * @return the computed result
522       */
# Line 498 | Line 529 | public abstract class ForkJoinTask<V> im
529  
530      /**
531       * Commences performing this task, awaits its completion if
532 <     * necessary, and return its result.
533 <     * @throws Throwable (a RuntimeException, Error, or unchecked
534 <     * exception) if the underlying computation did so.
532 >     * necessary, and return its result, or throws an (unchecked)
533 >     * exception if the underlying computation did so.
534 >     *
535       * @return the computed result
536       */
537      public final V invoke() {
# Line 511 | Line 542 | public abstract class ForkJoinTask<V> im
542      }
543  
544      /**
545 <     * Forks both tasks, returning when <code>isDone</code> holds for
546 <     * both of them or an exception is encountered. This method may be
547 <     * invoked only from within ForkJoinTask computations. Attempts to
548 <     * invoke in other contexts result in exceptions or errors
549 <     * including ClassCastException.
550 <     * @param t1 one task
551 <     * @param t2 the other task
552 <     * @throws NullPointerException if t1 or t2 are null
553 <     * @throws RuntimeException or Error if either task did so.
545 >     * Forks the given tasks, returning when {@code isDone} holds for
546 >     * each task or an (unchecked) exception is encountered, in which
547 >     * case the exception is rethrown.  If more than one task
548 >     * encounters an exception, then this method throws any one of
549 >     * these exceptions.  The individual status of each task may be
550 >     * checked using {@link #getException()} and related methods.
551 >     *
552 >     * <p>This method may be invoked only from within {@code
553 >     * ForkJoinTask} computations (as may be determined using method
554 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
555 >     * result in exceptions or errors, possibly including {@code
556 >     * ClassCastException}.
557 >     *
558 >     * @param t1 the first task
559 >     * @param t2 the second task
560 >     * @throws NullPointerException if any task is null
561       */
562 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
562 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
563          t2.fork();
564          t1.invoke();
565          t2.join();
566      }
567  
568      /**
569 <     * Forks the given tasks, returning when <code>isDone</code> holds
570 <     * for all of them. If any task encounters an exception, others
571 <     * may be cancelled.  This method may be invoked only from within
572 <     * ForkJoinTask computations. Attempts to invoke in other contexts
573 <     * result in exceptions or errors including ClassCastException.
574 <     * @param tasks the array of tasks
575 <     * @throws NullPointerException if tasks or any element are null.
576 <     * @throws RuntimeException or Error if any task did so.
569 >     * Forks the given tasks, returning when {@code isDone} holds for
570 >     * each task or an (unchecked) exception is encountered, in which
571 >     * case the exception is rethrown. If any task encounters an
572 >     * exception, others may be, but are not guaranteed to be,
573 >     * cancelled.  If more than one task encounters an exception, then
574 >     * this method throws any one of these exceptions.  The individual
575 >     * status of each task may be checked using {@link #getException()}
576 >     * and related methods.
577 >     *
578 >     * <p>This method may be invoked only from within {@code
579 >     * ForkJoinTask} computations (as may be determined using method
580 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
581 >     * result in exceptions or errors, possibly including {@code
582 >     * ClassCastException}.
583 >     *
584 >     * @param tasks the tasks
585 >     * @throws NullPointerException if any task is null
586       */
587      public static void invokeAll(ForkJoinTask<?>... tasks) {
588          Throwable ex = null;
# Line 571 | Line 618 | public abstract class ForkJoinTask<V> im
618      }
619  
620      /**
621 <     * Forks all tasks in the collection, returning when
622 <     * <code>isDone</code> holds for all of them. If any task
623 <     * encounters an exception, others may be cancelled.  This method
624 <     * may be invoked only from within ForkJoinTask
625 <     * computations. Attempts to invoke in other contexts resul!t in
626 <     * exceptions or errors including ClassCastException.
621 >     * Forks all tasks in the specified collection, returning when
622 >     * {@code isDone} holds for each task or an (unchecked) exception
623 >     * is encountered.  If any task encounters an exception, others
624 >     * may be, but are not guaranteed to be, cancelled.  If more than
625 >     * one task encounters an exception, then this method throws any
626 >     * one of these exceptions.  The individual status of each task
627 >     * may be checked using {@link #getException()} and related
628 >     * methods.  The behavior of this operation is undefined if the
629 >     * specified collection is modified while the operation is in
630 >     * progress.
631 >     *
632 >     * <p>This method may be invoked only from within {@code
633 >     * ForkJoinTask} computations (as may be determined using method
634 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
635 >     * result in exceptions or errors, possibly including {@code
636 >     * ClassCastException}.
637 >     *
638       * @param tasks the collection of tasks
639 <     * @throws NullPointerException if tasks or any element are null.
640 <     * @throws RuntimeException or Error if any task did so.
639 >     * @return the tasks argument, to simplify usage
640 >     * @throws NullPointerException if tasks or any element are null
641       */
642 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
643 <        if (!(tasks instanceof List)) {
644 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
645 <            return;
642 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
643 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
644 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
645 >            return tasks;
646          }
647 +        @SuppressWarnings("unchecked")
648          List<? extends ForkJoinTask<?>> ts =
649 <            (List<? extends ForkJoinTask<?>>)tasks;
649 >            (List<? extends ForkJoinTask<?>>) tasks;
650          Throwable ex = null;
651          int last = ts.size() - 1;
652          for (int i = last; i >= 0; --i) {
# Line 618 | Line 677 | public abstract class ForkJoinTask<V> im
677          }
678          if (ex != null)
679              rethrowException(ex);
680 +        return tasks;
681      }
682  
683      /**
684 <     * Returns true if the computation performed by this task has
685 <     * completed (or has been cancelled).
686 <     * @return true if this computation has completed
687 <     */
688 <    public final boolean isDone() {
689 <        return status < 0;
690 <    }
631 <
632 <    /**
633 <     * Returns true if this task was cancelled.
634 <     * @return true if this task was cancelled
635 <     */
636 <    public final boolean isCancelled() {
637 <        return (status & COMPLETION_MASK) == CANCELLED;
638 <    }
639 <
640 <    /**
641 <     * Asserts that the results of this task's computation will not be
642 <     * used. If a cancellation occurs before atempting to execute this
643 <     * task, then execution will be suppressed, <code>isCancelled</code>
644 <     * will report true, and <code>join</code> will result in a
645 <     * <code>CancellationException</code> being thrown. Otherwise, when
646 <     * cancellation races with completion, there are no guarantees
647 <     * about whether <code>isCancelled</code> will report true, whether
648 <     * <code>join</code> will return normally or via an exception, or
649 <     * whether these behaviors will remain consistent upon repeated
650 <     * invocation.
684 >     * Attempts to cancel execution of this task. This attempt will
685 >     * fail if the task has already completed, has already been
686 >     * cancelled, or could not be cancelled for some other reason. If
687 >     * successful, and this task has not started when cancel is
688 >     * called, execution of this task is suppressed, {@link
689 >     * #isCancelled} will report true, and {@link #join} will result
690 >     * in a {@code CancellationException} being thrown.
691       *
692       * <p>This method may be overridden in subclasses, but if so, must
693       * still ensure that these minimal properties hold. In particular,
694 <     * the cancel method itself must not throw exceptions.
694 >     * the {@code cancel} method itself must not throw exceptions.
695       *
696 <     * <p> This method is designed to be invoked by <em>other</em>
696 >     * <p>This method is designed to be invoked by <em>other</em>
697       * tasks. To terminate the current task, you can just return or
698       * throw an unchecked exception from its computation method, or
699 <     * invoke <code>completeExceptionally</code>.
699 >     * invoke {@link #completeExceptionally}.
700       *
701       * @param mayInterruptIfRunning this value is ignored in the
702 <     * default implementation because tasks are not in general
703 <     * cancelled via interruption.
702 >     * default implementation because tasks are not
703 >     * cancelled via interruption
704       *
705 <     * @return true if this task is now cancelled
705 >     * @return {@code true} if this task is now cancelled
706       */
707      public boolean cancel(boolean mayInterruptIfRunning) {
708          setCompletion(CANCELLED);
# Line 670 | Line 710 | public abstract class ForkJoinTask<V> im
710      }
711  
712      /**
713 <     * Returns true if this task threw an exception or was cancelled
714 <     * @return true if this task threw an exception or was cancelled
713 >     * Returns {@code true} if the computation performed by this task
714 >     * has completed (or has been cancelled).
715 >     *
716 >     * @return {@code true} if this computation has completed
717 >     */
718 >    public final boolean isDone() {
719 >        return status < 0;
720 >    }
721 >
722 >    /**
723 >     * Returns {@code true} if this task was cancelled.
724 >     *
725 >     * @return {@code true} if this task was cancelled
726 >     */
727 >    public final boolean isCancelled() {
728 >        return (status & COMPLETION_MASK) == CANCELLED;
729 >    }
730 >
731 >    /**
732 >     * Returns {@code true} if this task threw an exception or was cancelled.
733 >     *
734 >     * @return {@code true} if this task threw an exception or was cancelled
735       */
736      public final boolean isCompletedAbnormally() {
737          return (status & COMPLETION_MASK) < NORMAL;
738      }
739  
740      /**
741 +     * Returns {@code true} if this task completed without throwing an
742 +     * exception and was not cancelled.
743 +     *
744 +     * @return {@code true} if this task completed without throwing an
745 +     * exception and was not cancelled
746 +     */
747 +    public final boolean isCompletedNormally() {
748 +        return (status & COMPLETION_MASK) == NORMAL;
749 +    }
750 +
751 +    /**
752 +     * Returns {@code true} if this task threw an exception.
753 +     *
754 +     * @return {@code true} if this task threw an exception
755 +     */
756 +    public final boolean isCompletedExceptionally() {
757 +        return (status & COMPLETION_MASK) == EXCEPTIONAL;
758 +    }
759 +
760 +    /**
761       * Returns the exception thrown by the base computation, or a
762 <     * CancellationException if cancelled, or null if none or if the
763 <     * method has not yet completed.
764 <     * @return the exception, or null if none
762 >     * {@code CancellationException} if cancelled, or {@code null} if
763 >     * none or if the method has not yet completed.
764 >     *
765 >     * @return the exception, or {@code null} if none
766       */
767      public final Throwable getException() {
768          int s = status & COMPLETION_MASK;
# Line 695 | Line 776 | public abstract class ForkJoinTask<V> im
776      /**
777       * Completes this task abnormally, and if not already aborted or
778       * cancelled, causes it to throw the given exception upon
779 <     * <code>join</code> and related operations. This method may be used
779 >     * {@code join} and related operations. This method may be used
780       * to induce exceptions in asynchronous tasks, or to force
781       * completion of tasks that would not otherwise complete.  Its use
782 <     * in other situations is likely to be wrong.  This method is
783 <     * overridable, but overridden versions must invoke <code>super</code>
782 >     * in other situations is discouraged.  This method is
783 >     * overridable, but overridden versions must invoke {@code super}
784       * implementation to maintain guarantees.
785       *
786       * @param ex the exception to throw. If this exception is
# Line 708 | Line 789 | public abstract class ForkJoinTask<V> im
789       */
790      public void completeExceptionally(Throwable ex) {
791          setDoneExceptionally((ex instanceof RuntimeException) ||
792 <                             (ex instanceof Error)? ex :
792 >                             (ex instanceof Error) ? ex :
793                               new RuntimeException(ex));
794      }
795  
796      /**
797       * Completes this task, and if not already aborted or cancelled,
798 <     * returning a <code>null</code> result upon <code>join</code> and related
798 >     * returning a {@code null} result upon {@code join} and related
799       * operations. This method may be used to provide results for
800       * asynchronous tasks, or to provide alternative handling for
801       * tasks that would not otherwise complete normally. Its use in
802 <     * other situations is likely to be wrong. This method is
803 <     * overridable, but overridden versions must invoke <code>super</code>
802 >     * other situations is discouraged. This method is
803 >     * overridable, but overridden versions must invoke {@code super}
804       * implementation to maintain guarantees.
805       *
806 <     * @param value the result value for this task.
806 >     * @param value the result value for this task
807       */
808      public void complete(V value) {
809          try {
810              setRawResult(value);
811 <        } catch(Throwable rex) {
811 >        } catch (Throwable rex) {
812              setDoneExceptionally(rex);
813              return;
814          }
# Line 743 | Line 824 | public abstract class ForkJoinTask<V> im
824  
825      public final V get(long timeout, TimeUnit unit)
826          throws InterruptedException, ExecutionException, TimeoutException {
827 +        long nanos = unit.toNanos(timeout);
828          ForkJoinWorkerThread w = getWorker();
829          if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
830 <            awaitDone(w, unit.toNanos(timeout));
830 >            awaitDone(w, nanos);
831          return reportTimedFutureResult();
832      }
833  
834      /**
835       * Possibly executes other tasks until this task is ready, then
836       * returns the result of the computation.  This method may be more
837 <     * efficient than <code>join</code>, but is only applicable when
838 <     * there are no potemtial dependencies between continuation of the
837 >     * efficient than {@code join}, but is only applicable when
838 >     * there are no potential dependencies between continuation of the
839       * current task and that of any other task that might be executed
840       * while helping. (This usually holds for pure divide-and-conquer
841 <     * tasks). This method may be invoked only from within
842 <     * ForkJoinTask computations. Attempts to invoke in other contexts
843 <     * resul!t in exceptions or errors including ClassCastException.
841 >     * tasks).
842 >     *
843 >     * <p>This method may be invoked only from within {@code
844 >     * ForkJoinTask} computations (as may be determined using method
845 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
846 >     * result in exceptions or errors, possibly including {@code
847 >     * ClassCastException}.
848 >     *
849       * @return the computed result
850       */
851      public final V helpJoin() {
852 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
852 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
853          if (status < 0 || !w.unpushTask(this) || !tryExec())
854              reportException(busyJoin(w));
855          return getRawResult();
# Line 770 | Line 857 | public abstract class ForkJoinTask<V> im
857  
858      /**
859       * Possibly executes other tasks until this task is ready.  This
860 <     * method may be invoked only from within ForkJoinTask
861 <     * computations. Attempts to invoke in other contexts resul!t in
862 <     * exceptions or errors including ClassCastException.
860 >     * method may be useful when processing collections of tasks when
861 >     * some have been cancelled or otherwise known to have aborted.
862 >     *
863 >     * <p>This method may be invoked only from within {@code
864 >     * ForkJoinTask} computations (as may be determined using method
865 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
866 >     * result in exceptions or errors, possibly including {@code
867 >     * ClassCastException}.
868       */
869      public final void quietlyHelpJoin() {
870          if (status >= 0) {
871              ForkJoinWorkerThread w =
872 <                (ForkJoinWorkerThread)(Thread.currentThread());
872 >                (ForkJoinWorkerThread) Thread.currentThread();
873              if (!w.unpushTask(this) || !tryQuietlyInvoke())
874                  busyJoin(w);
875          }
# Line 811 | Line 903 | public abstract class ForkJoinTask<V> im
903  
904      /**
905       * Possibly executes tasks until the pool hosting the current task
906 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
907 <     * designs in which many tasks are forked, but none are explicitly
908 <     * joined, instead executing them until all are processed.
906 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
907 >     * be of use in designs in which many tasks are forked, but none
908 >     * are explicitly joined, instead executing them until all are
909 >     * processed.
910 >     *
911 >     * <p>This method may be invoked only from within {@code
912 >     * ForkJoinTask} computations (as may be determined using method
913 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
914 >     * result in exceptions or errors, possibly including {@code
915 >     * ClassCastException}.
916       */
917      public static void helpQuiesce() {
918 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
919 <            helpQuiescePool();
918 >        ((ForkJoinWorkerThread) Thread.currentThread())
919 >            .helpQuiescePool();
920      }
921  
922      /**
923       * Resets the internal bookkeeping state of this task, allowing a
924 <     * subsequent <code>fork</code>. This method allows repeated reuse of
924 >     * subsequent {@code fork}. This method allows repeated reuse of
925       * this task, but only if reuse occurs when this task has either
926       * never been forked, or has been forked, then completed and all
927       * outstanding joins of this task have also completed. Effects
928 <     * under any other usage conditions are not guaranteed, and are
929 <     * almost surely wrong. This method may be useful when executing
928 >     * under any other usage conditions are not guaranteed.
929 >     * This method may be useful when executing
930       * pre-constructed trees of subtasks in loops.
931       */
932      public void reinitialize() {
# Line 838 | Line 937 | public abstract class ForkJoinTask<V> im
937  
938      /**
939       * Returns the pool hosting the current task execution, or null
940 <     * if this task is executing outside of any pool.
941 <     * @return the pool, or null if none.
940 >     * if this task is executing outside of any ForkJoinPool.
941 >     *
942 >     * @see #inForkJoinPool
943 >     * @return the pool, or {@code null} if none
944       */
945      public static ForkJoinPool getPool() {
946          Thread t = Thread.currentThread();
947 <        return ((t instanceof ForkJoinWorkerThread)?
948 <                ((ForkJoinWorkerThread)t).pool : null);
947 >        return (t instanceof ForkJoinWorkerThread) ?
948 >            ((ForkJoinWorkerThread) t).pool : null;
949 >    }
950 >
951 >    /**
952 >     * Returns {@code true} if the current thread is executing as a
953 >     * ForkJoinPool computation.
954 >     *
955 >     * @return {@code true} if the current thread is executing as a
956 >     * ForkJoinPool computation, or false otherwise
957 >     */
958 >    public static boolean inForkJoinPool() {
959 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
960      }
961  
962      /**
# Line 853 | Line 965 | public abstract class ForkJoinTask<V> im
965       * by the current thread, and has not commenced executing in
966       * another thread.  This method may be useful when arranging
967       * alternative local processing of tasks that could have been, but
968 <     * were not, stolen. This method may be invoked only from within
969 <     * ForkJoinTask computations. Attempts to invoke in other contexts
970 <     * result in exceptions or errors including ClassCastException.
971 <     * @return true if unforked
968 >     * were not, stolen.
969 >     *
970 >     * <p>This method may be invoked only from within {@code
971 >     * ForkJoinTask} computations (as may be determined using method
972 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
973 >     * result in exceptions or errors, possibly including {@code
974 >     * ClassCastException}.
975 >     *
976 >     * @return {@code true} if unforked
977       */
978      public boolean tryUnfork() {
979 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
979 >        return ((ForkJoinWorkerThread) Thread.currentThread())
980 >            .unpushTask(this);
981      }
982  
983      /**
# Line 867 | Line 985 | public abstract class ForkJoinTask<V> im
985       * forked by the current worker thread but not yet executed. This
986       * value may be useful for heuristic decisions about whether to
987       * fork other tasks.
988 +     *
989 +     * <p>This method may be invoked only from within {@code
990 +     * ForkJoinTask} computations (as may be determined using method
991 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
992 +     * result in exceptions or errors, possibly including {@code
993 +     * ClassCastException}.
994 +     *
995       * @return the number of tasks
996       */
997      public static int getQueuedTaskCount() {
998 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
999 <            getQueueSize();
998 >        return ((ForkJoinWorkerThread) Thread.currentThread())
999 >            .getQueueSize();
1000      }
1001  
1002      /**
1003 <     * Returns a estimate of how many more locally queued tasks are
1003 >     * Returns an estimate of how many more locally queued tasks are
1004       * held by the current worker thread than there are other worker
1005       * threads that might steal them.  This value may be useful for
1006       * heuristic decisions about whether to fork other tasks. In many
# Line 883 | Line 1008 | public abstract class ForkJoinTask<V> im
1008       * aim to maintain a small constant surplus (for example, 3) of
1009       * tasks, and to process computations locally if this threshold is
1010       * exceeded.
1011 +     *
1012 +     * <p>This method may be invoked only from within {@code
1013 +     * ForkJoinTask} computations (as may be determined using method
1014 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1015 +     * result in exceptions or errors, possibly including {@code
1016 +     * ClassCastException}.
1017 +     *
1018       * @return the surplus number of tasks, which may be negative
1019       */
1020      public static int getSurplusQueuedTaskCount() {
1021 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
1021 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1022              .getEstimatedSurplusTaskCount();
1023      }
1024  
1025      // Extension methods
1026  
1027      /**
1028 <     * Returns the result that would be returned by <code>join</code>,
1029 <     * even if this task completed abnormally, or null if this task is
1030 <     * not known to have been completed.  This method is designed to
1031 <     * aid debugging, as well as to support extensions. Its use in any
1032 <     * other context is discouraged.
1028 >     * Returns the result that would be returned by {@link #join}, even
1029 >     * if this task completed abnormally, or {@code null} if this task
1030 >     * is not known to have been completed.  This method is designed
1031 >     * to aid debugging, as well as to support extensions. Its use in
1032 >     * any other context is discouraged.
1033       *
1034 <     * @return the result, or null if not completed.
1034 >     * @return the result, or {@code null} if not completed
1035       */
1036      public abstract V getRawResult();
1037  
# Line 918 | Line 1050 | public abstract class ForkJoinTask<V> im
1050       * called otherwise. The return value controls whether this task
1051       * is considered to be done normally. It may return false in
1052       * asynchronous actions that require explicit invocations of
1053 <     * <code>complete</code> to become joinable. It may throw exceptions
1054 <     * to indicate abnormal exit.
1055 <     * @return true if completed normally
1056 <     * @throws Error or RuntimeException if encountered during computation
1053 >     * {@link #complete} to become joinable. It may also throw an
1054 >     * (unchecked) exception to indicate abnormal exit.
1055 >     *
1056 >     * @return {@code true} if completed normally
1057       */
1058      protected abstract boolean exec();
1059  
1060      /**
1061 <     * Returns, but does not unschedule or execute, the task most
1062 <     * recently forked by the current thread but not yet executed, if
1063 <     * one is available. There is no guarantee that this task will
1064 <     * actually be polled or executed next.
1065 <     * This method is designed primarily to support extensions,
1066 <     * and is unlikely to be useful otherwise.
1061 >     * Returns, but does not unschedule or execute, a task queued by
1062 >     * the current thread but not yet executed, if one is immediately
1063 >     * available. There is no guarantee that this task will actually
1064 >     * be polled or executed next. Conversely, this method may return
1065 >     * null even if a task exists but cannot be accessed without
1066 >     * contention with other threads.  This method is designed
1067 >     * primarily to support extensions, and is unlikely to be useful
1068 >     * otherwise.
1069 >     *
1070 >     * <p>This method may be invoked only from within {@code
1071 >     * ForkJoinTask} computations (as may be determined using method
1072 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1073 >     * result in exceptions or errors, possibly including {@code
1074 >     * ClassCastException}.
1075       *
1076 <     * @return the next task, or null if none are available
1076 >     * @return the next task, or {@code null} if none are available
1077       */
1078      protected static ForkJoinTask<?> peekNextLocalTask() {
1079 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
1079 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1080 >            .peekTask();
1081      }
1082  
1083      /**
1084 <     * Unschedules and returns, without executing, the task most
1085 <     * recently forked by the current thread but not yet executed.
1086 <     * This method is designed primarily to support extensions,
1087 <     * and is unlikely to be useful otherwise.
1084 >     * Unschedules and returns, without executing, the next task
1085 >     * queued by the current thread but not yet executed.  This method
1086 >     * is designed primarily to support extensions, and is unlikely to
1087 >     * be useful otherwise.
1088       *
1089 <     * @return the next task, or null if none are available
1089 >     * <p>This method may be invoked only from within {@code
1090 >     * ForkJoinTask} computations (as may be determined using method
1091 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1092 >     * result in exceptions or errors, possibly including {@code
1093 >     * ClassCastException}.
1094 >     *
1095 >     * @return the next task, or {@code null} if none are available
1096       */
1097      protected static ForkJoinTask<?> pollNextLocalTask() {
1098 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask();
1098 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1099 >            .pollLocalTask();
1100      }
1101  
1102      /**
1103 <     * Unschedules and returns, without executing, the task most
1104 <     * recently forked by the current thread but not yet executed, if
1105 <     * one is available, or if not available, a task that was forked
1106 <     * by some other thread, if available. Availability may be
1107 <     * transient, so a <code>null</code> result does not necessarily
1108 <     * imply quiecence of the pool this task is operating in.
1109 <     * This method is designed primarily to support extensions,
1110 <     * and is unlikely to be useful otherwise.
1111 <     *
1112 <     * @return a task, or null if none are available
1103 >     * Unschedules and returns, without executing, the next task
1104 >     * queued by the current thread but not yet executed, if one is
1105 >     * available, or if not available, a task that was forked by some
1106 >     * other thread, if available. Availability may be transient, so a
1107 >     * {@code null} result does not necessarily imply quiescence
1108 >     * of the pool this task is operating in.  This method is designed
1109 >     * primarily to support extensions, and is unlikely to be useful
1110 >     * otherwise.
1111 >     *
1112 >     * <p>This method may be invoked only from within {@code
1113 >     * ForkJoinTask} computations (as may be determined using method
1114 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1115 >     * result in exceptions or errors, possibly including {@code
1116 >     * ClassCastException}.
1117 >     *
1118 >     * @return a task, or {@code null} if none are available
1119       */
1120      protected static ForkJoinTask<?> pollTask() {
1121 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1122 <            pollLocalOrStolenTask();
1121 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1122 >            .pollTask();
1123 >    }
1124 >
1125 >    /**
1126 >     * Adaptor for Runnables. This implements RunnableFuture
1127 >     * to be compliant with AbstractExecutorService constraints
1128 >     * when used in ForkJoinPool.
1129 >     */
1130 >    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1131 >        implements RunnableFuture<T> {
1132 >        final Runnable runnable;
1133 >        final T resultOnCompletion;
1134 >        T result;
1135 >        AdaptedRunnable(Runnable runnable, T result) {
1136 >            if (runnable == null) throw new NullPointerException();
1137 >            this.runnable = runnable;
1138 >            this.resultOnCompletion = result;
1139 >        }
1140 >        public T getRawResult() { return result; }
1141 >        public void setRawResult(T v) { result = v; }
1142 >        public boolean exec() {
1143 >            runnable.run();
1144 >            result = resultOnCompletion;
1145 >            return true;
1146 >        }
1147 >        public void run() { invoke(); }
1148 >        private static final long serialVersionUID = 5232453952276885070L;
1149 >    }
1150 >
1151 >    /**
1152 >     * Adaptor for Callables
1153 >     */
1154 >    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1155 >        implements RunnableFuture<T> {
1156 >        final Callable<? extends T> callable;
1157 >        T result;
1158 >        AdaptedCallable(Callable<? extends T> callable) {
1159 >            if (callable == null) throw new NullPointerException();
1160 >            this.callable = callable;
1161 >        }
1162 >        public T getRawResult() { return result; }
1163 >        public void setRawResult(T v) { result = v; }
1164 >        public boolean exec() {
1165 >            try {
1166 >                result = callable.call();
1167 >                return true;
1168 >            } catch (Error err) {
1169 >                throw err;
1170 >            } catch (RuntimeException rex) {
1171 >                throw rex;
1172 >            } catch (Exception ex) {
1173 >                throw new RuntimeException(ex);
1174 >            }
1175 >        }
1176 >        public void run() { invoke(); }
1177 >        private static final long serialVersionUID = 2838392045355241008L;
1178 >    }
1179 >
1180 >    /**
1181 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1182 >     * method of the given {@code Runnable} as its action, and returns
1183 >     * a null result upon {@link #join}.
1184 >     *
1185 >     * @param runnable the runnable action
1186 >     * @return the task
1187 >     */
1188 >    public static ForkJoinTask<?> adapt(Runnable runnable) {
1189 >        return new AdaptedRunnable<Void>(runnable, null);
1190 >    }
1191 >
1192 >    /**
1193 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1194 >     * method of the given {@code Runnable} as its action, and returns
1195 >     * the given result upon {@link #join}.
1196 >     *
1197 >     * @param runnable the runnable action
1198 >     * @param result the result upon completion
1199 >     * @return the task
1200 >     */
1201 >    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1202 >        return new AdaptedRunnable<T>(runnable, result);
1203 >    }
1204 >
1205 >    /**
1206 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1207 >     * method of the given {@code Callable} as its action, and returns
1208 >     * its result upon {@link #join}, translating any checked exceptions
1209 >     * encountered into {@code RuntimeException}.
1210 >     *
1211 >     * @param callable the callable action
1212 >     * @return the task
1213 >     */
1214 >    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1215 >        return new AdaptedCallable<T>(callable);
1216      }
1217  
1218      // Serialization support
# Line 976 | Line 1223 | public abstract class ForkJoinTask<V> im
1223       * Save the state to a stream.
1224       *
1225       * @serialData the current run status and the exception thrown
1226 <     * during execution, or null if none.
1226 >     * during execution, or {@code null} if none
1227       * @param s the stream
1228       */
1229      private void writeObject(java.io.ObjectOutputStream s)
# Line 987 | Line 1234 | public abstract class ForkJoinTask<V> im
1234  
1235      /**
1236       * Reconstitute the instance from a stream.
1237 +     *
1238       * @param s the stream
1239       */
1240      private void readObject(java.io.ObjectInputStream s)
# Line 996 | Line 1244 | public abstract class ForkJoinTask<V> im
1244          status |= EXTERNAL_SIGNAL; // conservatively set external signal
1245          Object ex = s.readObject();
1246          if (ex != null)
1247 <            setDoneExceptionally((Throwable)ex);
1247 >            setDoneExceptionally((Throwable) ex);
1248      }
1249  
1250 <    // Temporary Unsafe mechanics for preliminary release
1250 >    // Unsafe mechanics
1251  
1252 <    static final Unsafe _unsafe;
1253 <    static final long statusOffset;
1252 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1253 >    private static final long statusOffset =
1254 >        objectFieldOffset("status", ForkJoinTask.class);
1255  
1256 <    static {
1256 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1257          try {
1258 <            if (ForkJoinTask.class.getClassLoader() != null) {
1259 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1260 <                f.setAccessible(true);
1261 <                _unsafe = (Unsafe)f.get(null);
1262 <            }
1263 <            else
1264 <                _unsafe = Unsafe.getUnsafe();
1016 <            statusOffset = _unsafe.objectFieldOffset
1017 <                (ForkJoinTask.class.getDeclaredField("status"));
1018 <        } catch (Exception ex) { throw new Error(ex); }
1258 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1259 >        } catch (NoSuchFieldException e) {
1260 >            // Convert Exception to corresponding Error
1261 >            NoSuchFieldError error = new NoSuchFieldError(field);
1262 >            error.initCause(e);
1263 >            throw error;
1264 >        }
1265      }
1266  
1267 +    /**
1268 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1269 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1270 +     * into a jdk.
1271 +     *
1272 +     * @return a sun.misc.Unsafe
1273 +     */
1274 +    private static sun.misc.Unsafe getUnsafe() {
1275 +        try {
1276 +            return sun.misc.Unsafe.getUnsafe();
1277 +        } catch (SecurityException se) {
1278 +            try {
1279 +                return java.security.AccessController.doPrivileged
1280 +                    (new java.security
1281 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1282 +                        public sun.misc.Unsafe run() throws Exception {
1283 +                            java.lang.reflect.Field f = sun.misc
1284 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1285 +                            f.setAccessible(true);
1286 +                            return (sun.misc.Unsafe) f.get(null);
1287 +                        }});
1288 +            } catch (java.security.PrivilegedActionException e) {
1289 +                throw new RuntimeException("Could not initialize intrinsics",
1290 +                                           e.getCause());
1291 +            }
1292 +        }
1293 +    }
1294   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines