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.16 by jsr166, Fri Jul 24 23:47:01 2009 UTC

# Line 9 | Line 9 | import java.io.Serializable;
9   import java.util.*;
10   import java.util.concurrent.*;
11   import java.util.concurrent.atomic.*;
12 import sun.misc.Unsafe;
13 import java.lang.reflect.*;
12  
13   /**
14 < * Abstract base class for tasks that run within a ForkJoinPool.  A
15 < * ForkJoinTask is a thread-like entity that is much lighter weight
16 < * than a normal thread.  Huge numbers of tasks and subtasks may be
17 < * hosted by a small number of actual threads in a ForkJoinPool,
18 < * at the price of some usage limitations.
14 > * Abstract base class for tasks that run within a {@link
15 > * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
16 > * lighter weight than a normal thread.  Huge numbers of tasks and
17 > * subtasks may be hosted by a small number of actual threads in a
18 > * ForkJoinPool, at the price of some usage limitations.
19   *
20 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
21 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
22 < * set of restrictions (that are only partially statically
23 < * enforceable) reflecting their intended use as computational tasks
24 < * calculating pure functions or operating on purely isolated objects.
25 < * The primary coordination mechanisms supported for ForkJoinTasks are
26 < * <tt>fork</tt>, that arranges asynchronous execution, and
27 < * <tt>join</tt>, that doesn't proceed until the task's result has
28 < * been computed. (Cancellation is also supported).  The computation
29 < * defined in the <tt>compute</tt> method should avoid
30 < * <tt>synchronized</tt> methods or blocks, and should minimize
31 < * blocking synchronization apart from joining other tasks or using
20 > * <p> A "main" ForkJoinTask begins execution when submitted to a
21 > * {@link ForkJoinPool}. Once started, it will usually in turn start
22 > * other subtasks.  As indicated by the name of this class, many
23 > * programs using ForkJoinTasks employ only methods {@code fork}
24 > * and {@code join}, or derivatives such as
25 > * {@code invokeAll}.  However, this class also provides a number
26 > * of other methods that can come into play in advanced usages, as
27 > * well as extension mechanics that allow support of new forms of
28 > * fork/join processing.
29 > *
30 > * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
31 > * efficiency of ForkJoinTasks stems from a set of restrictions (that
32 > * are only partially statically enforceable) reflecting their
33 > * intended use as computational tasks calculating pure functions or
34 > * operating on purely isolated objects.  The primary coordination
35 > * mechanisms are {@link #fork}, that arranges asynchronous execution,
36 > * and {@link #join}, that doesn't proceed until the task's result has
37 > * been computed.  Computations should avoid {@code synchronized}
38 > * methods or blocks, and should minimize other blocking
39 > * synchronization apart from joining other tasks or using
40   * synchronizers such as Phasers that are advertised to cooperate with
41   * fork/join scheduling. Tasks should also not perform blocking IO,
42   * and should ideally access variables that are completely independent
# Line 38 | Line 44 | import java.lang.reflect.*;
44   * restrictions, for example using shared output streams, may be
45   * tolerable in practice, but frequent use may result in poor
46   * performance, and the potential to indefinitely stall if the number
47 < * of threads not waiting for external synchronization becomes
48 < * exhausted. This usage restriction is in part enforced by not
49 < * permitting checked exceptions such as IOExceptions to be
50 < * thrown. However, computations may still encounter unchecked
47 > * of threads not waiting for IO or other external synchronization
48 > * becomes exhausted. This usage restriction is in part enforced by
49 > * not permitting checked exceptions such as {@code IOExceptions}
50 > * to be thrown. However, computations may still encounter unchecked
51   * exceptions, that are rethrown to callers attempting join
52   * them. These exceptions may additionally include
53   * RejectedExecutionExceptions stemming from internal resource
54   * exhaustion such as failure to allocate internal task queues.
55   *
56 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
57 < * subclassed.  Instead, you subclass one of the abstract classes that
58 < * support different styles of fork/join processing.  Normally, a
59 < * concrete ForkJoinTask subclass declares fields comprising its
60 < * parameters, established in a constructor, and then defines a
61 < * <tt>compute</tt> method that somehow uses the control methods
62 < * supplied by this base class. While these methods have
63 < * <tt>public</tt> access, some of them may only be called from within
64 < * other ForkJoinTasks. Attempts to invoke them in other contexts
65 < * result in exceptions or errors including ClassCastException.  The
66 < * only way to invoke a "main" driver task is to submit it to a
67 < * ForkJoinPool. Once started, this will usually in turn start other
68 < * subtasks.
56 > * <p>The primary method for awaiting completion and extracting
57 > * results of a task is {@link #join}, but there are several variants:
58 > * The {@link Future#get} methods support interruptible and/or timed
59 > * waits for completion and report results using {@code Future}
60 > * conventions. Method {@link #helpJoin} enables callers to actively
61 > * execute other tasks while awaiting joins, which is sometimes more
62 > * efficient but only applies when all subtasks are known to be
63 > * strictly tree-structured. Method {@link #invoke} is semantically
64 > * equivalent to {@code fork(); join()} but always attempts to
65 > * begin execution in the current thread. The "<em>quiet</em>" forms
66 > * of these methods do not extract results or report exceptions. These
67 > * may be useful when a set of tasks are being executed, and you need
68 > * to delay processing of results or exceptions until all complete.
69 > * Method {@code invokeAll} (available in multiple versions)
70 > * performs the most common form of parallel invocation: forking a set
71 > * of tasks and joining them all.
72 > *
73 > * <p> The ForkJoinTask class is not usually directly subclassed.
74 > * Instead, you subclass one of the abstract classes that support a
75 > * particular style of fork/join processing.  Normally, a concrete
76 > * ForkJoinTask subclass declares fields comprising its parameters,
77 > * established in a constructor, and then defines a {@code compute}
78 > * method that somehow uses the control methods supplied by this base
79 > * class. While these methods have {@code public} access (to allow
80 > * instances of different task subclasses to call each others
81 > * methods), some of them may only be called from within other
82 > * ForkJoinTasks (as may be determined using method {@link
83 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
84 > * result in exceptions or errors, possibly including
85 > * ClassCastException.
86   *
87 < * <p>Most base support methods are <tt>final</tt> because their
87 > * <p>Most base support methods are {@code final} because their
88   * implementations are intrinsically tied to the underlying
89   * lightweight task scheduling framework, and so cannot be overridden.
90   * Developers creating new basic styles of fork/join processing should
91 < * minimally implement protected methods <tt>exec</tt>,
92 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
93 < * introducing an abstract computational method that can be
94 < * implemented in its subclasses. To support such extensions,
95 < * instances of ForkJoinTasks maintain an atomically updated
96 < * <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.
91 > * minimally implement {@code protected} methods
92 > * {@code exec}, {@code setRawResult}, and
93 > * {@code getRawResult}, while also introducing an abstract
94 > * computational method that can be implemented in its subclasses,
95 > * possibly relying on other {@code protected} methods provided
96 > * by this class.
97   *
98   * <p>ForkJoinTasks should perform relatively small amounts of
99 < * computations, othewise splitting into smaller tasks. As a very
99 > * computations, otherwise splitting into smaller tasks. As a very
100   * rough rule of thumb, a task should perform more than 100 and less
101   * than 10000 basic computational steps. If tasks are too big, then
102 < * parellelism cannot improve throughput. If too small, then memory
102 > * parallelism cannot improve throughput. If too small, then memory
103   * and internal task maintenance overhead may overwhelm processing.
104   *
105 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
106 < * be used in extensions such as remote execution frameworks. However,
107 < * it is in general safe to serialize tasks only before or after, but
105 > * <p>ForkJoinTasks are {@code Serializable}, which enables them
106 > * to be used in extensions such as remote execution frameworks. It is
107 > * in general sensible to serialize tasks only before or after, but
108   * not during execution. Serialization is not relied on during
109   * execution itself.
110 + *
111 + * @since 1.7
112 + * @author Doug Lea
113   */
114   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
115 +
116      /**
117 <     * Status field holding all run status. We pack this into a single
118 <     * int both to minimize footprint overhead and to ensure atomicity
119 <     * (updates are via CAS).
98 <     *
99 <     * Status is initially zero, and takes on nonnegative values until
117 >     * Run control status bits packed into a single int to minimize
118 >     * footprint and to ensure atomicity (via CAS).  Status is
119 >     * initially zero, and takes on nonnegative values until
120       * completed, upon which status holds COMPLETED. CANCELLED, or
121       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
122       * blocking waits by other threads have SIGNAL_MASK bits set --
# Line 111 | Line 131 | public abstract class ForkJoinTask<V> im
131       * currently unused. Also value 0x80000000 is available as spare
132       * completion value.
133       */
134 <    volatile int status; // accessed directy by pool and workers
134 >    volatile int status; // accessed directly by pool and workers
135  
136      static final int COMPLETION_MASK      = 0xe0000000;
137      static final int NORMAL               = 0xe0000000; // == mask
# Line 124 | Line 144 | public abstract class ForkJoinTask<V> im
144      /**
145       * Table of exceptions thrown by tasks, to enable reporting by
146       * callers. Because exceptions are rare, we don't directly keep
147 <     * them with task objects, but instead us a weak ref table.  Note
147 >     * them with task objects, but instead use a weak ref table.  Note
148       * that cancellation exceptions don't appear in the table, but are
149       * instead recorded as status values.
150 <     * Todo: Use ConcurrentReferenceHashMap
150 >     * TODO: Use ConcurrentReferenceHashMap
151       */
152      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
153          Collections.synchronizedMap
# Line 136 | Line 156 | public abstract class ForkJoinTask<V> im
156      // within-package utilities
157  
158      /**
159 <     * Get current worker thread, or null if not a worker thread
159 >     * Gets current worker thread, or null if not a worker thread.
160       */
161      static ForkJoinWorkerThread getWorker() {
162          Thread t = Thread.currentThread();
163 <        return ((t instanceof ForkJoinWorkerThread)?
164 <                (ForkJoinWorkerThread)t : null);
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);
163 >        return ((t instanceof ForkJoinWorkerThread) ?
164 >                (ForkJoinWorkerThread) t : null);
165      }
166  
167      final boolean casStatus(int cmp, int val) {
168 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
168 >        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
169      }
170  
171      /**
# Line 162 | Line 173 | public abstract class ForkJoinTask<V> im
173       */
174      static void rethrowException(Throwable ex) {
175          if (ex != null)
176 <            _unsafe.throwException(ex);
176 >            UNSAFE.throwException(ex);
177      }
178  
179      // Setting completion status
180  
181      /**
182 <     * Mark completion and wake up threads waiting to join this task.
182 >     * Marks completion and wakes up threads waiting to join this task.
183 >     *
184       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
185       */
186      final void setCompletion(int completion) {
187 <        ForkJoinPool pool = getWorkerPool();
187 >        ForkJoinPool pool = getPool();
188          if (pool != null) {
189              int s; // Clear signal bits while setting completion status
190 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
190 >            do {} while ((s = status) >= 0 && !casStatus(s, completion));
191  
192              if ((s & SIGNAL_MASK) != 0) {
193                  if ((s &= INTERNAL_SIGNAL_MASK) != 0)
194                      pool.updateRunningCount(s);
195 <                synchronized(this) { notifyAll(); }
195 >                synchronized (this) { notifyAll(); }
196              }
197          }
198          else
# Line 193 | Line 205 | public abstract class ForkJoinTask<V> im
205       */
206      private void externallySetCompletion(int completion) {
207          int s;
208 <        do;while ((s = status) >= 0 &&
209 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
210 <        synchronized(this) { notifyAll(); }
208 >        do {} while ((s = status) >= 0 &&
209 >                     !casStatus(s, (s & SIGNAL_MASK) | completion));
210 >        synchronized (this) { notifyAll(); }
211      }
212  
213      /**
214 <     * Sets status to indicate normal completion
214 >     * Sets status to indicate normal completion.
215       */
216      final void setNormalCompletion() {
217          // Try typical fast case -- single CAS, no signal, not already done.
218          // Manually expand casStatus to improve chances of inlining it
219 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
219 >        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
220              setCompletion(NORMAL);
221      }
222  
223      // internal waiting and notification
224  
225      /**
226 <     * Performs the actual monitor wait for awaitDone
226 >     * Performs the actual monitor wait for awaitDone.
227       */
228      private void doAwaitDone() {
229          // Minimize lock bias and in/de-flation effects by maximizing
230          // chances of waiting inside sync
231          try {
232              while (status >= 0)
233 <                synchronized(this) { if (status >= 0) wait(); }
233 >                synchronized (this) { if (status >= 0) wait(); }
234          } catch (InterruptedException ie) {
235              onInterruptedWait();
236          }
237      }
238  
239      /**
240 <     * Performs the actual monitor wait for awaitDone
240 >     * Performs the actual timed monitor wait for awaitDone.
241       */
242      private void doAwaitDone(long startTime, long nanos) {
243 <        synchronized(this) {
243 >        synchronized (this) {
244              try {
245                  while (status >= 0) {
246                      long nt = nanos - System.nanoTime() - startTime;
247                      if (nt <= 0)
248                          break;
249 <                    wait(nt / 1000000, (int)(nt % 1000000));
249 >                    wait(nt / 1000000, (int) (nt % 1000000));
250                  }
251              } catch (InterruptedException ie) {
252                  onInterruptedWait();
# Line 247 | Line 259 | public abstract class ForkJoinTask<V> im
259      /**
260       * Sets status to indicate there is joiner, then waits for join,
261       * surrounded with pool notifications.
262 +     *
263       * @return status upon exit
264       */
265 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
266 <        ForkJoinPool pool = w == null? null : w.pool;
265 >    private int awaitDone(ForkJoinWorkerThread w,
266 >                          boolean maintainParallelism) {
267 >        ForkJoinPool pool = (w == null) ? null : w.pool;
268          int s;
269          while ((s = status) >= 0) {
270 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
270 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
271                  if (pool == null || !pool.preJoin(this, maintainParallelism))
272                      doAwaitDone();
273                  if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
# Line 266 | Line 280 | public abstract class ForkJoinTask<V> im
280  
281      /**
282       * Timed version of awaitDone
283 +     *
284       * @return status upon exit
285       */
286 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
287 <        ForkJoinPool pool = w == null? null : w.pool;
286 >    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
287 >        ForkJoinPool pool = (w == null) ? null : w.pool;
288          int s;
289          while ((s = status) >= 0) {
290 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
290 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
291                  long startTime = System.nanoTime();
292                  if (pool == null || !pool.preJoin(this, false))
293                      doAwaitDone(startTime, nanos);
# Line 289 | Line 304 | public abstract class ForkJoinTask<V> im
304      }
305  
306      /**
307 <     * Notify pool that thread is unblocked. Called by signalled
307 >     * Notifies pool that thread is unblocked. Called by signalled
308       * threads when woken by non-FJ threads (which is atypical).
309       */
310      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
311          int s;
312 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
312 >        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
313          if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
314              pool.updateRunningCount(s);
315      }
316  
317      /**
318 <     * Notify pool to adjust counts on cancelled or timed out wait
318 >     * Notifies pool to adjust counts on cancelled or timed out wait.
319       */
320      private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
321          if (pool != null) {
# Line 314 | Line 329 | public abstract class ForkJoinTask<V> im
329          }
330      }
331  
332 +    /**
333 +     * Handles interruptions during waits.
334 +     */
335      private void onInterruptedWait() {
336 <        Thread t = Thread.currentThread();
337 <        if (t instanceof ForkJoinWorkerThread) {
338 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
339 <            if (w.isTerminating())
340 <                cancelIgnoreExceptions();
341 <        }
324 <        else { // re-interrupt
325 <            try {
326 <                t.interrupt();
327 <            } catch (SecurityException ignore) {
328 <            }
329 <        }
336 >        ForkJoinWorkerThread w = getWorker();
337 >        if (w == null)
338 >            Thread.currentThread().interrupt(); // re-interrupt
339 >        else if (w.isTerminating())
340 >            cancelIgnoringExceptions();
341 >        // else if FJworker, ignore interrupt
342      }
343  
344      // Recording and reporting exceptions
# Line 337 | Line 349 | public abstract class ForkJoinTask<V> im
349      }
350  
351      /**
352 <     * Throws the exception associated with status s;
352 >     * Throws the exception associated with status s.
353 >     *
354       * @throws the exception
355       */
356      private void reportException(int s) {
# Line 350 | Line 363 | public abstract class ForkJoinTask<V> im
363      }
364  
365      /**
366 <     * Returns result or throws exception using j.u.c.Future conventions
367 <     * Only call when isDone known to be true.
366 >     * Returns result or throws exception using j.u.c.Future conventions.
367 >     * Only call when {@code isDone} known to be true.
368       */
369      private V reportFutureResult()
370          throws ExecutionException, InterruptedException {
# Line 370 | Line 383 | public abstract class ForkJoinTask<V> im
383  
384      /**
385       * Returns result or throws exception using j.u.c.Future conventions
386 <     * with timeouts
386 >     * with timeouts.
387       */
388      private V reportTimedFutureResult()
389          throws InterruptedException, ExecutionException, TimeoutException {
# Line 391 | Line 404 | public abstract class ForkJoinTask<V> im
404  
405      /**
406       * Calls exec, recording completion, and rethrowing exception if
407 <     * encountered. Caller should normally check status before calling
407 >     * encountered. Caller should normally check status before calling.
408 >     *
409       * @return true if completed normally
410       */
411      private boolean tryExec() {
# Line 409 | Line 423 | public abstract class ForkJoinTask<V> im
423  
424      /**
425       * Main execution method used by worker threads. Invokes
426 <     * base computation unless already complete
426 >     * base computation unless already complete.
427       */
428      final void quietlyExec() {
429          if (status >= 0) {
430              try {
431                  if (!exec())
432                      return;
433 <            } catch(Throwable rex) {
433 >            } catch (Throwable rex) {
434                  setDoneExceptionally(rex);
435                  return;
436              }
# Line 425 | Line 439 | public abstract class ForkJoinTask<V> im
439      }
440  
441      /**
442 <     * Calls exec, recording but not rethrowing exception
443 <     * Caller should normally check status before calling
442 >     * Calls exec(), recording but not rethrowing exception.
443 >     * Caller should normally check status before calling.
444 >     *
445       * @return true if completed normally
446       */
447      private boolean tryQuietlyInvoke() {
# Line 442 | Line 457 | public abstract class ForkJoinTask<V> im
457      }
458  
459      /**
460 <     * Cancel, ignoring any exceptions it throws
460 >     * Cancels, ignoring any exceptions it throws.
461       */
462 <    final void cancelIgnoreExceptions() {
462 >    final void cancelIgnoringExceptions() {
463          try {
464              cancel(false);
465 <        } catch(Throwable ignore) {
465 >        } catch (Throwable ignore) {
466          }
467      }
468  
469 +    /**
470 +     * Main implementation of helpJoin
471 +     */
472 +    private int busyJoin(ForkJoinWorkerThread w) {
473 +        int s;
474 +        ForkJoinTask<?> t;
475 +        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
476 +            t.quietlyExec();
477 +        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
478 +    }
479 +
480      // public methods
481  
482      /**
483       * Arranges to asynchronously execute this task.  While it is not
484       * necessarily enforced, it is a usage error to fork a task more
485       * than once unless it has completed and been reinitialized.  This
486 <     * method may be invoked only from within other ForkJoinTask
487 <     * computations. Attempts to invoke in other contexts result in
488 <     * exceptions or errors including ClassCastException.
486 >     * method may be invoked only from within ForkJoinTask
487 >     * computations (as may be determined using method {@link
488 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
489 >     * in exceptions or errors, possibly including ClassCastException.
490       */
491      public final void fork() {
492 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
492 >        ((ForkJoinWorkerThread) Thread.currentThread())
493 >            .pushTask(this);
494      }
495  
496      /**
497       * Returns the result of the computation when it is ready.
498 <     * This method differs from <tt>get</tt> in that abnormal
498 >     * This method differs from {@code get} in that abnormal
499       * completion results in RuntimeExceptions or Errors, not
500       * ExecutionExceptions.
501       *
# Line 480 | Line 508 | public abstract class ForkJoinTask<V> im
508          return getRawResult();
509      }
510  
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
511      /**
512 <     * Possibly executes other tasks until this task is ready, then
513 <     * returns the result of the computation.  This method may be more
514 <     * 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.
512 >     * Commences performing this task, awaits its completion if
513 >     * necessary, and return its result.
514 >     *
515       * @throws Throwable (a RuntimeException, Error, or unchecked
516 <     * exception) if the underlying computation did so.
516 >     * exception) if the underlying computation did so
517       * @return the computed result
518       */
519      public final V invoke() {
# Line 527 | Line 524 | public abstract class ForkJoinTask<V> im
524      }
525  
526      /**
527 <     * Joins this task, without returning its result or throwing an
528 <     * exception. This method may be useful when processing
529 <     * collections of tasks when some have been cancelled or otherwise
530 <     * known to have aborted.
527 >     * Forks both tasks, returning when {@code isDone} holds for
528 >     * both of them or an exception is encountered. This method may be
529 >     * invoked only from within ForkJoinTask computations (as may be
530 >     * determined using method {@link #inForkJoinPool}). Attempts to
531 >     * invoke in other contexts result in exceptions or errors,
532 >     * possibly including ClassCastException.
533 >     *
534 >     * @param t1 one task
535 >     * @param t2 the other task
536 >     * @throws NullPointerException if t1 or t2 are null
537 >     * @throws RuntimeException or Error if either task did so
538       */
539 <    public final void quietlyJoin() {
540 <        if (status >= 0) {
541 <            ForkJoinWorkerThread w = getWorker();
542 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
539 >    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
540 >        t2.fork();
541 >        t1.invoke();
542 >        t2.join();
543      }
544  
545      /**
546 <     * Possibly executes other tasks until this task is ready.
546 >     * Forks the given tasks, returning when {@code isDone} holds
547 >     * for all of them. If any task encounters an exception, others
548 >     * may be cancelled.  This method may be invoked only from within
549 >     * ForkJoinTask computations (as may be determined using method
550 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
551 >     * result in exceptions or errors, possibly including
552 >     * ClassCastException.
553 >     *
554 >     * @param tasks the array of tasks
555 >     * @throws NullPointerException if tasks or any element are null
556 >     * @throws RuntimeException or Error if any task did so
557       */
558 <    public final void quietlyHelpJoin() {
559 <        if (status >= 0) {
560 <            ForkJoinWorkerThread w =
561 <                (ForkJoinWorkerThread)(Thread.currentThread());
562 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
563 <                w.helpJoinTask(this);
558 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
559 >        Throwable ex = null;
560 >        int last = tasks.length - 1;
561 >        for (int i = last; i >= 0; --i) {
562 >            ForkJoinTask<?> t = tasks[i];
563 >            if (t == null) {
564 >                if (ex == null)
565 >                    ex = new NullPointerException();
566 >            }
567 >            else if (i != 0)
568 >                t.fork();
569 >            else {
570 >                t.quietlyInvoke();
571 >                if (ex == null)
572 >                    ex = t.getException();
573 >            }
574          }
575 +        for (int i = 1; i <= last; ++i) {
576 +            ForkJoinTask<?> t = tasks[i];
577 +            if (t != null) {
578 +                if (ex != null)
579 +                    t.cancel(false);
580 +                else {
581 +                    t.quietlyJoin();
582 +                    if (ex == null)
583 +                        ex = t.getException();
584 +                }
585 +            }
586 +        }
587 +        if (ex != null)
588 +            rethrowException(ex);
589      }
590  
591      /**
592 <     * Performs this task and awaits its completion if necessary,
593 <     * without returning its result or throwing an exception. This
594 <     * method may be useful when processing collections of tasks when
595 <     * some have been cancelled or otherwise known to have aborted.
592 >     * Forks all tasks in the collection, returning when
593 >     * {@code isDone} holds for all of them. If any task
594 >     * encounters an exception, others may be cancelled.  This method
595 >     * may be invoked only from within ForkJoinTask computations (as
596 >     * may be determined using method {@link
597 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
598 >     * in exceptions or errors, possibly including ClassCastException.
599 >     *
600 >     * @param tasks the collection of tasks
601 >     * @throws NullPointerException if tasks or any element are null
602 >     * @throws RuntimeException or Error if any task did so
603       */
604 <    public final void quietlyInvoke() {
605 <        if (status >= 0 && !tryQuietlyInvoke())
606 <            quietlyJoin();
604 >    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
605 >        if (!(tasks instanceof List<?>)) {
606 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
607 >            return;
608 >        }
609 >        @SuppressWarnings("unchecked")
610 >        List<? extends ForkJoinTask<?>> ts =
611 >            (List<? extends ForkJoinTask<?>>) tasks;
612 >        Throwable ex = null;
613 >        int last = ts.size() - 1;
614 >        for (int i = last; i >= 0; --i) {
615 >            ForkJoinTask<?> t = ts.get(i);
616 >            if (t == null) {
617 >                if (ex == null)
618 >                    ex = new NullPointerException();
619 >            }
620 >            else if (i != 0)
621 >                t.fork();
622 >            else {
623 >                t.quietlyInvoke();
624 >                if (ex == null)
625 >                    ex = t.getException();
626 >            }
627 >        }
628 >        for (int i = 1; i <= last; ++i) {
629 >            ForkJoinTask<?> t = ts.get(i);
630 >            if (t != null) {
631 >                if (ex != null)
632 >                    t.cancel(false);
633 >                else {
634 >                    t.quietlyJoin();
635 >                    if (ex == null)
636 >                        ex = t.getException();
637 >                }
638 >            }
639 >        }
640 >        if (ex != null)
641 >            rethrowException(ex);
642      }
643  
644      /**
645       * Returns true if the computation performed by this task has
646       * completed (or has been cancelled).
647 +     *
648       * @return true if this computation has completed
649       */
650      public final boolean isDone() {
# Line 574 | Line 653 | public abstract class ForkJoinTask<V> im
653  
654      /**
655       * Returns true if this task was cancelled.
656 +     *
657       * @return true if this task was cancelled
658       */
659      public final boolean isCancelled() {
# Line 581 | Line 661 | public abstract class ForkJoinTask<V> im
661      }
662  
663      /**
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    /**
664       * Asserts that the results of this task's computation will not be
665 <     * used. If a cancellation occurs before this task is processed,
666 <     * then its <tt>compute</tt> method will not be executed,
667 <     * <tt>isCancelled</tt> will report true, and <tt>join</tt> will
668 <     * result in a CancellationException being thrown. Otherwise, when
665 >     * used. If a cancellation occurs before attempting to execute this
666 >     * task, then execution will be suppressed, {@code isCancelled}
667 >     * will report true, and {@code join} will result in a
668 >     * {@code CancellationException} being thrown. Otherwise, when
669       * cancellation races with completion, there are no guarantees
670 <     * about whether <tt>isCancelled</tt> will report true, whether
671 <     * <tt>join</tt> will return normally or via an exception, or
670 >     * about whether {@code isCancelled} will report true, whether
671 >     * {@code join} will return normally or via an exception, or
672       * whether these behaviors will remain consistent upon repeated
673       * invocation.
674       *
# Line 622 | Line 679 | public abstract class ForkJoinTask<V> im
679       * <p> This method is designed to be invoked by <em>other</em>
680       * tasks. To terminate the current task, you can just return or
681       * throw an unchecked exception from its computation method, or
682 <     * invoke <tt>completeExceptionally(someException)</tt>.
682 >     * invoke {@code completeExceptionally}.
683       *
684       * @param mayInterruptIfRunning this value is ignored in the
685       * default implementation because tasks are not in general
686 <     * cancelled via interruption.
686 >     * cancelled via interruption
687       *
688       * @return true if this task is now cancelled
689       */
# Line 636 | Line 693 | public abstract class ForkJoinTask<V> im
693      }
694  
695      /**
696 +     * Returns true if this task threw an exception or was cancelled.
697 +     *
698 +     * @return true if this task threw an exception or was cancelled
699 +     */
700 +    public final boolean isCompletedAbnormally() {
701 +        return (status & COMPLETION_MASK) < NORMAL;
702 +    }
703 +
704 +    /**
705 +     * Returns the exception thrown by the base computation, or a
706 +     * CancellationException if cancelled, or null if none or if the
707 +     * method has not yet completed.
708 +     *
709 +     * @return the exception, or null if none
710 +     */
711 +    public final Throwable getException() {
712 +        int s = status & COMPLETION_MASK;
713 +        if (s >= NORMAL)
714 +            return null;
715 +        if (s == CANCELLED)
716 +            return new CancellationException();
717 +        return exceptionMap.get(this);
718 +    }
719 +
720 +    /**
721       * Completes this task abnormally, and if not already aborted or
722       * cancelled, causes it to throw the given exception upon
723 <     * <tt>join</tt> and related operations. This method may be used
723 >     * {@code join} and related operations. This method may be used
724       * to induce exceptions in asynchronous tasks, or to force
725 <     * completion of tasks that would not otherwise complete.  This
726 <     * method is overridable, but overridden versions must invoke
727 <     * <tt>super</tt> implementation to maintain guarantees.
725 >     * completion of tasks that would not otherwise complete.  Its use
726 >     * in other situations is likely to be wrong.  This method is
727 >     * overridable, but overridden versions must invoke {@code super}
728 >     * implementation to maintain guarantees.
729 >     *
730       * @param ex the exception to throw. If this exception is
731       * not a RuntimeException or Error, the actual exception thrown
732       * will be a RuntimeException with cause ex.
733       */
734      public void completeExceptionally(Throwable ex) {
735          setDoneExceptionally((ex instanceof RuntimeException) ||
736 <                             (ex instanceof Error)? ex :
736 >                             (ex instanceof Error) ? ex :
737                               new RuntimeException(ex));
738      }
739  
740      /**
741       * Completes this task, and if not already aborted or cancelled,
742 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
742 >     * returning a {@code null} result upon {@code join} and related
743       * operations. This method may be used to provide results for
744       * asynchronous tasks, or to provide alternative handling for
745 <     * tasks that would not otherwise complete normally.
745 >     * tasks that would not otherwise complete normally. Its use in
746 >     * other situations is likely to be wrong. This method is
747 >     * overridable, but overridden versions must invoke {@code super}
748 >     * implementation to maintain guarantees.
749       *
750 <     * @param value the result value for this task.
750 >     * @param value the result value for this task
751       */
752      public void complete(V value) {
753          try {
754              setRawResult(value);
755 <        } catch(Throwable rex) {
755 >        } catch (Throwable rex) {
756              setDoneExceptionally(rex);
757              return;
758          }
759          setNormalCompletion();
760      }
761  
762 +    public final V get() throws InterruptedException, ExecutionException {
763 +        ForkJoinWorkerThread w = getWorker();
764 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
765 +            awaitDone(w, true);
766 +        return reportFutureResult();
767 +    }
768 +
769 +    public final V get(long timeout, TimeUnit unit)
770 +        throws InterruptedException, ExecutionException, TimeoutException {
771 +        ForkJoinWorkerThread w = getWorker();
772 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
773 +            awaitDone(w, unit.toNanos(timeout));
774 +        return reportTimedFutureResult();
775 +    }
776 +
777 +    /**
778 +     * Possibly executes other tasks until this task is ready, then
779 +     * returns the result of the computation.  This method may be more
780 +     * efficient than {@code join}, but is only applicable when
781 +     * there are no potential dependencies between continuation of the
782 +     * current task and that of any other task that might be executed
783 +     * while helping. (This usually holds for pure divide-and-conquer
784 +     * tasks). This method may be invoked only from within
785 +     * ForkJoinTask computations (as may be determined using method
786 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
787 +     * result in exceptions or errors, possibly including
788 +     * ClassCastException.
789 +     *
790 +     * @return the computed result
791 +     */
792 +    public final V helpJoin() {
793 +        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
794 +        if (status < 0 || !w.unpushTask(this) || !tryExec())
795 +            reportException(busyJoin(w));
796 +        return getRawResult();
797 +    }
798 +
799 +    /**
800 +     * Possibly executes other tasks until this task is ready.  This
801 +     * method may be invoked only from within ForkJoinTask
802 +     * computations (as may be determined using method {@link
803 +     * #inForkJoinPool}). Attempts to invoke in other contexts result
804 +     * in exceptions or errors, possibly including ClassCastException.
805 +     */
806 +    public final void quietlyHelpJoin() {
807 +        if (status >= 0) {
808 +            ForkJoinWorkerThread w =
809 +                (ForkJoinWorkerThread) Thread.currentThread();
810 +            if (!w.unpushTask(this) || !tryQuietlyInvoke())
811 +                busyJoin(w);
812 +        }
813 +    }
814 +
815 +    /**
816 +     * Joins this task, without returning its result or throwing an
817 +     * exception. This method may be useful when processing
818 +     * collections of tasks when some have been cancelled or otherwise
819 +     * known to have aborted.
820 +     */
821 +    public final void quietlyJoin() {
822 +        if (status >= 0) {
823 +            ForkJoinWorkerThread w = getWorker();
824 +            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
825 +                awaitDone(w, true);
826 +        }
827 +    }
828 +
829 +    /**
830 +     * Commences performing this task and awaits its completion if
831 +     * necessary, without returning its result or throwing an
832 +     * exception. This method may be useful when processing
833 +     * collections of tasks when some have been cancelled or otherwise
834 +     * known to have aborted.
835 +     */
836 +    public final void quietlyInvoke() {
837 +        if (status >= 0 && !tryQuietlyInvoke())
838 +            quietlyJoin();
839 +    }
840 +
841 +    /**
842 +     * Possibly executes tasks until the pool hosting the current task
843 +     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
844 +     * designs in which many tasks are forked, but none are explicitly
845 +     * joined, instead executing them until all are processed.
846 +     */
847 +    public static void helpQuiesce() {
848 +        ((ForkJoinWorkerThread) Thread.currentThread())
849 +            .helpQuiescePool();
850 +    }
851 +
852      /**
853       * Resets the internal bookkeeping state of this task, allowing a
854 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
854 >     * subsequent {@code fork}. This method allows repeated reuse of
855       * this task, but only if reuse occurs when this task has either
856       * never been forked, or has been forked, then completed and all
857       * outstanding joins of this task have also completed. Effects
# Line 689 | Line 866 | public abstract class ForkJoinTask<V> im
866      }
867  
868      /**
869 <     * Tries to unschedule this task for execution. This method will
870 <     * typically succeed if this task is the next task that would be
871 <     * executed by the current thread, and will typically fail (return
872 <     * false) otherwise. This method may be useful when arranging
696 <     * faster local processing of tasks that could have been, but were
697 <     * not, stolen.
698 <     * @return true if unforked
699 <     */
700 <    public boolean tryUnfork() {
701 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
702 <    }
703 <
704 <    /**
705 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
706 <     * of them or an exception is encountered. This method may be
707 <     * invoked only from within other ForkJoinTask
708 <     * computations. Attempts to invoke in other contexts result in
709 <     * 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.
869 >     * Returns the pool hosting the current task execution, or null
870 >     * if this task is executing outside of any ForkJoinPool.
871 >     *
872 >     * @return the pool, or null if none
873       */
874 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
875 <        t2.fork();
876 <        t1.invoke();
877 <        t2.join();
874 >    public static ForkJoinPool getPool() {
875 >        Thread t = Thread.currentThread();
876 >        return (t instanceof ForkJoinWorkerThread) ?
877 >            ((ForkJoinWorkerThread) t).pool : null;
878      }
879  
880      /**
881 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
882 <     * all of them. If any task encounters an exception, others may be
883 <     * cancelled.  This method may be invoked only from within other
884 <     * ForkJoinTask computations. Attempts to invoke in other contexts
885 <     * result in exceptions or errors including ClassCastException.
727 <     * @param tasks the array of tasks
728 <     * @throws NullPointerException if tasks or any element are null.
729 <     * @throws RuntimeException or Error if any task did so.
881 >     * Returns {@code true} if the current thread is executing as a
882 >     * ForkJoinPool computation.
883 >     *
884 >     * @return {@code true} if the current thread is executing as a
885 >     * ForkJoinPool computation, or false otherwise
886       */
887 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
888 <        Throwable ex = null;
733 <        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);
887 >    public static boolean inForkJoinPool() {
888 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
889      }
890  
891      /**
892 <     * Forks all tasks in the collection, returning when
893 <     * <tt>isDone</tt> holds for all of them. If any task encounters
894 <     * an exception, others may be cancelled.  This method may be
895 <     * invoked only from within other ForkJoinTask
896 <     * computations. Attempts to invoke in other contexts result in
897 <     * exceptions or errors including ClassCastException.
898 <     * @param tasks the collection of tasks
899 <     * @throws NullPointerException if tasks or any element are null.
900 <     * @throws RuntimeException or Error if any task did so.
892 >     * Tries to unschedule this task for execution. This method will
893 >     * typically succeed if this task is the most recently forked task
894 >     * by the current thread, and has not commenced executing in
895 >     * another thread.  This method may be useful when arranging
896 >     * alternative local processing of tasks that could have been, but
897 >     * were not, stolen. This method may be invoked only from within
898 >     * ForkJoinTask computations (as may be determined using method
899 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
900 >     * result in exceptions or errors, possibly including
901 >     * ClassCastException.
902 >     *
903 >     * @return true if unforked
904       */
905 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
906 <        if (!(tasks instanceof List)) {
907 <            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);
905 >    public boolean tryUnfork() {
906 >        return ((ForkJoinWorkerThread) Thread.currentThread())
907 >            .unpushTask(this);
908      }
909  
910      /**
911 <     * Possibly executes tasks until the pool hosting the current task
912 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
913 <     * designs in which many tasks are forked, but none are explicitly
914 <     * joined, instead executing them until all are processed.
911 >     * Returns an estimate of the number of tasks that have been
912 >     * forked by the current worker thread but not yet executed. This
913 >     * value may be useful for heuristic decisions about whether to
914 >     * fork other tasks.
915 >     *
916 >     * @return the number of tasks
917       */
918 <    public static void helpQuiesce() {
919 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
920 <            helpQuiescePool();
918 >    public static int getQueuedTaskCount() {
919 >        return ((ForkJoinWorkerThread) Thread.currentThread())
920 >            .getQueueSize();
921      }
922  
923      /**
924 <     * Returns a estimate of how many more locally queued tasks are
924 >     * Returns an estimate of how many more locally queued tasks are
925       * held by the current worker thread than there are other worker
926 <     * threads that might want to steal them.  This value may be
927 <     * useful for heuristic decisions about whether to fork other
928 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
929 <     * worker should aim to maintain a small constant surplus (for
930 <     * example, 3) of tasks, and to process computations locally if
931 <     * this threshold is exceeded.
926 >     * threads that might steal them.  This value may be useful for
927 >     * heuristic decisions about whether to fork other tasks. In many
928 >     * usages of ForkJoinTasks, at steady state, each worker should
929 >     * aim to maintain a small constant surplus (for example, 3) of
930 >     * tasks, and to process computations locally if this threshold is
931 >     * exceeded.
932 >     *
933       * @return the surplus number of tasks, which may be negative
934       */
935 <    public static int surplus() {
936 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
935 >    public static int getSurplusQueuedTaskCount() {
936 >        return ((ForkJoinWorkerThread) Thread.currentThread())
937              .getEstimatedSurplusTaskCount();
938      }
939  
940 <    // Extension kit
940 >    // Extension methods
941  
942      /**
943 <     * Returns the result that would be returned by <tt>join</tt>, or
944 <     * null if this task is not known to have been completed.  This
945 <     * method is designed to aid debugging, as well as to support
946 <     * extensions. Its use in any other context is discouraged.
943 >     * Returns the result that would be returned by {@code join},
944 >     * even if this task completed abnormally, or null if this task is
945 >     * not known to have been completed.  This method is designed to
946 >     * aid debugging, as well as to support extensions. Its use in any
947 >     * other context is discouraged.
948       *
949 <     * @return the result, or null if not completed.
949 >     * @return the result, or null if not completed
950       */
951      public abstract V getRawResult();
952  
# Line 865 | Line 965 | public abstract class ForkJoinTask<V> im
965       * called otherwise. The return value controls whether this task
966       * is considered to be done normally. It may return false in
967       * asynchronous actions that require explicit invocations of
968 <     * <tt>complete</tt> to become joinable. It may throw exceptions
968 >     * {@code complete} to become joinable. It may throw exceptions
969       * to indicate abnormal exit.
970 +     *
971       * @return true if completed normally
972       * @throws Error or RuntimeException if encountered during computation
973       */
974      protected abstract boolean exec();
975  
976 +    /**
977 +     * Returns, but does not unschedule or execute, the task queued by
978 +     * the current thread but not yet executed, if one is
979 +     * available. There is no guarantee that this task will actually
980 +     * be polled or executed next.  This method is designed primarily
981 +     * to support extensions, and is unlikely to be useful otherwise.
982 +     * This method may be invoked only from within ForkJoinTask
983 +     * computations (as may be determined using method {@link
984 +     * #inForkJoinPool}). Attempts to invoke in other contexts result
985 +     * in exceptions or errors, possibly including ClassCastException.
986 +     *
987 +     * @return the next task, or null if none are available
988 +     */
989 +    protected static ForkJoinTask<?> peekNextLocalTask() {
990 +        return ((ForkJoinWorkerThread) Thread.currentThread())
991 +            .peekTask();
992 +    }
993 +
994 +    /**
995 +     * Unschedules and returns, without executing, the next task
996 +     * queued by the current thread but not yet executed.  This method
997 +     * is designed primarily to support extensions, and is unlikely to
998 +     * be useful otherwise.  This method may be invoked only from
999 +     * within ForkJoinTask computations (as may be determined using
1000 +     * method {@link #inForkJoinPool}). Attempts to invoke in other
1001 +     * contexts result in exceptions or errors, possibly including
1002 +     * ClassCastException.
1003 +     *
1004 +     * @return the next task, or null if none are available
1005 +     */
1006 +    protected static ForkJoinTask<?> pollNextLocalTask() {
1007 +        return ((ForkJoinWorkerThread) Thread.currentThread())
1008 +            .pollLocalTask();
1009 +    }
1010 +
1011 +    /**
1012 +     * Unschedules and returns, without executing, the next task
1013 +     * queued by the current thread but not yet executed, if one is
1014 +     * available, or if not available, a task that was forked by some
1015 +     * other thread, if available. Availability may be transient, so a
1016 +     * {@code null} result does not necessarily imply quiescence
1017 +     * of the pool this task is operating in.  This method is designed
1018 +     * primarily to support extensions, and is unlikely to be useful
1019 +     * otherwise.  This method may be invoked only from within
1020 +     * ForkJoinTask computations (as may be determined using method
1021 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1022 +     * result in exceptions or errors, possibly including
1023 +     * ClassCastException.
1024 +     *
1025 +     * @return a task, or null if none are available
1026 +     */
1027 +    protected static ForkJoinTask<?> pollTask() {
1028 +        return ((ForkJoinWorkerThread) Thread.currentThread())
1029 +            .pollTask();
1030 +    }
1031 +
1032      // Serialization support
1033  
1034      private static final long serialVersionUID = -7721805057305804111L;
# Line 880 | Line 1037 | public abstract class ForkJoinTask<V> im
1037       * Save the state to a stream.
1038       *
1039       * @serialData the current run status and the exception thrown
1040 <     * during execution, or null if none.
1040 >     * during execution, or null if none
1041       * @param s the stream
1042       */
1043      private void writeObject(java.io.ObjectOutputStream s)
# Line 891 | Line 1048 | public abstract class ForkJoinTask<V> im
1048  
1049      /**
1050       * Reconstitute the instance from a stream.
1051 +     *
1052       * @param s the stream
1053       */
1054      private void readObject(java.io.ObjectInputStream s)
1055          throws java.io.IOException, ClassNotFoundException {
1056          s.defaultReadObject();
1057 <        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1057 >        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1058 >        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1059          Object ex = s.readObject();
1060          if (ex != null)
1061 <            setDoneExceptionally((Throwable)ex);
1061 >            setDoneExceptionally((Throwable) ex);
1062      }
1063  
1064 <    // Temporary Unsafe mechanics for preliminary release
1064 >    // Unsafe mechanics for jsr166y 3rd party package.
1065 >    private static sun.misc.Unsafe getUnsafe() {
1066 >        try {
1067 >            return sun.misc.Unsafe.getUnsafe();
1068 >        } catch (SecurityException se) {
1069 >            try {
1070 >                return java.security.AccessController.doPrivileged
1071 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1072 >                        public sun.misc.Unsafe run() throws Exception {
1073 >                            return getUnsafeByReflection();
1074 >                        }});
1075 >            } catch (java.security.PrivilegedActionException e) {
1076 >                throw new RuntimeException("Could not initialize intrinsics",
1077 >                                           e.getCause());
1078 >            }
1079 >        }
1080 >    }
1081  
1082 <    static final Unsafe _unsafe;
1083 <    static final long statusOffset;
1082 >    private static sun.misc.Unsafe getUnsafeByReflection()
1083 >            throws NoSuchFieldException, IllegalAccessException {
1084 >        java.lang.reflect.Field f =
1085 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1086 >        f.setAccessible(true);
1087 >        return (sun.misc.Unsafe) f.get(null);
1088 >    }
1089  
1090 <    static {
1090 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
1091          try {
1092 <            if (ForkJoinTask.class.getClassLoader() != null) {
1093 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1094 <                f.setAccessible(true);
1095 <                _unsafe = (Unsafe)f.get(null);
1096 <            }
1097 <            else
1098 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
920 <                (ForkJoinTask.class.getDeclaredField("status"));
921 <        } catch (Exception ex) { throw new Error(ex); }
1092 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1093 >        } catch (NoSuchFieldException e) {
1094 >            // Convert Exception to Error
1095 >            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1096 >            error.initCause(e);
1097 >            throw error;
1098 >        }
1099      }
1100  
1101 +    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1102 +    static final long statusOffset =
1103 +        fieldOffset("status", ForkJoinTask.class);
1104 +
1105   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines