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.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.29 by jsr166, Sun Aug 2 17:19:24 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 ForkJoinPool.  A
20 < * ForkJoinTask is a thread-like entity that is much lighter weight
21 < * than a normal thread.  Huge numbers of tasks and subtasks may be
22 < * hosted by a small number of actual threads in a ForkJoinPool,
23 < * at the price of some usage limitations.
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> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
26 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
27 < * set of restrictions (that are only partially statically
28 < * enforceable) reflecting their intended use as computational tasks
29 < * calculating pure functions or operating on purely isolated objects.
30 < * The primary coordination mechanisms supported for ForkJoinTasks are
31 < * <tt>fork</tt>, that arranges asynchronous execution, and
32 < * <tt>join</tt>, that doesn't proceed until the task's result has
33 < * been computed. (Cancellation is also supported).  The computation
31 < * defined in the <tt>compute</tt> method should avoid
32 < * <tt>synchronized</tt> methods or blocks, and should minimize
33 < * blocking synchronization apart from joining other tasks or using
34 < * synchronizers such as Phasers that are advertised to cooperate with
35 < * fork/join scheduling. Tasks should also not perform blocking IO,
36 < * and should ideally access variables that are completely independent
37 < * of those accessed by other running tasks. Minor breaches of these
38 < * restrictions, for example using shared output streams, may be
39 < * tolerable in practice, but frequent use may result in poor
40 < * performance, and the potential to indefinitely stall if the number
41 < * of threads not waiting for external synchronization becomes
42 < * exhausted. This usage restriction is in part enforced by not
43 < * permitting checked exceptions such as IOExceptions to be
44 < * thrown. However, computations may still encounter unchecked
45 < * exceptions, that are rethrown to callers attempting join
46 < * them. These exceptions may additionally include
47 < * RejectedExecutionExceptions stemming from internal resource
48 < * exhaustion such as failure to allocate internal task queues.
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> The <tt>ForkJoinTask</tt> class is not usually directly
36 < * subclassed.  Instead, you subclass one of the abstract classes that
37 < * support different styles of fork/join processing.  Normally, a
38 < * concrete ForkJoinTask subclass declares fields comprising its
39 < * parameters, established in a constructor, and then defines a
40 < * <tt>compute</tt> method that somehow uses the control methods
41 < * supplied by this base class. While these methods have
42 < * <tt>public</tt> access, some of them may only be called from within
43 < * other ForkJoinTasks. Attempts to invoke them in other contexts
44 < * result in exceptions or errors including ClassCastException.  The
45 < * only way to invoke a "main" driver task is to submit it to a
46 < * ForkJoinPool. Once started, this will usually in turn start other
47 < * subtasks.
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>Most base support methods are <tt>final</tt> because their
62 > * <p>The primary method for awaiting completion and extracting
63 > * results of a task is {@link #join}, but there are several variants:
64 > * The {@link Future#get} methods support interruptible and/or timed
65 > * waits for completion and report results using {@code Future}
66 > * conventions. Method {@link #helpJoin} enables callers to actively
67 > * execute other tasks while awaiting joins, which is sometimes more
68 > * efficient but only applies when all subtasks are known to be
69 > * strictly tree-structured. Method {@link #invoke} is semantically
70 > * equivalent to {@code fork(); join()} but always attempts to
71 > * begin execution in the current thread. The "<em>quiet</em>" forms
72 > * of these methods do not extract results or report exceptions. These
73 > * may be useful when a set of tasks are being executed, and you need
74 > * to delay processing of results or exceptions until all complete.
75 > * Method {@code invokeAll} (available in multiple versions)
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.
80 > * Instead, you subclass one of the abstract classes that support a
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 (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 protected methods <tt>exec</tt>,
100 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
101 < * introducing an abstract computational method that can be
102 < * implemented in its subclasses. To support such extensions,
103 < * instances of ForkJoinTasks maintain an atomically updated
104 < * <tt>short</tt> representing user-defined control state.  Control
74 < * state is guaranteed initially to be zero, and to be negative upon
75 < * completion, but may otherwise be used for any other control
76 < * purposes, such as maintaining join counts.  The {@link
77 < * ForkJoinWorkerThread} class supports additional inspection and
78 < * tuning methods that can be useful when developing extensions.
99 > * minimally implement {@code protected} methods
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>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
114 < * be used in extensions such as remote execution frameworks. However,
115 < * it is in general safe to serialize tasks only before or after, but
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 +
130      /**
131 <     * Status field holding all run status. We pack this into a single
132 <     * int both to minimize footprint overhead and to ensure atomicity
133 <     * (updates are via CAS).
98 <     *
99 <     * Status is initially zero, and takes on nonnegative values until
131 >     * Run control status bits packed into a single int to minimize
132 >     * footprint and to ensure atomicity (via CAS).  Status is
133 >     * initially zero, and takes on nonnegative values until
134       * completed, upon which status holds COMPLETED. CANCELLED, or
135       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
136       * blocking waits by other threads have SIGNAL_MASK bits set --
# Line 111 | 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 124 | 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 136 | 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);
145 <    }
146 <
147 <    /**
148 <     * Get pool of current worker thread, or null if not a worker thread
149 <     */
150 <    static ForkJoinPool getWorkerPool() {
151 <        Thread t = Thread.currentThread();
152 <        return ((t instanceof ForkJoinWorkerThread)?
153 <                ((ForkJoinWorkerThread)t).pool : 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 162 | 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 = getWorkerPool();
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 193 | 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 247 | 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 <    final 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 266 | Line 294 | public abstract class ForkJoinTask<V> im
294  
295      /**
296       * Timed version of awaitDone
297 +     *
298       * @return status upon exit
299       */
300 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
301 <        ForkJoinPool pool = w == null? null : w.pool;
300 >    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
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 289 | 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 314 | Line 343 | public abstract class ForkJoinTask<V> im
343          }
344      }
345  
346 +    /**
347 +     * Handles interruptions during waits.
348 +     */
349      private void onInterruptedWait() {
350 <        Thread t = Thread.currentThread();
351 <        if (t instanceof ForkJoinWorkerThread) {
352 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
353 <            if (w.isTerminating())
354 <                cancelIgnoreExceptions();
355 <        }
324 <        else { // re-interrupt
325 <            try {
326 <                t.interrupt();
327 <            } catch (SecurityException ignore) {
328 <            }
329 <        }
350 >        ForkJoinWorkerThread w = getWorker();
351 >        if (w == null)
352 >            Thread.currentThread().interrupt(); // re-interrupt
353 >        else if (w.isTerminating())
354 >            cancelIgnoringExceptions();
355 >        // else if FJworker, ignore interrupt
356      }
357  
358      // Recording and reporting exceptions
# Line 337 | 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 350 | 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 370 | 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 391 | 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 409 | 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 425 | 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 442 | 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 cancelIgnoreExceptions() {
476 >    final void cancelIgnoringExceptions() {
477          try {
478              cancel(false);
479 <        } catch(Throwable ignore) {
479 >        } catch (Throwable ignore) {
480          }
481      }
482  
483 +    /**
484 +     * Main implementation of helpJoin
485 +     */
486 +    private int busyJoin(ForkJoinWorkerThread w) {
487 +        int s;
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
492 +    }
493 +
494      // public methods
495  
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 other ForkJoinTask
501 <     * computations. Attempts to invoke in other contexts result in
502 <     * exceptions or errors including ClassCastException.
500 >     * method may be invoked only from within ForkJoinTask
501 >     * computations (as may be determined using method {@link
502 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
503 >     * in exceptions or errors, possibly including ClassCastException.
504 >     *
505 >     * @return {@code this}, to simplify usage.
506       */
507 <    public final void fork() {
508 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
507 >    public final ForkJoinTask<V> fork() {
508 >        ((ForkJoinWorkerThread) Thread.currentThread())
509 >            .pushTask(this);
510 >        return this;
511      }
512  
513      /**
514       * Returns the result of the computation when it is ready.
515 <     * This method differs from <tt>get</tt> in that abnormal
515 >     * This method differs from {@code get} in that abnormal
516       * completion results in RuntimeExceptions or Errors, not
517       * ExecutionExceptions.
518       *
# Line 480 | Line 525 | public abstract class ForkJoinTask<V> im
525          return getRawResult();
526      }
527  
483    public final V get() throws InterruptedException, ExecutionException {
484        ForkJoinWorkerThread w = getWorker();
485        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
486            awaitDone(w, true);
487        return reportFutureResult();
488    }
489
490    public final V get(long timeout, TimeUnit unit)
491        throws InterruptedException, ExecutionException, TimeoutException {
492        ForkJoinWorkerThread w = getWorker();
493        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
494            awaitDone(w, unit.toNanos(timeout));
495        return reportTimedFutureResult();
496    }
497
528      /**
529 <     * Possibly executes other tasks until this task is ready, then
530 <     * returns the result of the computation.  This method may be more
531 <     * efficient than <tt>join</tt>, but is only applicable when there
502 <     * are no potemtial dependencies between continuation of the
503 <     * current task and that of any other task that might be executed
504 <     * while helping. (This usually holds for pure divide-and-conquer
505 <     * tasks).
506 <     * @return the computed result
507 <     */
508 <    public final V helpJoin() {
509 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
510 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
511 <            reportException(w.helpJoinTask(this));
512 <        return getRawResult();
513 <    }
514 <
515 <    /**
516 <     * Performs this task, awaits its completion if necessary, and
517 <     * return its result.
529 >     * Commences performing this task, awaits its completion if
530 >     * necessary, and return its result.
531 >     *
532       * @throws Throwable (a RuntimeException, Error, or unchecked
533 <     * exception) if the underlying computation did so.
533 >     * exception) if the underlying computation did so
534       * @return the computed result
535       */
536      public final V invoke() {
# Line 527 | Line 541 | public abstract class ForkJoinTask<V> im
541      }
542  
543      /**
544 <     * Joins this task, without returning its result or throwing an
545 <     * exception. This method may be useful when processing
546 <     * collections of tasks when some have been cancelled or otherwise
547 <     * known to have aborted.
544 >     * Forks the given tasks, returning when {@code isDone} holds for
545 >     * each task or an exception is encountered. This method may be
546 >     * invoked only from within ForkJoinTask computations (as may be
547 >     * determined using method {@link #inForkJoinPool}). Attempts to
548 >     * invoke in other contexts result in exceptions or errors,
549 >     * possibly including ClassCastException.
550 >     *
551 >     * @param t1 the first task
552 >     * @param t2 the second task
553 >     * @throws NullPointerException if any task is null
554 >     * @throws RuntimeException or Error if a task did so
555       */
556 <    public final void quietlyJoin() {
557 <        if (status >= 0) {
558 <            ForkJoinWorkerThread w = getWorker();
559 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
556 >    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
557 >        t2.fork();
558 >        t1.invoke();
559 >        t2.join();
560      }
561  
562      /**
563 <     * Possibly executes other tasks until this task is ready.
563 >     * Forks the given tasks, returning when {@code isDone} holds for
564 >     * each task or an exception is encountered. If any task
565 >     * encounters an exception, others may be, but are not guaranteed
566 >     * to be, cancelled.  This method may be invoked only from within
567 >     * ForkJoinTask computations (as may be determined using method
568 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
569 >     * result in exceptions or errors, possibly including
570 >     * ClassCastException.
571 >     *
572 >     * Overloadings of this method exist for the special cases
573 >     * of one to four arguments.
574 >     *
575 >     * @param tasks the tasks
576 >     * @throws NullPointerException if tasks or any element are null
577 >     * @throws RuntimeException or Error if any task did so
578       */
579 <    public final void quietlyHelpJoin() {
580 <        if (status >= 0) {
581 <            ForkJoinWorkerThread w =
582 <                (ForkJoinWorkerThread)(Thread.currentThread());
583 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
584 <                w.helpJoinTask(this);
579 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
580 >        Throwable ex = null;
581 >        int last = tasks.length - 1;
582 >        for (int i = last; i >= 0; --i) {
583 >            ForkJoinTask<?> t = tasks[i];
584 >            if (t == null) {
585 >                if (ex == null)
586 >                    ex = new NullPointerException();
587 >            }
588 >            else if (i != 0)
589 >                t.fork();
590 >            else {
591 >                t.quietlyInvoke();
592 >                if (ex == null)
593 >                    ex = t.getException();
594 >            }
595 >        }
596 >        for (int i = 1; i <= last; ++i) {
597 >            ForkJoinTask<?> t = tasks[i];
598 >            if (t != null) {
599 >                if (ex != null)
600 >                    t.cancel(false);
601 >                else {
602 >                    t.quietlyJoin();
603 >                    if (ex == null)
604 >                        ex = t.getException();
605 >                }
606 >            }
607          }
608 +        if (ex != null)
609 +            rethrowException(ex);
610      }
611  
612      /**
613 <     * Performs this task and awaits its completion if necessary,
614 <     * without returning its result or throwing an exception. This
615 <     * method may be useful when processing collections of tasks when
616 <     * some have been cancelled or otherwise known to have aborted.
617 <     */
618 <    public final void quietlyInvoke() {
619 <        if (status >= 0 && !tryQuietlyInvoke())
620 <            quietlyJoin();
613 >     * Forks all tasks in the collection, returning when {@code
614 >     * isDone} holds for each task or an exception is encountered. If
615 >     * any task encounters an exception, others may be, but are not
616 >     * guaranteed to be, cancelled.  This method may be invoked only
617 >     * from within ForkJoinTask computations (as may be determined
618 >     * using method {@link #inForkJoinPool}). Attempts to invoke in
619 >     * other contexts result in exceptions or errors, possibly
620 >     * including ClassCastException.
621 >     *
622 >     * @param tasks the collection of tasks
623 >     * @return the tasks argument, to simplify usage
624 >     * @throws NullPointerException if tasks or any element are null
625 >     * @throws RuntimeException or Error if any task did so
626 >     */
627 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
628 >        if (!(tasks instanceof List<?>)) {
629 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
630 >            return tasks;
631 >        }
632 >        @SuppressWarnings("unchecked")
633 >        List<? extends ForkJoinTask<?>> ts =
634 >            (List<? extends ForkJoinTask<?>>) tasks;
635 >        Throwable ex = null;
636 >        int last = ts.size() - 1;
637 >        for (int i = last; i >= 0; --i) {
638 >            ForkJoinTask<?> t = ts.get(i);
639 >            if (t == null) {
640 >                if (ex == null)
641 >                    ex = new NullPointerException();
642 >            }
643 >            else if (i != 0)
644 >                t.fork();
645 >            else {
646 >                t.quietlyInvoke();
647 >                if (ex == null)
648 >                    ex = t.getException();
649 >            }
650 >        }
651 >        for (int i = 1; i <= last; ++i) {
652 >            ForkJoinTask<?> t = ts.get(i);
653 >            if (t != null) {
654 >                if (ex != null)
655 >                    t.cancel(false);
656 >                else {
657 >                    t.quietlyJoin();
658 >                    if (ex == null)
659 >                        ex = t.getException();
660 >                }
661 >            }
662 >        }
663 >        if (ex != null)
664 >            rethrowException(ex);
665 >        return tasks;
666      }
667  
668      /**
669 <     * Returns true if the computation performed by this task has
670 <     * completed (or has been cancelled).
671 <     * @return true if this computation has completed
669 >     * Returns {@code true} if the computation performed by this task
670 >     * has completed (or has been cancelled).
671 >     *
672 >     * @return {@code true} if this computation has completed
673       */
674      public final boolean isDone() {
675          return status < 0;
676      }
677  
678      /**
679 <     * Returns true if this task was cancelled.
680 <     * @return true if this task was cancelled
679 >     * Returns {@code true} if this task was cancelled.
680 >     *
681 >     * @return {@code true} if this task was cancelled
682       */
683      public final boolean isCancelled() {
684          return (status & COMPLETION_MASK) == CANCELLED;
685      }
686  
687      /**
584     * Returns true if this task threw an exception or was cancelled
585     * @return true if this task threw an exception or was cancelled
586     */
587    public final boolean completedAbnormally() {
588        return (status & COMPLETION_MASK) < NORMAL;
589    }
590
591    /**
592     * Returns the exception thrown by the base computation, or a
593     * CancellationException if cancelled, or null if none or if the
594     * method has not yet completed.
595     * @return the exception, or null if none
596     */
597    public final Throwable getException() {
598        int s = status & COMPLETION_MASK;
599        if (s >= NORMAL)
600            return null;
601        if (s == CANCELLED)
602            return new CancellationException();
603        return exceptionMap.get(this);
604    }
605
606    /**
688       * Asserts that the results of this task's computation will not be
689 <     * used. If a cancellation occurs before this task is processed,
690 <     * then its <tt>compute</tt> method will not be executed,
691 <     * <tt>isCancelled</tt> will report true, and <tt>join</tt> will
692 <     * result in a CancellationException being thrown. Otherwise, when
689 >     * used. If a cancellation occurs before attempting to execute this
690 >     * task, execution will be suppressed, {@link #isCancelled}
691 >     * will report true, and {@link #join} will result in a
692 >     * {@code CancellationException} being thrown. Otherwise, when
693       * cancellation races with completion, there are no guarantees
694 <     * about whether <tt>isCancelled</tt> will report true, whether
695 <     * <tt>join</tt> will return normally or via an exception, or
696 <     * whether these behaviors will remain consistent upon repeated
694 >     * about whether {@code isCancelled} will report {@code true},
695 >     * whether {@code join} will return normally or via an exception,
696 >     * or whether these behaviors will remain consistent upon repeated
697       * invocation.
698       *
699       * <p>This method may be overridden in subclasses, but if so, must
700       * still ensure that these minimal properties hold. In particular,
701 <     * the cancel method itself must not throw exceptions.
701 >     * the {@code cancel} method itself must not throw exceptions.
702       *
703 <     * <p> This method is designed to be invoked by <em>other</em>
703 >     * <p>This method is designed to be invoked by <em>other</em>
704       * tasks. To terminate the current task, you can just return or
705       * throw an unchecked exception from its computation method, or
706 <     * invoke <tt>completeExceptionally(someException)</tt>.
706 >     * invoke {@link #completeExceptionally}.
707       *
708       * @param mayInterruptIfRunning this value is ignored in the
709       * default implementation because tasks are not in general
710 <     * cancelled via interruption.
710 >     * cancelled via interruption
711       *
712 <     * @return true if this task is now cancelled
712 >     * @return {@code true} if this task is now cancelled
713       */
714      public boolean cancel(boolean mayInterruptIfRunning) {
715          setCompletion(CANCELLED);
# Line 636 | Line 717 | public abstract class ForkJoinTask<V> im
717      }
718  
719      /**
720 +     * Returns {@code true} if this task threw an exception or was cancelled.
721 +     *
722 +     * @return {@code true} if this task threw an exception or was cancelled
723 +     */
724 +    public final boolean isCompletedAbnormally() {
725 +        return (status & COMPLETION_MASK) < NORMAL;
726 +    }
727 +
728 +    /**
729 +     * Returns the exception thrown by the base computation, or a
730 +     * {@code CancellationException} if cancelled, or {@code null} if
731 +     * none or if the method has not yet completed.
732 +     *
733 +     * @return the exception, or {@code null} if none
734 +     */
735 +    public final Throwable getException() {
736 +        int s = status & COMPLETION_MASK;
737 +        if (s >= NORMAL)
738 +            return null;
739 +        if (s == CANCELLED)
740 +            return new CancellationException();
741 +        return exceptionMap.get(this);
742 +    }
743 +
744 +    /**
745       * Completes this task abnormally, and if not already aborted or
746       * cancelled, causes it to throw the given exception upon
747 <     * <tt>join</tt> and related operations. This method may be used
747 >     * {@code join} and related operations. This method may be used
748       * to induce exceptions in asynchronous tasks, or to force
749 <     * completion of tasks that would not otherwise complete.  This
750 <     * method is overridable, but overridden versions must invoke
751 <     * <tt>super</tt> implementation to maintain guarantees.
749 >     * completion of tasks that would not otherwise complete.  Its use
750 >     * in other situations is discouraged.  This method is
751 >     * overridable, but overridden versions must invoke {@code super}
752 >     * implementation to maintain guarantees.
753 >     *
754       * @param ex the exception to throw. If this exception is
755       * not a RuntimeException or Error, the actual exception thrown
756       * will be a RuntimeException with cause ex.
757       */
758      public void completeExceptionally(Throwable ex) {
759          setDoneExceptionally((ex instanceof RuntimeException) ||
760 <                             (ex instanceof Error)? ex :
760 >                             (ex instanceof Error) ? ex :
761                               new RuntimeException(ex));
762      }
763  
764      /**
765       * Completes this task, and if not already aborted or cancelled,
766 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
766 >     * returning a {@code null} result upon {@code join} and related
767       * operations. This method may be used to provide results for
768       * asynchronous tasks, or to provide alternative handling for
769 <     * tasks that would not otherwise complete normally.
769 >     * tasks that would not otherwise complete normally. Its use in
770 >     * other situations is discouraged. This method is
771 >     * overridable, but overridden versions must invoke {@code super}
772 >     * implementation to maintain guarantees.
773       *
774 <     * @param value the result value for this task.
774 >     * @param value the result value for this task
775       */
776      public void complete(V value) {
777          try {
778              setRawResult(value);
779 <        } catch(Throwable rex) {
779 >        } catch (Throwable rex) {
780              setDoneExceptionally(rex);
781              return;
782          }
783          setNormalCompletion();
784      }
785  
786 +    public final V get() throws InterruptedException, ExecutionException {
787 +        ForkJoinWorkerThread w = getWorker();
788 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
789 +            awaitDone(w, true);
790 +        return reportFutureResult();
791 +    }
792 +
793 +    public final V get(long timeout, TimeUnit unit)
794 +        throws InterruptedException, ExecutionException, TimeoutException {
795 +        long nanos = unit.toNanos(timeout);
796 +        ForkJoinWorkerThread w = getWorker();
797 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
798 +            awaitDone(w, nanos);
799 +        return reportTimedFutureResult();
800 +    }
801 +
802 +    /**
803 +     * Possibly executes other tasks until this task is ready, then
804 +     * returns the result of the computation.  This method may be more
805 +     * efficient than {@code join}, but is only applicable when
806 +     * there are no potential dependencies between continuation of the
807 +     * current task and that of any other task that might be executed
808 +     * while helping. (This usually holds for pure divide-and-conquer
809 +     * tasks). This method may be invoked only from within
810 +     * ForkJoinTask computations (as may be determined using method
811 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
812 +     * result in exceptions or errors, possibly including
813 +     * ClassCastException.
814 +     *
815 +     * @return the computed result
816 +     */
817 +    public final V helpJoin() {
818 +        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
819 +        if (status < 0 || !w.unpushTask(this) || !tryExec())
820 +            reportException(busyJoin(w));
821 +        return getRawResult();
822 +    }
823 +
824 +    /**
825 +     * Possibly executes other tasks until this task is ready.  This
826 +     * method may be invoked only from within ForkJoinTask
827 +     * computations (as may be determined using method {@link
828 +     * #inForkJoinPool}). Attempts to invoke in other contexts result
829 +     * in exceptions or errors, possibly including ClassCastException.
830 +     */
831 +    public final void quietlyHelpJoin() {
832 +        if (status >= 0) {
833 +            ForkJoinWorkerThread w =
834 +                (ForkJoinWorkerThread) Thread.currentThread();
835 +            if (!w.unpushTask(this) || !tryQuietlyInvoke())
836 +                busyJoin(w);
837 +        }
838 +    }
839 +
840 +    /**
841 +     * Joins this task, without returning its result or throwing an
842 +     * exception. This method may be useful when processing
843 +     * collections of tasks when some have been cancelled or otherwise
844 +     * known to have aborted.
845 +     */
846 +    public final void quietlyJoin() {
847 +        if (status >= 0) {
848 +            ForkJoinWorkerThread w = getWorker();
849 +            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
850 +                awaitDone(w, true);
851 +        }
852 +    }
853 +
854 +    /**
855 +     * Commences performing this task and awaits its completion if
856 +     * necessary, without returning its result or throwing an
857 +     * exception. This method may be useful when processing
858 +     * collections of tasks when some have been cancelled or otherwise
859 +     * known to have aborted.
860 +     */
861 +    public final void quietlyInvoke() {
862 +        if (status >= 0 && !tryQuietlyInvoke())
863 +            quietlyJoin();
864 +    }
865 +
866 +    /**
867 +     * Possibly executes tasks until the pool hosting the current task
868 +     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
869 +     * designs in which many tasks are forked, but none are explicitly
870 +     * joined, instead executing them until all are processed.  This
871 +     * method may be invoked only from within ForkJoinTask
872 +     * computations (as may be determined using method {@link
873 +     * #inForkJoinPool}). Attempts to invoke in other contexts result
874 +     * in exceptions or errors, possibly including ClassCastException.
875 +     */
876 +    public static void helpQuiesce() {
877 +        ((ForkJoinWorkerThread) Thread.currentThread())
878 +            .helpQuiescePool();
879 +    }
880 +
881      /**
882       * Resets the internal bookkeeping state of this task, allowing a
883 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
883 >     * subsequent {@code fork}. This method allows repeated reuse of
884       * this task, but only if reuse occurs when this task has either
885       * never been forked, or has been forked, then completed and all
886       * outstanding joins of this task have also completed. Effects
887       * under any other usage conditions are not guaranteed, and are
888 <     * almost surely wrong. This method may be useful when executing
888 >     * discouraged. This method may be useful when executing
889       * pre-constructed trees of subtasks in loops.
890       */
891      public void reinitialize() {
# Line 689 | Line 895 | public abstract class ForkJoinTask<V> im
895      }
896  
897      /**
898 <     * Tries to unschedule this task for execution. This method will
899 <     * typically succeed if this task is the next task that would be
900 <     * executed by the current thread, and will typically fail (return
901 <     * false) otherwise. This method may be useful when arranging
902 <     * faster local processing of tasks that could have been, but were
697 <     * not, stolen.
698 <     * @return true if unforked
898 >     * Returns the pool hosting the current task execution, or null
899 >     * if this task is executing outside of any ForkJoinPool.
900 >     *
901 >     * @see #inForkJoinPool
902 >     * @return the pool, or {@code null} if none
903       */
904 <    public boolean tryUnfork() {
905 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
904 >    public static ForkJoinPool getPool() {
905 >        Thread t = Thread.currentThread();
906 >        return (t instanceof ForkJoinWorkerThread) ?
907 >            ((ForkJoinWorkerThread) t).pool : null;
908      }
909  
910      /**
911 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
912 <     * of them or an exception is encountered. This method may be
913 <     * invoked only from within other ForkJoinTask
914 <     * computations. Attempts to invoke in other contexts result in
915 <     * exceptions or errors including ClassCastException.
710 <     * @param t1 one task
711 <     * @param t2 the other task
712 <     * @throws NullPointerException if t1 or t2 are null
713 <     * @throws RuntimeException or Error if either task did so.
911 >     * Returns {@code true} if the current thread is executing as a
912 >     * ForkJoinPool computation.
913 >     *
914 >     * @return {@code true} if the current thread is executing as a
915 >     * ForkJoinPool computation, or false otherwise
916       */
917 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
918 <        t2.fork();
717 <        t1.invoke();
718 <        t2.join();
917 >    public static boolean inForkJoinPool() {
918 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
919      }
920  
921      /**
922 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
923 <     * all of them. If any task encounters an exception, others may be
924 <     * cancelled.  This method may be invoked only from within other
925 <     * ForkJoinTask computations. Attempts to invoke in other contexts
926 <     * result in exceptions or errors including ClassCastException.
927 <     * @param tasks the array of tasks
928 <     * @throws NullPointerException if tasks or any element are null.
929 <     * @throws RuntimeException or Error if any task did so.
930 <     */
931 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
932 <        Throwable ex = null;
933 <        int last = tasks.length - 1;
734 <        for (int i = last; i >= 0; --i) {
735 <            ForkJoinTask<?> t = tasks[i];
736 <            if (t == null) {
737 <                if (ex == null)
738 <                    ex = new NullPointerException();
739 <            }
740 <            else if (i != 0)
741 <                t.fork();
742 <            else {
743 <                t.quietlyInvoke();
744 <                if (ex == null)
745 <                    ex = t.getException();
746 <            }
747 <        }
748 <        for (int i = 1; i <= last; ++i) {
749 <            ForkJoinTask<?> t = tasks[i];
750 <            if (t != null) {
751 <                if (ex != null)
752 <                    t.cancel(false);
753 <                else {
754 <                    t.quietlyJoin();
755 <                    if (ex == null)
756 <                        ex = t.getException();
757 <                }
758 <            }
759 <        }
760 <        if (ex != null)
761 <            rethrowException(ex);
762 <    }
763 <
764 <    /**
765 <     * Forks all tasks in the collection, returning when
766 <     * <tt>isDone</tt> holds for all of them. If any task encounters
767 <     * an exception, others may be cancelled.  This method may be
768 <     * invoked only from within other ForkJoinTask
769 <     * computations. Attempts to invoke in other contexts result in
770 <     * exceptions or errors including ClassCastException.
771 <     * @param tasks the collection of tasks
772 <     * @throws NullPointerException if tasks or any element are null.
773 <     * @throws RuntimeException or Error if any task did so.
922 >     * Tries to unschedule this task for execution. This method will
923 >     * typically succeed if this task is the most recently forked task
924 >     * by the current thread, and has not commenced executing in
925 >     * another thread.  This method may be useful when arranging
926 >     * alternative local processing of tasks that could have been, but
927 >     * were not, stolen. This method may be invoked only from within
928 >     * ForkJoinTask computations (as may be determined using method
929 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
930 >     * result in exceptions or errors, possibly including
931 >     * ClassCastException.
932 >     *
933 >     * @return {@code true} if unforked
934       */
935 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
936 <        if (!(tasks instanceof List)) {
937 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
778 <            return;
779 <        }
780 <        List<? extends ForkJoinTask<?>> ts =
781 <            (List<? extends ForkJoinTask<?>>)tasks;
782 <        Throwable ex = null;
783 <        int last = ts.size() - 1;
784 <        for (int i = last; i >= 0; --i) {
785 <            ForkJoinTask<?> t = ts.get(i);
786 <            if (t == null) {
787 <                if (ex == null)
788 <                    ex = new NullPointerException();
789 <            }
790 <            else if (i != 0)
791 <                t.fork();
792 <            else {
793 <                t.quietlyInvoke();
794 <                if (ex == null)
795 <                    ex = t.getException();
796 <            }
797 <        }
798 <        for (int i = 1; i <= last; ++i) {
799 <            ForkJoinTask<?> t = ts.get(i);
800 <            if (t != null) {
801 <                if (ex != null)
802 <                    t.cancel(false);
803 <                else {
804 <                    t.quietlyJoin();
805 <                    if (ex == null)
806 <                        ex = t.getException();
807 <                }
808 <            }
809 <        }
810 <        if (ex != null)
811 <            rethrowException(ex);
935 >    public boolean tryUnfork() {
936 >        return ((ForkJoinWorkerThread) Thread.currentThread())
937 >            .unpushTask(this);
938      }
939  
940      /**
941 <     * Possibly executes tasks until the pool hosting the current task
942 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
943 <     * designs in which many tasks are forked, but none are explicitly
944 <     * joined, instead executing them until all are processed.
941 >     * Returns an estimate of the number of tasks that have been
942 >     * forked by the current worker thread but not yet executed. This
943 >     * value may be useful for heuristic decisions about whether to
944 >     * fork other tasks.  This method may be invoked only from within
945 >     * ForkJoinTask computations (as may be determined using method
946 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
947 >     * result in exceptions or errors, possibly including
948 >     * ClassCastException.
949 >     * @return the number of tasks
950       */
951 <    public static void helpQuiesce() {
952 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
953 <            helpQuiescePool();
951 >    public static int getQueuedTaskCount() {
952 >        return ((ForkJoinWorkerThread) Thread.currentThread())
953 >            .getQueueSize();
954      }
955  
956      /**
957 <     * Returns a estimate of how many more locally queued tasks are
957 >     * Returns an estimate of how many more locally queued tasks are
958       * held by the current worker thread than there are other worker
959 <     * threads that might want to steal them.  This value may be
960 <     * useful for heuristic decisions about whether to fork other
961 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
962 <     * worker should aim to maintain a small constant surplus (for
963 <     * example, 3) of tasks, and to process computations locally if
964 <     * this threshold is exceeded.
959 >     * threads that might steal them.  This value may be useful for
960 >     * heuristic decisions about whether to fork other tasks. In many
961 >     * usages of ForkJoinTasks, at steady state, each worker should
962 >     * aim to maintain a small constant surplus (for example, 3) of
963 >     * tasks, and to process computations locally if this threshold is
964 >     * exceeded.  This method may be invoked only from within
965 >     * ForkJoinTask computations (as may be determined using method
966 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
967 >     * result in exceptions or errors, possibly including
968 >     * ClassCastException.  *
969       * @return the surplus number of tasks, which may be negative
970       */
971 <    public static int surplus() {
972 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
971 >    public static int getSurplusQueuedTaskCount() {
972 >        return ((ForkJoinWorkerThread) Thread.currentThread())
973              .getEstimatedSurplusTaskCount();
974      }
975  
976 <    // Extension kit
976 >    // Extension methods
977  
978      /**
979 <     * Returns the result that would be returned by <tt>join</tt>, or
980 <     * null if this task is not known to have been completed.  This
981 <     * method is designed to aid debugging, as well as to support
982 <     * extensions. Its use in any other context is discouraged.
979 >     * Returns the result that would be returned by {@link #join}, even
980 >     * if this task completed abnormally, or {@code null} if this task
981 >     * is not known to have been completed.  This method is designed
982 >     * to aid debugging, as well as to support extensions. Its use in
983 >     * any other context is discouraged.
984       *
985 <     * @return the result, or null if not completed.
985 >     * @return the result, or {@code null} if not completed
986       */
987      public abstract V getRawResult();
988  
# Line 865 | Line 1001 | public abstract class ForkJoinTask<V> im
1001       * called otherwise. The return value controls whether this task
1002       * is considered to be done normally. It may return false in
1003       * asynchronous actions that require explicit invocations of
1004 <     * <tt>complete</tt> to become joinable. It may throw exceptions
1004 >     * {@link #complete} to become joinable. It may throw exceptions
1005       * to indicate abnormal exit.
1006 <     * @return true if completed normally
1006 >     *
1007 >     * @return {@code true} if completed normally
1008       * @throws Error or RuntimeException if encountered during computation
1009       */
1010      protected abstract boolean exec();
1011  
1012 +    /**
1013 +     * Returns, but does not unschedule or execute, a task queued by
1014 +     * the current thread but not yet executed, if one is immediately
1015 +     * available. There is no guarantee that this task will actually
1016 +     * be polled or executed next. Conversely, this method may return
1017 +     * null even if a task exists but cannot be accessed without
1018 +     * contention with other threads.  This method is designed
1019 +     * primarily to support extensions, and is unlikely to be useful
1020 +     * otherwise.  This method may be invoked only from within
1021 +     * ForkJoinTask computations (as may be determined using method
1022 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1023 +     * result in exceptions or errors, possibly including
1024 +     * ClassCastException.
1025 +     *
1026 +     * @return the next task, or {@code null} if none are available
1027 +     */
1028 +    protected static ForkJoinTask<?> peekNextLocalTask() {
1029 +        return ((ForkJoinWorkerThread) Thread.currentThread())
1030 +            .peekTask();
1031 +    }
1032 +
1033 +    /**
1034 +     * Unschedules and returns, without executing, the next task
1035 +     * queued by the current thread but not yet executed.  This method
1036 +     * is designed primarily to support extensions, and is unlikely to
1037 +     * be useful otherwise.  This method may be invoked only from
1038 +     * within ForkJoinTask computations (as may be determined using
1039 +     * method {@link #inForkJoinPool}). Attempts to invoke in other
1040 +     * contexts result in exceptions or errors, possibly including
1041 +     * ClassCastException.
1042 +     *
1043 +     * @return the next task, or {@code null} if none are available
1044 +     */
1045 +    protected static ForkJoinTask<?> pollNextLocalTask() {
1046 +        return ((ForkJoinWorkerThread) Thread.currentThread())
1047 +            .pollLocalTask();
1048 +    }
1049 +
1050 +    /**
1051 +     * Unschedules and returns, without executing, the next task
1052 +     * queued by the current thread but not yet executed, if one is
1053 +     * available, or if not available, a task that was forked by some
1054 +     * other thread, if available. Availability may be transient, so a
1055 +     * {@code null} result does not necessarily imply quiescence
1056 +     * of the pool this task is operating in.  This method is designed
1057 +     * primarily to support extensions, and is unlikely to be useful
1058 +     * otherwise.  This method may be invoked only from within
1059 +     * ForkJoinTask computations (as may be determined using method
1060 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1061 +     * result in exceptions or errors, possibly including
1062 +     * ClassCastException.
1063 +     *
1064 +     * @return a task, or {@code null} if none are available
1065 +     */
1066 +    protected static ForkJoinTask<?> pollTask() {
1067 +        return ((ForkJoinWorkerThread) Thread.currentThread())
1068 +            .pollTask();
1069 +    }
1070 +
1071 +    /**
1072 +     * Adaptor for Runnables. This implements RunnableFuture
1073 +     * to be compliant with AbstractExecutorService constraints
1074 +     * when used in ForkJoinPool.
1075 +     */
1076 +    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1077 +        implements RunnableFuture<T> {
1078 +        final Runnable runnable;
1079 +        final T resultOnCompletion;
1080 +        T result;
1081 +        AdaptedRunnable(Runnable runnable, T result) {
1082 +            if (runnable == null) throw new NullPointerException();
1083 +            this.runnable = runnable;
1084 +            this.resultOnCompletion = result;
1085 +        }
1086 +        public T getRawResult() { return result; }
1087 +        public void setRawResult(T v) { result = v; }
1088 +        public boolean exec() {
1089 +            runnable.run();
1090 +            result = resultOnCompletion;
1091 +            return true;
1092 +        }
1093 +        public void run() { invoke(); }
1094 +        private static final long serialVersionUID = 5232453952276885070L;
1095 +    }
1096 +
1097 +    /**
1098 +     * Adaptor for Callables
1099 +     */
1100 +    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1101 +        implements RunnableFuture<T> {
1102 +        final Callable<? extends T> callable;
1103 +        T result;
1104 +        AdaptedCallable(Callable<? extends T> callable) {
1105 +            if (callable == null) throw new NullPointerException();
1106 +            this.callable = callable;
1107 +        }
1108 +        public T getRawResult() { return result; }
1109 +        public void setRawResult(T v) { result = v; }
1110 +        public boolean exec() {
1111 +            try {
1112 +                result = callable.call();
1113 +                return true;
1114 +            } catch (Error err) {
1115 +                throw err;
1116 +            } catch (RuntimeException rex) {
1117 +                throw rex;
1118 +            } catch (Exception ex) {
1119 +                throw new RuntimeException(ex);
1120 +            }
1121 +        }
1122 +        public void run() { invoke(); }
1123 +        private static final long serialVersionUID = 2838392045355241008L;
1124 +    }
1125 +
1126 +    /**
1127 +     * Returns a new ForkJoinTask that performs the {@code run}
1128 +     * method of the given Runnable as its action, and returns a null
1129 +     * result upon {@code join}.
1130 +     *
1131 +     * @param runnable the runnable action
1132 +     * @return the task
1133 +     */
1134 +    public static ForkJoinTask<?> adapt(Runnable runnable) {
1135 +        return new AdaptedRunnable<Void>(runnable, null);
1136 +    }
1137 +
1138 +    /**
1139 +     * Returns a new ForkJoinTask that performs the {@code run}
1140 +     * method of the given Runnable as its action, and returns the
1141 +     * given result upon {@code join}.
1142 +     *
1143 +     * @param runnable the runnable action
1144 +     * @param result the result upon completion
1145 +     * @return the task
1146 +     */
1147 +    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1148 +        return new AdaptedRunnable<T>(runnable, result);
1149 +    }
1150 +
1151 +    /**
1152 +     * Returns a new ForkJoinTask that performs the {@code call}
1153 +     * method of the given Callable as its action, and returns its
1154 +     * result upon {@code join}, translating any checked
1155 +     * exceptions encountered into {@code RuntimeException}.
1156 +     *
1157 +     * @param callable the callable action
1158 +     * @return the task
1159 +     */
1160 +    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1161 +        return new AdaptedCallable<T>(callable);
1162 +    }
1163 +
1164      // Serialization support
1165  
1166      private static final long serialVersionUID = -7721805057305804111L;
# Line 880 | Line 1169 | public abstract class ForkJoinTask<V> im
1169       * Save the state to a stream.
1170       *
1171       * @serialData the current run status and the exception thrown
1172 <     * during execution, or null if none.
1172 >     * during execution, or {@code null} if none
1173       * @param s the stream
1174       */
1175      private void writeObject(java.io.ObjectOutputStream s)
# Line 891 | Line 1180 | public abstract class ForkJoinTask<V> im
1180  
1181      /**
1182       * Reconstitute the instance from a stream.
1183 +     *
1184       * @param s the stream
1185       */
1186      private void readObject(java.io.ObjectInputStream s)
1187          throws java.io.IOException, ClassNotFoundException {
1188          s.defaultReadObject();
1189 <        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1189 >        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1190 >        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1191          Object ex = s.readObject();
1192          if (ex != null)
1193 <            setDoneExceptionally((Throwable)ex);
1193 >            setDoneExceptionally((Throwable) ex);
1194      }
1195  
1196 <    // Temporary Unsafe mechanics for preliminary release
1196 >    // Unsafe mechanics
1197  
1198 <    static final Unsafe _unsafe;
1199 <    static final long statusOffset;
1198 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1199 >    private static final long statusOffset =
1200 >        objectFieldOffset("status", ForkJoinTask.class);
1201  
1202 <    static {
1202 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1203          try {
1204 <            if (ForkJoinTask.class.getClassLoader() != null) {
1205 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1206 <                f.setAccessible(true);
1207 <                _unsafe = (Unsafe)f.get(null);
1208 <            }
1209 <            else
1210 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
920 <                (ForkJoinTask.class.getDeclaredField("status"));
921 <        } catch (Exception ex) { throw new Error(ex); }
1204 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1205 >        } catch (NoSuchFieldException e) {
1206 >            // Convert Exception to corresponding Error
1207 >            NoSuchFieldError error = new NoSuchFieldError(field);
1208 >            error.initCause(e);
1209 >            throw error;
1210 >        }
1211      }
1212  
1213 +    /**
1214 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1215 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1216 +     * into a jdk.
1217 +     *
1218 +     * @return a sun.misc.Unsafe
1219 +     */
1220 +    private static sun.misc.Unsafe getUnsafe() {
1221 +        try {
1222 +            return sun.misc.Unsafe.getUnsafe();
1223 +        } catch (SecurityException se) {
1224 +            try {
1225 +                return java.security.AccessController.doPrivileged
1226 +                    (new java.security
1227 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1228 +                        public sun.misc.Unsafe run() throws Exception {
1229 +                            java.lang.reflect.Field f = sun.misc
1230 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1231 +                            f.setAccessible(true);
1232 +                            return (sun.misc.Unsafe) f.get(null);
1233 +                        }});
1234 +            } catch (java.security.PrivilegedActionException e) {
1235 +                throw new RuntimeException("Could not initialize intrinsics",
1236 +                                           e.getCause());
1237 +            }
1238 +        }
1239 +    }
1240   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines