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.8 by jsr166, Mon Jul 20 21:54:51 2009 UTC vs.
Revision 1.31 by jsr166, Sun Aug 2 22:58:50 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.io.Serializable;
9 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import sun.misc.Unsafe;
12 < import java.lang.reflect.*;
10 >
11 > import java.io.Serializable;
12 > import java.util.Collection;
13 > import java.util.Collections;
14 > import java.util.List;
15 > import java.util.Map;
16 > import java.util.WeakHashMap;
17  
18   /**
19 < * Abstract base class for tasks that run within a {@link
20 < * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
19 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
20 > * A {@code ForkJoinTask} is a thread-like entity that is much
21   * lighter weight than a normal thread.  Huge numbers of tasks and
22   * subtasks may be hosted by a small number of actual threads in a
23   * ForkJoinPool, at the price of some usage limitations.
24   *
25 < * <p> A "main" ForkJoinTask begins execution when submitted to a
26 < * {@link ForkJoinPool}. Once started, it will usually in turn start
27 < * other subtasks.  As indicated by the name of this class, many
28 < * programs using ForkJoinTasks employ only methods {@code fork}
29 < * and {@code join}, or derivatives such as
30 < * {@code invokeAll}.  However, this class also provides a number
31 < * of other methods that can come into play in advanced usages, as
32 < * well as extension mechanics that allow support of new forms of
33 < * fork/join processing.
25 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
26 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
27 > * start other subtasks.  As indicated by the name of this class,
28 > * many programs using {@code ForkJoinTask} employ only methods
29 > * {@link #fork} and {@link #join}, or derivatives such as {@link
30 > * #invokeAll}.  However, this class also provides a number of other
31 > * methods that can come into play in advanced usages, as well as
32 > * extension mechanics that allow support of new forms of fork/join
33 > * processing.
34   *
35 < * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
36 < * efficiency of ForkJoinTasks stems from a set of restrictions (that
37 < * are only partially statically enforceable) reflecting their
38 < * intended use as computational tasks calculating pure functions or
39 < * operating on purely isolated objects.  The primary coordination
40 < * mechanisms are {@link #fork}, that arranges asynchronous execution,
41 < * and {@link #join}, that doesn't proceed until the task's result has
42 < * been computed.  Computations should avoid {@code synchronized}
43 < * methods or blocks, and should minimize other blocking
44 < * synchronization apart from joining other tasks or using
45 < * synchronizers such as Phasers that are advertised to cooperate with
46 < * fork/join scheduling. Tasks should also not perform blocking IO,
47 < * and should ideally access variables that are completely independent
48 < * of those accessed by other running tasks. Minor breaches of these
49 < * restrictions, for example using shared output streams, may be
50 < * tolerable in practice, but frequent use may result in poor
51 < * performance, and the potential to indefinitely stall if the number
52 < * of threads not waiting for IO or other external synchronization
53 < * becomes exhausted. This usage restriction is in part enforced by
54 < * not permitting checked exceptions such as {@code IOExceptions}
55 < * to be thrown. However, computations may still encounter unchecked
56 < * exceptions, that are rethrown to callers attempting join
57 < * them. These exceptions may additionally include
58 < * RejectedExecutionExceptions stemming from internal resource
59 < * exhaustion such as failure to allocate internal task queues.
35 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
36 > * The efficiency of {@code ForkJoinTask}s stems from a set of
37 > * restrictions (that are only partially statically enforceable)
38 > * reflecting their intended use as computational tasks calculating
39 > * pure functions or operating on purely isolated objects.  The
40 > * primary coordination mechanisms are {@link #fork}, that arranges
41 > * asynchronous execution, and {@link #join}, that doesn't proceed
42 > * until the task's result has been computed.  Computations should
43 > * avoid {@code synchronized} methods or blocks, and should minimize
44 > * other blocking synchronization apart from joining other tasks or
45 > * using synchronizers such as Phasers that are advertised to
46 > * cooperate with fork/join scheduling. Tasks should also not perform
47 > * blocking IO, and should ideally access variables that are
48 > * completely independent of those accessed by other running
49 > * tasks. Minor breaches of these restrictions, for example using
50 > * shared output streams, may be tolerable in practice, but frequent
51 > * use may result in poor performance, and the potential to
52 > * indefinitely stall if the number of threads not waiting for IO or
53 > * other external synchronization becomes exhausted. This usage
54 > * restriction is in part enforced by not permitting checked
55 > * exceptions such as {@code IOExceptions} to be thrown. However,
56 > * computations may still encounter unchecked exceptions, that are
57 > * rethrown to callers attempting join them. These exceptions may
58 > * additionally include RejectedExecutionExceptions stemming from
59 > * internal resource exhaustion such as failure to allocate internal
60 > * task queues.
61   *
62   * <p>The primary method for awaiting completion and extracting
63   * results of a task is {@link #join}, but there are several variants:
# Line 72 | Line 76 | import java.lang.reflect.*;
76   * performs the most common form of parallel invocation: forking a set
77   * of tasks and joining them all.
78   *
79 < * <p> The ForkJoinTask class is not usually directly subclassed.
79 > * <p>The ForkJoinTask class is not usually directly subclassed.
80   * Instead, you subclass one of the abstract classes that support a
81 < * particular style of fork/join processing.  Normally, a concrete
81 > * particular style of fork/join processing, typically {@link
82 > * RecursiveAction} for computations that do not return results, or
83 > * {@link RecursiveTask} for those that do.  Normally, a concrete
84   * ForkJoinTask subclass declares fields comprising its parameters,
85   * established in a constructor, and then defines a {@code compute}
86   * method that somehow uses the control methods supplied by this base
87   * class. While these methods have {@code public} access (to allow
88   * instances of different task subclasses to call each others
89   * methods), some of them may only be called from within other
90 < * ForkJoinTasks. Attempts to invoke them in other contexts result in
91 < * exceptions or errors possibly including ClassCastException.
90 > * ForkJoinTasks (as may be determined using method {@link
91 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
92 > * result in exceptions or errors, possibly including
93 > * ClassCastException.
94   *
95   * <p>Most base support methods are {@code final} because their
96   * implementations are intrinsically tied to the underlying
97   * lightweight task scheduling framework, and so cannot be overridden.
98   * Developers creating new basic styles of fork/join processing should
99   * minimally implement {@code protected} methods
100 < * {@code exec}, {@code setRawResult}, and
101 < * {@code getRawResult}, while also introducing an abstract
100 > * {@link #exec}, {@link #setRawResult}, and
101 > * {@link #getRawResult}, while also introducing an abstract
102   * computational method that can be implemented in its subclasses,
103   * possibly relying on other {@code protected} methods provided
104   * by this class.
105   *
106   * <p>ForkJoinTasks should perform relatively small amounts of
107 < * computations, othewise splitting into smaller tasks. As a very
107 > * computations, otherwise 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
110 > * parallelism cannot improve throughput. If too small, then memory
111   * and internal task maintenance overhead may overwhelm processing.
112   *
113 + * <p>This class provides {@code adapt} methods for {@link
114 + * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
115 + * may be of use when mixing execution of ForkJoinTasks with other
116 + * kinds of tasks. When all tasks are of this form, consider using a
117 + * pool in {@link ForkJoinPool#setAsyncMode}.
118 + *
119   * <p>ForkJoinTasks are {@code Serializable}, which enables them
120   * to be used in extensions such as remote execution frameworks. It is
121   * in general sensible to serialize tasks only before or after, but
122   * not during execution. Serialization is not relied on during
123   * 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 {
# Line 375 | Line 397 | public abstract class ForkJoinTask<V> im
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 {
# 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 possibly 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} 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 499 | Line 530 | public abstract class ForkJoinTask<V> im
530      /**
531       * Commences performing this task, awaits its completion if
532       * necessary, and return its result.
533 +     *
534       * @throws Throwable (a RuntimeException, Error, or unchecked
535 <     * exception) if the underlying computation did so.
535 >     * exception) if the underlying computation did so
536       * @return the computed result
537       */
538      public final V invoke() {
# Line 511 | Line 543 | public abstract class ForkJoinTask<V> im
543      }
544  
545      /**
546 <     * Forks both tasks, returning when {@code isDone} holds for
547 <     * both of them or an exception is encountered. This method may be
548 <     * invoked only from within ForkJoinTask computations. Attempts to
549 <     * invoke in other contexts result in exceptions or errors
550 <     * possibly including ClassCastException.
551 <     * @param t1 one task
552 <     * @param t2 the other task
553 <     * @throws NullPointerException if t1 or t2 are null
554 <     * @throws RuntimeException or Error if either task did so.
546 >     * Forks the given tasks, returning when {@code isDone} holds
547 >     * for each task or an exception is encountered.
548 >     *
549 >     * <p>This method may be invoked only from within {@code
550 >     * ForkJoinTask} computations (as may be determined using method
551 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
552 >     * result in exceptions or errors, possibly including {@code
553 >     * ClassCastException}.
554 >     *
555 >     * @param t1 the first task
556 >     * @param t2 the second task
557 >     * @throws NullPointerException if any task is null
558 >     * @throws RuntimeException or Error if a task did so
559       */
560 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
560 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
561          t2.fork();
562          t1.invoke();
563          t2.join();
564      }
565  
566      /**
567 <     * Forks the given tasks, returning when {@code isDone} holds
568 <     * for all of them. If any task encounters an exception, others
569 <     * may be cancelled.  This method may be invoked only from within
570 <     * ForkJoinTask computations. Attempts to invoke in other contexts
571 <     * result in exceptions or errors possibly including ClassCastException.
572 <     * @param tasks the array of tasks
573 <     * @throws NullPointerException if tasks or any element are null.
574 <     * @throws RuntimeException or Error if any task did so.
567 >     * Forks the given tasks, returning when {@code isDone} holds for
568 >     * each task or an exception is encountered. If any task
569 >     * encounters an exception, others may be, but are not guaranteed
570 >     * to be, cancelled.
571 >     *
572 >     * <p>This method may be invoked only from within {@code
573 >     * ForkJoinTask} computations (as may be determined using method
574 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
575 >     * result in exceptions or errors, possibly including {@code
576 >     * ClassCastException}.
577 >     *
578 >     * <p>Overloadings of this method exist for the special cases
579 >     * of one to four arguments.
580 >     *
581 >     * @param tasks the tasks
582 >     * @throws NullPointerException if tasks or any element are null
583 >     * @throws RuntimeException or Error if any task did so
584       */
585      public static void invokeAll(ForkJoinTask<?>... tasks) {
586          Throwable ex = null;
# Line 571 | Line 616 | public abstract class ForkJoinTask<V> im
616      }
617  
618      /**
619 <     * Forks all tasks in the collection, returning when
620 <     * {@code isDone} holds for all of them. If any task
621 <     * encounters an exception, others may be cancelled.  This method
622 <     * may be invoked only from within ForkJoinTask
623 <     * computations. Attempts to invoke in other contexts resul!t in
624 <     * exceptions or errors possibly including ClassCastException.
619 >     * Forks all tasks in the collection, returning when {@code
620 >     * isDone} holds for each task or an exception is encountered.
621 >     * If any task encounters an exception, others may be, but are
622 >     * not guaranteed to be, cancelled.
623 >     *
624 >     * <p>This method may be invoked only from within {@code
625 >     * ForkJoinTask} computations (as may be determined using method
626 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
627 >     * result in exceptions or errors, possibly including {@code
628 >     * ClassCastException}.
629 >     *
630       * @param tasks the collection of tasks
631 <     * @throws NullPointerException if tasks or any element are null.
632 <     * @throws RuntimeException or Error if any task did so.
633 <     */
634 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
635 <        if (!(tasks instanceof List)) {
636 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
637 <            return;
631 >     * @return the tasks argument, to simplify usage
632 >     * @throws NullPointerException if tasks or any element are null
633 >     * @throws RuntimeException or Error if any task did so
634 >     */
635 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
636 >        if (!(tasks instanceof List<?>)) {
637 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
638 >            return tasks;
639          }
640 +        @SuppressWarnings("unchecked")
641          List<? extends ForkJoinTask<?>> ts =
642 <            (List<? extends ForkJoinTask<?>>)tasks;
642 >            (List<? extends ForkJoinTask<?>>) tasks;
643          Throwable ex = null;
644          int last = ts.size() - 1;
645          for (int i = last; i >= 0; --i) {
# Line 618 | Line 670 | public abstract class ForkJoinTask<V> im
670          }
671          if (ex != null)
672              rethrowException(ex);
673 +        return tasks;
674      }
675  
676      /**
677 <     * Returns true if the computation performed by this task has
678 <     * completed (or has been cancelled).
679 <     * @return true if this computation has completed
677 >     * Returns {@code true} if the computation performed by this task
678 >     * has completed (or has been cancelled).
679 >     *
680 >     * @return {@code true} if this computation has completed
681       */
682      public final boolean isDone() {
683          return status < 0;
684      }
685  
686      /**
687 <     * Returns true if this task was cancelled.
688 <     * @return true if this task was cancelled
687 >     * Returns {@code true} if this task was cancelled.
688 >     *
689 >     * @return {@code true} if this task was cancelled
690       */
691      public final boolean isCancelled() {
692          return (status & COMPLETION_MASK) == CANCELLED;
# Line 639 | Line 694 | public abstract class ForkJoinTask<V> im
694  
695      /**
696       * Asserts that the results of this task's computation will not be
697 <     * used. If a cancellation occurs before atempting to execute this
698 <     * task, then execution will be suppressed, {@code isCancelled}
699 <     * will report true, and {@code join} will result in a
697 >     * used. If a cancellation occurs before attempting to execute this
698 >     * task, execution will be suppressed, {@link #isCancelled}
699 >     * will report true, and {@link #join} will result in a
700       * {@code CancellationException} being thrown. Otherwise, when
701       * cancellation races with completion, there are no guarantees
702 <     * about whether {@code isCancelled} will report true, whether
703 <     * {@code join} will return normally or via an exception, or
704 <     * whether these behaviors will remain consistent upon repeated
702 >     * about whether {@code isCancelled} will report {@code true},
703 >     * whether {@code join} will return normally or via an exception,
704 >     * or whether these behaviors will remain consistent upon repeated
705       * invocation.
706       *
707       * <p>This method may be overridden in subclasses, but if so, must
708       * still ensure that these minimal properties hold. In particular,
709 <     * the cancel method itself must not throw exceptions.
709 >     * the {@code cancel} method itself must not throw exceptions.
710       *
711 <     * <p> This method is designed to be invoked by <em>other</em>
711 >     * <p>This method is designed to be invoked by <em>other</em>
712       * tasks. To terminate the current task, you can just return or
713       * throw an unchecked exception from its computation method, or
714 <     * invoke {@code completeExceptionally}.
714 >     * invoke {@link #completeExceptionally}.
715       *
716       * @param mayInterruptIfRunning this value is ignored in the
717       * default implementation because tasks are not in general
718 <     * cancelled via interruption.
718 >     * cancelled via interruption
719       *
720 <     * @return true if this task is now cancelled
720 >     * @return {@code true} if this task is now cancelled
721       */
722      public boolean cancel(boolean mayInterruptIfRunning) {
723          setCompletion(CANCELLED);
# Line 670 | Line 725 | public abstract class ForkJoinTask<V> im
725      }
726  
727      /**
728 <     * Returns true if this task threw an exception or was cancelled
729 <     * @return true if this task threw an exception or was cancelled
728 >     * Returns {@code true} if this task threw an exception or was cancelled.
729 >     *
730 >     * @return {@code true} if this task threw an exception or was cancelled
731       */
732      public final boolean isCompletedAbnormally() {
733          return (status & COMPLETION_MASK) < NORMAL;
# Line 679 | Line 735 | public abstract class ForkJoinTask<V> im
735  
736      /**
737       * Returns the exception thrown by the base computation, or a
738 <     * CancellationException if cancelled, or null if none or if the
739 <     * method has not yet completed.
740 <     * @return the exception, or null if none
738 >     * {@code CancellationException} if cancelled, or {@code null} if
739 >     * none or if the method has not yet completed.
740 >     *
741 >     * @return the exception, or {@code null} if none
742       */
743      public final Throwable getException() {
744          int s = status & COMPLETION_MASK;
# Line 698 | Line 755 | public abstract class ForkJoinTask<V> im
755       * {@code join} and related operations. This method may be used
756       * to induce exceptions in asynchronous tasks, or to force
757       * completion of tasks that would not otherwise complete.  Its use
758 <     * in other situations is likely to be wrong.  This method is
758 >     * in other situations is discouraged.  This method is
759       * overridable, but overridden versions must invoke {@code super}
760       * implementation to maintain guarantees.
761       *
# Line 708 | Line 765 | public abstract class ForkJoinTask<V> im
765       */
766      public void completeExceptionally(Throwable ex) {
767          setDoneExceptionally((ex instanceof RuntimeException) ||
768 <                             (ex instanceof Error)? ex :
768 >                             (ex instanceof Error) ? ex :
769                               new RuntimeException(ex));
770      }
771  
# Line 718 | Line 775 | public abstract class ForkJoinTask<V> im
775       * operations. This method may be used to provide results for
776       * asynchronous tasks, or to provide alternative handling for
777       * tasks that would not otherwise complete normally. Its use in
778 <     * other situations is likely to be wrong. This method is
778 >     * other situations is discouraged. This method is
779       * overridable, but overridden versions must invoke {@code super}
780       * implementation to maintain guarantees.
781       *
782 <     * @param value the result value for this task.
782 >     * @param value the result value for this task
783       */
784      public void complete(V value) {
785          try {
786              setRawResult(value);
787 <        } catch(Throwable rex) {
787 >        } catch (Throwable rex) {
788              setDoneExceptionally(rex);
789              return;
790          }
# Line 743 | Line 800 | public abstract class ForkJoinTask<V> im
800  
801      public final V get(long timeout, TimeUnit unit)
802          throws InterruptedException, ExecutionException, TimeoutException {
803 +        long nanos = unit.toNanos(timeout);
804          ForkJoinWorkerThread w = getWorker();
805          if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
806 <            awaitDone(w, unit.toNanos(timeout));
806 >            awaitDone(w, nanos);
807          return reportTimedFutureResult();
808      }
809  
# Line 753 | Line 811 | public abstract class ForkJoinTask<V> im
811       * Possibly executes other tasks until this task is ready, then
812       * returns the result of the computation.  This method may be more
813       * efficient than {@code join}, but is only applicable when
814 <     * there are no potemtial dependencies between continuation of the
814 >     * there are no potential dependencies between continuation of the
815       * current task and that of any other task that might be executed
816       * while helping. (This usually holds for pure divide-and-conquer
817 <     * tasks). This method may be invoked only from within
818 <     * ForkJoinTask computations. Attempts to invoke in other contexts
819 <     * resul!t in exceptions or errors possibly including ClassCastException.
817 >     * tasks).
818 >     *
819 >     * <p>This method may be invoked only from within {@code
820 >     * ForkJoinTask} computations (as may be determined using method
821 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
822 >     * result in exceptions or errors, possibly including {@code
823 >     * ClassCastException}.
824 >     *
825       * @return the computed result
826       */
827      public final V helpJoin() {
828 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
828 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
829          if (status < 0 || !w.unpushTask(this) || !tryExec())
830              reportException(busyJoin(w));
831          return getRawResult();
832      }
833  
834      /**
835 <     * Possibly executes other tasks until this task is ready.  This
836 <     * method may be invoked only from within ForkJoinTask
837 <     * computations. Attempts to invoke in other contexts resul!t in
838 <     * exceptions or errors possibly including ClassCastException.
835 >     * Possibly executes other tasks until this task is ready.
836 >     *
837 >     * <p>This method may be invoked only from within {@code
838 >     * ForkJoinTask} computations (as may be determined using method
839 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
840 >     * result in exceptions or errors, possibly including {@code
841 >     * ClassCastException}.
842       */
843      public final void quietlyHelpJoin() {
844          if (status >= 0) {
845              ForkJoinWorkerThread w =
846 <                (ForkJoinWorkerThread)(Thread.currentThread());
846 >                (ForkJoinWorkerThread) Thread.currentThread();
847              if (!w.unpushTask(this) || !tryQuietlyInvoke())
848                  busyJoin(w);
849          }
# Line 814 | Line 880 | public abstract class ForkJoinTask<V> im
880       * {@link ForkJoinPool#isQuiescent}. This method may be of use in
881       * designs in which many tasks are forked, but none are explicitly
882       * joined, instead executing them until all are processed.
883 +     *
884 +     * <p>This method may be invoked only from within {@code
885 +     * ForkJoinTask} computations (as may be determined using method
886 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
887 +     * result in exceptions or errors, possibly including {@code
888 +     * ClassCastException}.
889       */
890      public static void helpQuiesce() {
891 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
892 <            helpQuiescePool();
891 >        ((ForkJoinWorkerThread) Thread.currentThread())
892 >            .helpQuiescePool();
893      }
894  
895      /**
# Line 826 | Line 898 | public abstract class ForkJoinTask<V> im
898       * this task, but only if reuse occurs when this task has either
899       * never been forked, or has been forked, then completed and all
900       * outstanding joins of this task have also completed. Effects
901 <     * under any other usage conditions are not guaranteed, and are
902 <     * almost surely wrong. This method may be useful when executing
901 >     * under any other usage conditions are not guaranteed.
902 >     * This method may be useful when executing
903       * pre-constructed trees of subtasks in loops.
904       */
905      public void reinitialize() {
# Line 838 | Line 910 | public abstract class ForkJoinTask<V> im
910  
911      /**
912       * Returns the pool hosting the current task execution, or null
913 <     * if this task is executing outside of any pool.
914 <     * @return the pool, or null if none.
913 >     * if this task is executing outside of any ForkJoinPool.
914 >     *
915 >     * @see #inForkJoinPool
916 >     * @return the pool, or {@code null} if none
917       */
918      public static ForkJoinPool getPool() {
919          Thread t = Thread.currentThread();
920 <        return ((t instanceof ForkJoinWorkerThread)?
921 <                ((ForkJoinWorkerThread)t).pool : null);
920 >        return (t instanceof ForkJoinWorkerThread) ?
921 >            ((ForkJoinWorkerThread) t).pool : null;
922 >    }
923 >
924 >    /**
925 >     * Returns {@code true} if the current thread is executing as a
926 >     * ForkJoinPool computation.
927 >     *
928 >     * @return {@code true} if the current thread is executing as a
929 >     * ForkJoinPool computation, or false otherwise
930 >     */
931 >    public static boolean inForkJoinPool() {
932 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
933      }
934  
935      /**
# Line 853 | Line 938 | public abstract class ForkJoinTask<V> im
938       * by the current thread, and has not commenced executing in
939       * another thread.  This method may be useful when arranging
940       * alternative local processing of tasks that could have been, but
941 <     * were not, stolen. This method may be invoked only from within
942 <     * ForkJoinTask computations. Attempts to invoke in other contexts
943 <     * result in exceptions or errors possibly including ClassCastException.
944 <     * @return true if unforked
941 >     * were not, stolen.
942 >     *
943 >     * <p>This method may be invoked only from within {@code
944 >     * ForkJoinTask} computations (as may be determined using method
945 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
946 >     * result in exceptions or errors, possibly including {@code
947 >     * ClassCastException}.
948 >     *
949 >     * @return {@code true} if unforked
950       */
951      public boolean tryUnfork() {
952 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
952 >        return ((ForkJoinWorkerThread) Thread.currentThread())
953 >            .unpushTask(this);
954      }
955  
956      /**
# Line 867 | Line 958 | public abstract class ForkJoinTask<V> im
958       * forked by the current worker thread but not yet executed. This
959       * value may be useful for heuristic decisions about whether to
960       * fork other tasks.
961 +     *
962 +     * <p>This method may be invoked only from within {@code
963 +     * ForkJoinTask} computations (as may be determined using method
964 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
965 +     * result in exceptions or errors, possibly including {@code
966 +     * ClassCastException}.
967 +     *
968       * @return the number of tasks
969       */
970      public static int getQueuedTaskCount() {
971 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
972 <            getQueueSize();
971 >        return ((ForkJoinWorkerThread) Thread.currentThread())
972 >            .getQueueSize();
973      }
974  
975      /**
976 <     * Returns a estimate of how many more locally queued tasks are
976 >     * Returns an estimate of how many more locally queued tasks are
977       * held by the current worker thread than there are other worker
978       * threads that might steal them.  This value may be useful for
979       * heuristic decisions about whether to fork other tasks. In many
# Line 883 | Line 981 | public abstract class ForkJoinTask<V> im
981       * aim to maintain a small constant surplus (for example, 3) of
982       * tasks, and to process computations locally if this threshold is
983       * exceeded.
984 +     *
985 +     * <p>This method may be invoked only from within {@code
986 +     * ForkJoinTask} computations (as may be determined using method
987 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
988 +     * result in exceptions or errors, possibly including {@code
989 +     * ClassCastException}.
990 +     *
991       * @return the surplus number of tasks, which may be negative
992       */
993      public static int getSurplusQueuedTaskCount() {
994 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
994 >        return ((ForkJoinWorkerThread) Thread.currentThread())
995              .getEstimatedSurplusTaskCount();
996      }
997  
998      // Extension methods
999  
1000      /**
1001 <     * Returns the result that would be returned by {@code join},
1002 <     * even if this task completed abnormally, or null if this task is
1003 <     * not known to have been completed.  This method is designed to
1004 <     * aid debugging, as well as to support extensions. Its use in any
1005 <     * other context is discouraged.
1001 >     * Returns the result that would be returned by {@link #join}, even
1002 >     * if this task completed abnormally, or {@code null} if this task
1003 >     * is not known to have been completed.  This method is designed
1004 >     * to aid debugging, as well as to support extensions. Its use in
1005 >     * any other context is discouraged.
1006       *
1007 <     * @return the result, or null if not completed.
1007 >     * @return the result, or {@code null} if not completed
1008       */
1009      public abstract V getRawResult();
1010  
# Line 918 | Line 1023 | public abstract class ForkJoinTask<V> im
1023       * called otherwise. The return value controls whether this task
1024       * is considered to be done normally. It may return false in
1025       * asynchronous actions that require explicit invocations of
1026 <     * {@code complete} to become joinable. It may throw exceptions
1026 >     * {@link #complete} to become joinable. It may throw exceptions
1027       * to indicate abnormal exit.
1028 <     * @return true if completed normally
1028 >     *
1029 >     * @return {@code true} if completed normally
1030       * @throws Error or RuntimeException if encountered during computation
1031       */
1032      protected abstract boolean exec();
1033  
1034      /**
1035 <     * Returns, but does not unschedule or execute, the task queued by
1036 <     * the current thread but not yet executed, if one is
1035 >     * Returns, but does not unschedule or execute, a task queued by
1036 >     * the current thread but not yet executed, if one is immediately
1037       * available. There is no guarantee that this task will actually
1038 <     * be polled or executed next.  This method is designed primarily
1039 <     * to support extensions, and is unlikely to be useful otherwise.
1040 <     * This method may be invoked only from within ForkJoinTask
1041 <     * computations. Attempts to invoke in other contexts result in
1042 <     * exceptions or errors possibly including ClassCastException.
1038 >     * be polled or executed next. Conversely, this method may return
1039 >     * null even if a task exists but cannot be accessed without
1040 >     * contention with other threads.  This method is designed
1041 >     * primarily to support extensions, and is unlikely to be useful
1042 >     * otherwise.
1043       *
1044 <     * @return the next task, or null if none are available
1044 >     * <p>This method may be invoked only from within {@code
1045 >     * ForkJoinTask} computations (as may be determined using method
1046 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1047 >     * result in exceptions or errors, possibly including {@code
1048 >     * ClassCastException}.
1049 >     *
1050 >     * @return the next task, or {@code null} if none are available
1051       */
1052      protected static ForkJoinTask<?> peekNextLocalTask() {
1053 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
1053 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1054 >            .peekTask();
1055      }
1056  
1057      /**
1058       * Unschedules and returns, without executing, the next task
1059       * queued by the current thread but not yet executed.  This method
1060       * is designed primarily to support extensions, and is unlikely to
1061 <     * be useful otherwise.  This method may be invoked only from
1062 <     * within ForkJoinTask computations. Attempts to invoke in other
1063 <     * contexts result in exceptions or errors possibly including
1064 <     * ClassCastException.
1061 >     * be useful otherwise.
1062 >     *
1063 >     * <p>This method may be invoked only from within {@code
1064 >     * ForkJoinTask} computations (as may be determined using method
1065 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1066 >     * result in exceptions or errors, possibly including {@code
1067 >     * ClassCastException}.
1068       *
1069 <     * @return the next task, or null if none are available
1069 >     * @return the next task, or {@code null} if none are available
1070       */
1071      protected static ForkJoinTask<?> pollNextLocalTask() {
1072 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
1072 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1073 >            .pollLocalTask();
1074      }
1075  
1076      /**
# Line 961 | Line 1078 | public abstract class ForkJoinTask<V> im
1078       * queued by the current thread but not yet executed, if one is
1079       * available, or if not available, a task that was forked by some
1080       * other thread, if available. Availability may be transient, so a
1081 <     * {@code null} result does not necessarily imply quiecence
1081 >     * {@code null} result does not necessarily imply quiescence
1082       * of the pool this task is operating in.  This method is designed
1083       * primarily to support extensions, and is unlikely to be useful
1084 <     * otherwise.  This method may be invoked only from within
968 <     * ForkJoinTask computations. Attempts to invoke in other contexts
969 <     * result in exceptions or errors possibly including
970 <     * ClassCastException.
1084 >     * otherwise.
1085       *
1086 <     * @return a task, or null if none are available
1086 >     * <p>This method may be invoked only from within {@code
1087 >     * ForkJoinTask} computations (as may be determined using method
1088 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1089 >     * result in exceptions or errors, possibly including {@code
1090 >     * ClassCastException}.
1091 >     *
1092 >     * @return a task, or {@code null} if none are available
1093       */
1094      protected static ForkJoinTask<?> pollTask() {
1095 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1096 <            pollTask();
1095 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1096 >            .pollTask();
1097 >    }
1098 >
1099 >    /**
1100 >     * Adaptor for Runnables. This implements RunnableFuture
1101 >     * to be compliant with AbstractExecutorService constraints
1102 >     * when used in ForkJoinPool.
1103 >     */
1104 >    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1105 >        implements RunnableFuture<T> {
1106 >        final Runnable runnable;
1107 >        final T resultOnCompletion;
1108 >        T result;
1109 >        AdaptedRunnable(Runnable runnable, T result) {
1110 >            if (runnable == null) throw new NullPointerException();
1111 >            this.runnable = runnable;
1112 >            this.resultOnCompletion = result;
1113 >        }
1114 >        public T getRawResult() { return result; }
1115 >        public void setRawResult(T v) { result = v; }
1116 >        public boolean exec() {
1117 >            runnable.run();
1118 >            result = resultOnCompletion;
1119 >            return true;
1120 >        }
1121 >        public void run() { invoke(); }
1122 >        private static final long serialVersionUID = 5232453952276885070L;
1123 >    }
1124 >
1125 >    /**
1126 >     * Adaptor for Callables
1127 >     */
1128 >    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1129 >        implements RunnableFuture<T> {
1130 >        final Callable<? extends T> callable;
1131 >        T result;
1132 >        AdaptedCallable(Callable<? extends T> callable) {
1133 >            if (callable == null) throw new NullPointerException();
1134 >            this.callable = callable;
1135 >        }
1136 >        public T getRawResult() { return result; }
1137 >        public void setRawResult(T v) { result = v; }
1138 >        public boolean exec() {
1139 >            try {
1140 >                result = callable.call();
1141 >                return true;
1142 >            } catch (Error err) {
1143 >                throw err;
1144 >            } catch (RuntimeException rex) {
1145 >                throw rex;
1146 >            } catch (Exception ex) {
1147 >                throw new RuntimeException(ex);
1148 >            }
1149 >        }
1150 >        public void run() { invoke(); }
1151 >        private static final long serialVersionUID = 2838392045355241008L;
1152 >    }
1153 >
1154 >    /**
1155 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1156 >     * method of the given {@code Runnable} as its action, and returns
1157 >     * a null result upon {@link #join}.
1158 >     *
1159 >     * @param runnable the runnable action
1160 >     * @return the task
1161 >     */
1162 >    public static ForkJoinTask<?> adapt(Runnable runnable) {
1163 >        return new AdaptedRunnable<Void>(runnable, null);
1164 >    }
1165 >
1166 >    /**
1167 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1168 >     * method of the given {@code Runnable} as its action, and returns
1169 >     * the given result upon {@link #join}.
1170 >     *
1171 >     * @param runnable the runnable action
1172 >     * @param result the result upon completion
1173 >     * @return the task
1174 >     */
1175 >    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1176 >        return new AdaptedRunnable<T>(runnable, result);
1177 >    }
1178 >
1179 >    /**
1180 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1181 >     * method of the given {@code Callable} as its action, and returns
1182 >     * its result upon {@link #join}, translating any checked exceptions
1183 >     * encountered into {@code RuntimeException}.
1184 >     *
1185 >     * @param callable the callable action
1186 >     * @return the task
1187 >     */
1188 >    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1189 >        return new AdaptedCallable<T>(callable);
1190      }
1191  
1192      // Serialization support
# Line 984 | Line 1197 | public abstract class ForkJoinTask<V> im
1197       * Save the state to a stream.
1198       *
1199       * @serialData the current run status and the exception thrown
1200 <     * during execution, or null if none.
1200 >     * during execution, or {@code null} if none
1201       * @param s the stream
1202       */
1203      private void writeObject(java.io.ObjectOutputStream s)
# Line 995 | Line 1208 | public abstract class ForkJoinTask<V> im
1208  
1209      /**
1210       * Reconstitute the instance from a stream.
1211 +     *
1212       * @param s the stream
1213       */
1214      private void readObject(java.io.ObjectInputStream s)
# Line 1004 | Line 1218 | public abstract class ForkJoinTask<V> im
1218          status |= EXTERNAL_SIGNAL; // conservatively set external signal
1219          Object ex = s.readObject();
1220          if (ex != null)
1221 <            setDoneExceptionally((Throwable)ex);
1221 >            setDoneExceptionally((Throwable) ex);
1222 >    }
1223 >
1224 >    // Unsafe mechanics
1225 >
1226 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1227 >    private static final long statusOffset =
1228 >        objectFieldOffset("status", ForkJoinTask.class);
1229 >
1230 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1231 >        try {
1232 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1233 >        } catch (NoSuchFieldException e) {
1234 >            // Convert Exception to corresponding Error
1235 >            NoSuchFieldError error = new NoSuchFieldError(field);
1236 >            error.initCause(e);
1237 >            throw error;
1238 >        }
1239      }
1240  
1241 <    // Temporary Unsafe mechanics for preliminary release
1242 <    private static Unsafe getUnsafe() throws Throwable {
1241 >    /**
1242 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1243 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1244 >     * into a jdk.
1245 >     *
1246 >     * @return a sun.misc.Unsafe
1247 >     */
1248 >    private static sun.misc.Unsafe getUnsafe() {
1249          try {
1250 <            return Unsafe.getUnsafe();
1250 >            return sun.misc.Unsafe.getUnsafe();
1251          } catch (SecurityException se) {
1252              try {
1253                  return java.security.AccessController.doPrivileged
1254 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1255 <                        public Unsafe run() throws Exception {
1256 <                            return getUnsafePrivileged();
1254 >                    (new java.security
1255 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1256 >                        public sun.misc.Unsafe run() throws Exception {
1257 >                            java.lang.reflect.Field f = sun.misc
1258 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1259 >                            f.setAccessible(true);
1260 >                            return (sun.misc.Unsafe) f.get(null);
1261                          }});
1262              } catch (java.security.PrivilegedActionException e) {
1263 <                throw e.getCause();
1263 >                throw new RuntimeException("Could not initialize intrinsics",
1264 >                                           e.getCause());
1265              }
1266          }
1267      }
1026
1027    private static Unsafe getUnsafePrivileged()
1028            throws NoSuchFieldException, IllegalAccessException {
1029        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1030        f.setAccessible(true);
1031        return (Unsafe) f.get(null);
1032    }
1033
1034    private static long fieldOffset(String fieldName)
1035            throws NoSuchFieldException {
1036        return _unsafe.objectFieldOffset
1037            (ForkJoinTask.class.getDeclaredField(fieldName));
1038    }
1039
1040    static final Unsafe _unsafe;
1041    static final long statusOffset;
1042
1043    static {
1044        try {
1045            _unsafe = getUnsafe();
1046            statusOffset = fieldOffset("status");
1047        } catch (Throwable e) {
1048            throw new RuntimeException("Could not initialize intrinsics", e);
1049        }
1050    }
1051
1268   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines