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.14 by jsr166, Thu Jul 23 23:07:57 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines