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.63 by dl, Sat Sep 18 12:10:21 2010 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.io.Serializable;
9 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import sun.misc.Unsafe;
12 < import java.lang.reflect.*;
10 > import java.io.Serializable;
11 > import java.util.Collection;
12 > import java.util.Collections;
13 > import java.util.List;
14 > import java.util.RandomAccess;
15 > import java.util.Map;
16 > import java.util.WeakHashMap;
17  
18   /**
19 < * Abstract base class for tasks that run within a ForkJoinPool.  A
20 < * ForkJoinTask is a thread-like entity that is much lighter weight
21 < * than a normal thread.  Huge numbers of tasks and subtasks may be
22 < * hosted by a small number of actual threads in a ForkJoinPool,
23 < * at the price of some usage limitations.
19 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
20 > * A {@code ForkJoinTask} is a thread-like entity that is much
21 > * lighter weight than a normal thread.  Huge numbers of tasks and
22 > * subtasks may be hosted by a small number of actual threads in a
23 > * ForkJoinPool, at the price of some usage limitations.
24 > *
25 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
26 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
27 > * start other subtasks.  As indicated by the name of this class,
28 > * many programs using {@code ForkJoinTask} employ only methods
29 > * {@link #fork} and {@link #join}, or derivatives such as {@link
30 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
31 > * provides a number of other methods that can come into play in
32 > * advanced usages, as well as extension mechanics that allow
33 > * support of new forms of fork/join processing.
34   *
35 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
36 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
37 < * set of restrictions (that are only partially statically
38 < * enforceable) reflecting their intended use as computational tasks
39 < * calculating pure functions or operating on purely isolated objects.
40 < * The primary coordination mechanisms supported for ForkJoinTasks are
41 < * <tt>fork</tt>, that arranges asynchronous execution, and
42 < * <tt>join</tt>, that doesn't proceed until the task's result has
43 < * been computed. (Cancellation is also supported).  The computation
44 < * defined in the <tt>compute</tt> method should avoid
45 < * <tt>synchronized</tt> methods or blocks, and should minimize
46 < * blocking synchronization apart from joining other tasks or using
47 < * synchronizers such as Phasers that are advertised to cooperate with
48 < * fork/join scheduling. Tasks should also not perform blocking IO,
49 < * and should ideally access variables that are completely independent
50 < * of those accessed by other running tasks. Minor breaches of these
51 < * restrictions, for example using shared output streams, may be
52 < * tolerable in practice, but frequent use may result in poor
53 < * performance, and the potential to indefinitely stall if the number
54 < * of threads not waiting for external synchronization becomes
55 < * exhausted. This usage restriction is in part enforced by not
56 < * permitting checked exceptions such as IOExceptions to be
57 < * thrown. However, computations may still encounter unchecked
58 < * exceptions, that are rethrown to callers attempting join
59 < * them. These exceptions may additionally include
60 < * RejectedExecutionExceptions stemming from internal resource
48 < * exhaustion such as failure to allocate internal task queues.
35 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
36 > * The efficiency of {@code ForkJoinTask}s stems from a set of
37 > * restrictions (that are only partially statically enforceable)
38 > * reflecting their intended use as computational tasks calculating
39 > * pure functions or operating on purely isolated objects.  The
40 > * primary coordination mechanisms are {@link #fork}, that arranges
41 > * asynchronous execution, and {@link #join}, that doesn't proceed
42 > * until the task's result has been computed.  Computations should
43 > * avoid {@code synchronized} methods or blocks, and should minimize
44 > * other blocking synchronization apart from joining other tasks or
45 > * using synchronizers such as Phasers that are advertised to
46 > * cooperate with fork/join scheduling. Tasks should also not perform
47 > * blocking IO, and should ideally access variables that are
48 > * completely independent of those accessed by other running
49 > * tasks. Minor breaches of these restrictions, for example using
50 > * shared output streams, may be tolerable in practice, but frequent
51 > * use may result in poor performance, and the potential to
52 > * indefinitely stall if the number of threads not waiting for IO or
53 > * other external synchronization becomes exhausted. This usage
54 > * restriction is in part enforced by not permitting checked
55 > * exceptions such as {@code IOExceptions} to be thrown. However,
56 > * computations may still encounter unchecked exceptions, that are
57 > * rethrown to callers attempting to join them. These exceptions may
58 > * additionally include {@link RejectedExecutionException} stemming
59 > * from internal resource exhaustion, such as failure to allocate
60 > * internal task queues.
61   *
62 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
63 < * subclassed.  Instead, you subclass one of the abstract classes that
64 < * support different styles of fork/join processing.  Normally, a
65 < * concrete ForkJoinTask subclass declares fields comprising its
66 < * parameters, established in a constructor, and then defines a
67 < * <tt>compute</tt> method that somehow uses the control methods
68 < * supplied by this base class. While these methods have
69 < * <tt>public</tt> access, some of them may only be called from within
70 < * other ForkJoinTasks. Attempts to invoke them in other contexts
71 < * result in exceptions or errors including ClassCastException.  The
72 < * only way to invoke a "main" driver task is to submit it to a
73 < * ForkJoinPool. Once started, this will usually in turn start other
74 < * subtasks.
62 > * <p>The primary method for awaiting completion and extracting
63 > * results of a task is {@link #join}, but there are several variants:
64 > * The {@link Future#get} methods support interruptible and/or timed
65 > * waits for completion and report results using {@code Future}
66 > * conventions. Method {@link #invoke} is semantically
67 > * equivalent to {@code fork(); join()} but always attempts to begin
68 > * execution in the current thread. The "<em>quiet</em>" forms of
69 > * these methods do not extract results or report exceptions. These
70 > * may be useful when a set of tasks are being executed, and you need
71 > * to delay processing of results or exceptions until all complete.
72 > * Method {@code invokeAll} (available in multiple versions)
73 > * performs the most common form of parallel invocation: forking a set
74 > * of tasks and joining them all.
75   *
76 < * <p>Most base support methods are <tt>final</tt> because their
77 < * implementations are intrinsically tied to the underlying
78 < * lightweight task scheduling framework, and so cannot be overridden.
79 < * Developers creating new basic styles of fork/join processing should
80 < * minimally implement protected methods <tt>exec</tt>,
81 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
82 < * introducing an abstract computational method that can be
83 < * implemented in its subclasses. To support such extensions,
84 < * instances of ForkJoinTasks maintain an atomically updated
85 < * <tt>short</tt> representing user-defined control state.  Control
86 < * state is guaranteed initially to be zero, and to be negative upon
87 < * completion, but may otherwise be used for any other control
88 < * purposes, such as maintaining join counts.  The {@link
89 < * ForkJoinWorkerThread} class supports additional inspection and
90 < * tuning methods that can be useful when developing extensions.
76 > * <p>The execution status of tasks may be queried at several levels
77 > * of detail: {@link #isDone} is true if a task completed in any way
78 > * (including the case where a task was cancelled without executing);
79 > * {@link #isCompletedNormally} is true if a task completed without
80 > * cancellation or encountering an exception; {@link #isCancelled} is
81 > * true if the task was cancelled (in which case {@link #getException}
82 > * returns a {@link java.util.concurrent.CancellationException}); and
83 > * {@link #isCompletedAbnormally} is true if a task was either
84 > * cancelled or encountered an exception, in which case {@link
85 > * #getException} will return either the encountered exception or
86 > * {@link java.util.concurrent.CancellationException}.
87 > *
88 > * <p>The ForkJoinTask class is not usually directly subclassed.
89 > * Instead, you subclass one of the abstract classes that support a
90 > * particular style of fork/join processing, typically {@link
91 > * RecursiveAction} for computations that do not return results, or
92 > * {@link RecursiveTask} for those that do.  Normally, a concrete
93 > * ForkJoinTask subclass declares fields comprising its parameters,
94 > * established in a constructor, and then defines a {@code compute}
95 > * method that somehow uses the control methods supplied by this base
96 > * class. While these methods have {@code public} access (to allow
97 > * instances of different task subclasses to call each other's
98 > * methods), some of them may only be called from within other
99 > * ForkJoinTasks (as may be determined using method {@link
100 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
101 > * result in exceptions or errors, possibly including
102 > * {@code ClassCastException}.
103 > *
104 > * <p>Most base support methods are {@code final}, to prevent
105 > * overriding of implementations that are intrinsically tied to the
106 > * underlying lightweight task scheduling framework.  Developers
107 > * creating new basic styles of fork/join processing should minimally
108 > * implement {@code protected} methods {@link #exec}, {@link
109 > * #setRawResult}, and {@link #getRawResult}, while also introducing
110 > * an abstract computational method that can be implemented in its
111 > * subclasses, possibly relying on other {@code protected} methods
112 > * provided by this class.
113   *
114   * <p>ForkJoinTasks should perform relatively small amounts of
115 < * computations, othewise splitting into smaller tasks. As a very
116 < * rough rule of thumb, a task should perform more than 100 and less
117 < * than 10000 basic computational steps. If tasks are too big, then
118 < * parellelism cannot improve throughput. If too small, then memory
119 < * and internal task maintenance overhead may overwhelm processing.
115 > * computation. Large tasks should be split into smaller subtasks,
116 > * usually via recursive decomposition. As a very rough rule of thumb,
117 > * a task should perform more than 100 and less than 10000 basic
118 > * computational steps. If tasks are too big, then parallelism cannot
119 > * improve throughput. If too small, then memory and internal task
120 > * maintenance overhead may overwhelm processing.
121 > *
122 > * <p>This class provides {@code adapt} methods for {@link Runnable}
123 > * and {@link Callable}, that may be of use when mixing execution of
124 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
125 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
126 > *
127 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
128 > * used in extensions such as remote execution frameworks. It is
129 > * sensible to serialize tasks only before or after, but not during,
130 > * execution. Serialization is not relied on during execution itself.
131   *
132 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
133 < * be used in extensions such as remote execution frameworks. However,
89 < * it is in general safe to serialize tasks only before or after, but
90 < * not during execution. Serialization is not relied on during
91 < * execution itself.
132 > * @since 1.7
133 > * @author Doug Lea
134   */
135   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
136 <    /**
137 <     * Status field holding all run status. We pack this into a single
138 <     * int both to minimize footprint overhead and to ensure atomicity
139 <     * (updates are via CAS).
140 <     *
141 <     * Status is initially zero, and takes on nonnegative values until
142 <     * completed, upon which status holds COMPLETED. CANCELLED, or
143 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
144 <     * blocking waits by other threads have SIGNAL_MASK bits set --
145 <     * bit 15 for external (nonFJ) waits, and the rest a count of
146 <     * waiting FJ threads.  (This representation relies on
147 <     * ForkJoinPool max thread limits). Completion of a stolen task
148 <     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
149 <     * though suboptimal for some purposes, we use basic builtin
150 <     * wait/notify to take advantage of "monitor inflation" in JVMs
151 <     * that we would otherwise need to emulate to avoid adding further
152 <     * per-task bookkeeping overhead. Note that bits 16-28 are
153 <     * currently unused. Also value 0x80000000 is available as spare
154 <     * completion value.
155 <     */
156 <    volatile int status; // accessed directy by pool and workers
157 <
158 <    static final int COMPLETION_MASK      = 0xe0000000;
159 <    static final int NORMAL               = 0xe0000000; // == mask
160 <    static final int CANCELLED            = 0xc0000000;
161 <    static final int EXCEPTIONAL          = 0xa0000000;
162 <    static final int SIGNAL_MASK          = 0x0000ffff;
163 <    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
164 <    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
136 >
137 >    /*
138 >     * See the internal documentation of class ForkJoinPool for a
139 >     * general implementation overview.  ForkJoinTasks are mainly
140 >     * responsible for maintaining their "status" field amidst relays
141 >     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
142 >     * methods of this class are more-or-less layered into (1) basic
143 >     * status maintenance (2) execution and awaiting completion (3)
144 >     * user-level methods that additionally report results. This is
145 >     * sometimes hard to see because this file orders exported methods
146 >     * in a way that flows well in javadocs. In particular, most
147 >     * join mechanics are in method quietlyJoin, below.
148 >     */
149 >
150 >    /*
151 >     * The status field holds run control status bits packed into a
152 >     * single int to minimize footprint and to ensure atomicity (via
153 >     * CAS).  Status is initially zero, and takes on nonnegative
154 >     * values until completed, upon which status holds value
155 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
156 >     * waits by other threads have the SIGNAL bit set.  Completion of
157 >     * a stolen task with SIGNAL set awakens any waiters via
158 >     * notifyAll. Even though suboptimal for some purposes, we use
159 >     * basic builtin wait/notify to take advantage of "monitor
160 >     * inflation" in JVMs that we would otherwise need to emulate to
161 >     * avoid adding further per-task bookkeeping overhead.  We want
162 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
163 >     * techniques, so use some odd coding idioms that tend to avoid
164 >     * them.
165 >     */
166 >
167 >    /** The run status of this task */
168 >    volatile int status; // accessed directly by pool and workers
169 >
170 >    private static final int NORMAL      = -1;
171 >    private static final int CANCELLED   = -2;
172 >    private static final int EXCEPTIONAL = -3;
173 >    private static final int SIGNAL      =  1;
174  
175      /**
176       * Table of exceptions thrown by tasks, to enable reporting by
177       * callers. Because exceptions are rare, we don't directly keep
178 <     * them with task objects, but instead us a weak ref table.  Note
178 >     * them with task objects, but instead use a weak ref table.  Note
179       * that cancellation exceptions don't appear in the table, but are
180       * instead recorded as status values.
181 <     * Todo: Use ConcurrentReferenceHashMap
181 >     * TODO: Use ConcurrentReferenceHashMap
182       */
183      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
184          Collections.synchronizedMap
185          (new WeakHashMap<ForkJoinTask<?>, Throwable>());
186  
187 <    // within-package utilities
137 <
138 <    /**
139 <     * Get current worker thread, or null if not a worker thread
140 <     */
141 <    static ForkJoinWorkerThread getWorker() {
142 <        Thread t = Thread.currentThread();
143 <        return ((t instanceof ForkJoinWorkerThread)?
144 <                (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);
154 <    }
155 <
156 <    final boolean casStatus(int cmp, int val) {
157 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
158 <    }
187 >    // Maintaining completion status
188  
189      /**
190 <     * Workaround for not being able to rethrow unchecked exceptions.
191 <     */
192 <    static void rethrowException(Throwable ex) {
164 <        if (ex != null)
165 <            _unsafe.throwException(ex);
166 <    }
167 <
168 <    // Setting completion status
169 <
170 <    /**
171 <     * Mark completion and wake up threads waiting to join this task.
190 >     * Marks completion and wakes up threads waiting to join this task,
191 >     * also clearing signal request bits.
192 >     *
193       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
194       */
195 <    final void setCompletion(int completion) {
196 <        ForkJoinPool pool = getWorkerPool();
197 <        if (pool != null) {
198 <            int s; // Clear signal bits while setting completion status
199 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
200 <
201 <            if ((s & SIGNAL_MASK) != 0) {
181 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
182 <                    pool.updateRunningCount(s);
183 <                synchronized(this) { notifyAll(); }
195 >    private void setCompletion(int completion) {
196 >        int s;
197 >        while ((s = status) >= 0) {
198 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
199 >                if (s != 0)
200 >                    synchronized (this) { notifyAll(); }
201 >                break;
202              }
203          }
186        else
187            externallySetCompletion(completion);
188    }
189
190    /**
191     * Version of setCompletion for non-FJ threads.  Leaves signal
192     * bits for unblocked threads to adjust, and always notifies.
193     */
194    private void externallySetCompletion(int completion) {
195        int s;
196        do;while ((s = status) >= 0 &&
197                  !casStatus(s, (s & SIGNAL_MASK) | completion));
198        synchronized(this) { notifyAll(); }
204      }
205  
206      /**
207 <     * Sets status to indicate normal completion
208 <     */
209 <    final void setNormalCompletion() {
205 <        // Try typical fast case -- single CAS, no signal, not already done.
206 <        // Manually expand casStatus to improve chances of inlining it
207 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
208 <            setCompletion(NORMAL);
209 <    }
210 <
211 <    // internal waiting and notification
212 <
213 <    /**
214 <     * Performs the actual monitor wait for awaitDone
207 >     * Records exception and sets exceptional completion.
208 >     *
209 >     * @return status on exit
210       */
211 <    private void doAwaitDone() {
212 <        // Minimize lock bias and in/de-flation effects by maximizing
213 <        // chances of waiting inside sync
219 <        try {
220 <            while (status >= 0)
221 <                synchronized(this) { if (status >= 0) wait(); }
222 <        } catch (InterruptedException ie) {
223 <            onInterruptedWait();
224 <        }
211 >    private void setExceptionalCompletion(Throwable rex) {
212 >        exceptionMap.put(this, rex);
213 >        setCompletion(EXCEPTIONAL);
214      }
215  
216      /**
217 <     * Performs the actual monitor wait for awaitDone
217 >     * Blocks a worker thread until completion. Called only by
218 >     * pool. Currently unused -- pool-based waits use timeout
219 >     * version below.
220       */
221 <    private void doAwaitDone(long startTime, long nanos) {
222 <        synchronized(this) {
221 >    final void internalAwaitDone() {
222 >        int s;         // the odd construction reduces lock bias effects
223 >        while ((s = status) >= 0) {
224              try {
225 <                while (status >= 0) {
226 <                    long nt = nanos - System.nanoTime() - startTime;
227 <                    if (nt <= 0)
236 <                        break;
237 <                    wait(nt / 1000000, (int)(nt % 1000000));
225 >                synchronized (this) {
226 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
227 >                        wait();
228                  }
229              } catch (InterruptedException ie) {
230 <                onInterruptedWait();
230 >                cancelIfTerminating();
231              }
232          }
233      }
234  
245    // Awaiting completion
246
235      /**
236 <     * Sets status to indicate there is joiner, then waits for join,
237 <     * surrounded with pool notifications.
238 <     * @return status upon exit
236 >     * Blocks a worker thread until completed or timed out.  Called
237 >     * only by pool.
238 >     *
239 >     * @return status on exit
240       */
241 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
253 <        ForkJoinPool pool = w == null? null : w.pool;
241 >    final int internalAwaitDone(long millis) {
242          int s;
243 <        while ((s = status) >= 0) {
244 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
245 <                if (pool == null || !pool.preJoin(this, maintainParallelism))
246 <                    doAwaitDone();
247 <                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
248 <                    adjustPoolCountsOnUnblock(pool);
249 <                break;
243 >        if ((s = status) >= 0) {
244 >            try {
245 >                synchronized (this) {
246 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
247 >                        wait(millis, 0);
248 >                }
249 >            } catch (InterruptedException ie) {
250 >                cancelIfTerminating();
251              }
252 +            s = status;
253          }
254          return s;
255      }
256  
257      /**
258 <     * Timed version of awaitDone
269 <     * @return status upon exit
258 >     * Blocks a non-worker-thread until completion.
259       */
260 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
272 <        ForkJoinPool pool = w == null? null : w.pool;
260 >    private void externalAwaitDone() {
261          int s;
262          while ((s = status) >= 0) {
263 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
264 <                long startTime = System.nanoTime();
265 <                if (pool == null || !pool.preJoin(this, false))
266 <                    doAwaitDone(startTime, nanos);
267 <                if ((s = status) >= 0) {
268 <                    adjustPoolCountsOnCancelledWait(pool);
269 <                    s = status;
263 >            synchronized (this) {
264 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
265 >                    boolean interrupted = false;
266 >                    while (status >= 0) {
267 >                        try {
268 >                            wait();
269 >                        } catch (InterruptedException ie) {
270 >                            interrupted = true;
271 >                        }
272 >                    }
273 >                    if (interrupted)
274 >                        Thread.currentThread().interrupt();
275 >                    break;
276                  }
283                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
284                    adjustPoolCountsOnUnblock(pool);
285                break;
277              }
278          }
288        return s;
279      }
280  
281      /**
282 <     * Notify pool that thread is unblocked. Called by signalled
283 <     * threads when woken by non-FJ threads (which is atypical).
282 >     * Unless done, calls exec and records status if completed, but
283 >     * doesn't wait for completion otherwise. Primary execution method
284 >     * for ForkJoinWorkerThread.
285       */
286 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
287 <        int s;
288 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
289 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
290 <            pool.updateRunningCount(s);
286 >    final void quietlyExec() {
287 >        try {
288 >            if (status < 0 || !exec())
289 >                return;
290 >        } catch (Throwable rex) {
291 >            setExceptionalCompletion(rex);
292 >            return;
293 >        }
294 >        setCompletion(NORMAL); // must be outside try block
295      }
296  
297 +    // public methods
298 +
299      /**
300 <     * Notify pool to adjust counts on cancelled or timed out wait
300 >     * Arranges to asynchronously execute this task.  While it is not
301 >     * necessarily enforced, it is a usage error to fork a task more
302 >     * than once unless it has completed and been reinitialized.
303 >     * Subsequent modifications to the state of this task or any data
304 >     * it operates on are not necessarily consistently observable by
305 >     * any thread other than the one executing it unless preceded by a
306 >     * call to {@link #join} or related methods, or a call to {@link
307 >     * #isDone} returning {@code true}.
308 >     *
309 >     * <p>This method may be invoked only from within {@code
310 >     * ForkJoinTask} computations (as may be determined using method
311 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
312 >     * result in exceptions or errors, possibly including {@code
313 >     * ClassCastException}.
314 >     *
315 >     * @return {@code this}, to simplify usage
316       */
317 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
318 <        if (pool != null) {
319 <            int s;
320 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
309 <                if (casStatus(s, s - 1)) {
310 <                    pool.updateRunningCount(1);
311 <                    break;
312 <                }
313 <            }
314 <        }
317 >    public final ForkJoinTask<V> fork() {
318 >        ((ForkJoinWorkerThread) Thread.currentThread())
319 >            .pushTask(this);
320 >        return this;
321      }
322  
323 <    private void onInterruptedWait() {
324 <        Thread t = Thread.currentThread();
325 <        if (t instanceof ForkJoinWorkerThread) {
326 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
327 <            if (w.isTerminating())
328 <                cancelIgnoreExceptions();
329 <        }
330 <        else { // re-interrupt
331 <            try {
332 <                t.interrupt();
333 <            } catch (SecurityException ignore) {
334 <            }
335 <        }
323 >    /**
324 >     * Returns the result of the computation when it {@link #isDone is done}.
325 >     * This method differs from {@link #get()} in that
326 >     * abnormal completion results in {@code RuntimeException} or
327 >     * {@code Error}, not {@code ExecutionException}.
328 >     *
329 >     * @return the computed result
330 >     */
331 >    public final V join() {
332 >        quietlyJoin();
333 >        Throwable ex;
334 >        if (status < NORMAL && (ex = getException()) != null)
335 >            UNSAFE.throwException(ex);
336 >        return getRawResult();
337      }
338  
339 <    // Recording and reporting exceptions
339 >    /**
340 >     * Commences performing this task, awaits its completion if
341 >     * necessary, and returns its result, or throws an (unchecked)
342 >     * {@code RuntimeException} or {@code Error} if the underlying
343 >     * computation did so.
344 >     *
345 >     * @return the computed result
346 >     */
347 >    public final V invoke() {
348 >        quietlyInvoke();
349 >        Throwable ex;
350 >        if (status < NORMAL && (ex = getException()) != null)
351 >            UNSAFE.throwException(ex);
352 >        return getRawResult();
353 >    }
354  
355 <    private void setDoneExceptionally(Throwable rex) {
356 <        exceptionMap.put(this, rex);
357 <        setCompletion(EXCEPTIONAL);
355 >    /**
356 >     * Forks the given tasks, returning when {@code isDone} holds for
357 >     * each task or an (unchecked) exception is encountered, in which
358 >     * case the exception is rethrown. If more than one task
359 >     * encounters an exception, then this method throws any one of
360 >     * these exceptions. If any task encounters an exception, the
361 >     * other may be cancelled. However, the execution status of
362 >     * individual tasks is not guaranteed upon exceptional return. The
363 >     * status of each task may be obtained using {@link
364 >     * #getException()} and related methods to check if they have been
365 >     * cancelled, completed normally or exceptionally, or left
366 >     * unprocessed.
367 >     *
368 >     * <p>This method may be invoked only from within {@code
369 >     * ForkJoinTask} computations (as may be determined using method
370 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
371 >     * result in exceptions or errors, possibly including {@code
372 >     * ClassCastException}.
373 >     *
374 >     * @param t1 the first task
375 >     * @param t2 the second task
376 >     * @throws NullPointerException if any task is null
377 >     */
378 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
379 >        t2.fork();
380 >        t1.invoke();
381 >        t2.join();
382      }
383  
384      /**
385 <     * Throws the exception associated with status s;
386 <     * @throws the exception
385 >     * Forks the given tasks, returning when {@code isDone} holds for
386 >     * each task or an (unchecked) exception is encountered, in which
387 >     * case the exception is rethrown. If more than one task
388 >     * encounters an exception, then this method throws any one of
389 >     * these exceptions. If any task encounters an exception, others
390 >     * may be cancelled. However, the execution status of individual
391 >     * tasks is not guaranteed upon exceptional return. The status of
392 >     * each task may be obtained using {@link #getException()} and
393 >     * related methods to check if they have been cancelled, completed
394 >     * normally or exceptionally, or left unprocessed.
395 >     *
396 >     * <p>This method may be invoked only from within {@code
397 >     * ForkJoinTask} computations (as may be determined using method
398 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
399 >     * result in exceptions or errors, possibly including {@code
400 >     * ClassCastException}.
401 >     *
402 >     * @param tasks the tasks
403 >     * @throws NullPointerException if any task is null
404       */
405 <    private void reportException(int s) {
406 <        if ((s &= COMPLETION_MASK) < NORMAL) {
407 <            if (s == CANCELLED)
408 <                throw new CancellationException();
409 <            else
410 <                rethrowException(exceptionMap.get(this));
405 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
406 >        Throwable ex = null;
407 >        int last = tasks.length - 1;
408 >        for (int i = last; i >= 0; --i) {
409 >            ForkJoinTask<?> t = tasks[i];
410 >            if (t == null) {
411 >                if (ex == null)
412 >                    ex = new NullPointerException();
413 >            }
414 >            else if (i != 0)
415 >                t.fork();
416 >            else {
417 >                t.quietlyInvoke();
418 >                if (ex == null && t.status < NORMAL)
419 >                    ex = t.getException();
420 >            }
421 >        }
422 >        for (int i = 1; i <= last; ++i) {
423 >            ForkJoinTask<?> t = tasks[i];
424 >            if (t != null) {
425 >                if (ex != null)
426 >                    t.cancel(false);
427 >                else {
428 >                    t.quietlyJoin();
429 >                    if (ex == null && t.status < NORMAL)
430 >                        ex = t.getException();
431 >                }
432 >            }
433          }
434 +        if (ex != null)
435 +            UNSAFE.throwException(ex);
436      }
437  
438      /**
439 <     * Returns result or throws exception using j.u.c.Future conventions
440 <     * Only call when isDone known to be true.
439 >     * Forks all tasks in the specified collection, returning when
440 >     * {@code isDone} holds for each task or an (unchecked) exception
441 >     * is encountered, in which case the exception is rethrown. If
442 >     * more than one task encounters an exception, then this method
443 >     * throws any one of these exceptions. If any task encounters an
444 >     * exception, others may be cancelled. However, the execution
445 >     * status of individual tasks is not guaranteed upon exceptional
446 >     * return. The status of each task may be obtained using {@link
447 >     * #getException()} and related methods to check if they have been
448 >     * cancelled, completed normally or exceptionally, or left
449 >     * unprocessed.
450 >     *
451 >     * <p>This method may be invoked only from within {@code
452 >     * ForkJoinTask} computations (as may be determined using method
453 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
454 >     * result in exceptions or errors, possibly including {@code
455 >     * ClassCastException}.
456 >     *
457 >     * @param tasks the collection of tasks
458 >     * @return the tasks argument, to simplify usage
459 >     * @throws NullPointerException if tasks or any element are null
460       */
461 <    private V reportFutureResult()
462 <        throws ExecutionException, InterruptedException {
463 <        int s = status & COMPLETION_MASK;
464 <        if (s < NORMAL) {
360 <            Throwable ex;
361 <            if (s == CANCELLED)
362 <                throw new CancellationException();
363 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
364 <                throw new ExecutionException(ex);
365 <            if (Thread.interrupted())
366 <                throw new InterruptedException();
461 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
462 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
463 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
464 >            return tasks;
465          }
466 <        return getRawResult();
466 >        @SuppressWarnings("unchecked")
467 >        List<? extends ForkJoinTask<?>> ts =
468 >            (List<? extends ForkJoinTask<?>>) tasks;
469 >        Throwable ex = null;
470 >        int last = ts.size() - 1;
471 >        for (int i = last; i >= 0; --i) {
472 >            ForkJoinTask<?> t = ts.get(i);
473 >            if (t == null) {
474 >                if (ex == null)
475 >                    ex = new NullPointerException();
476 >            }
477 >            else if (i != 0)
478 >                t.fork();
479 >            else {
480 >                t.quietlyInvoke();
481 >                if (ex == null && t.status < NORMAL)
482 >                    ex = t.getException();
483 >            }
484 >        }
485 >        for (int i = 1; i <= last; ++i) {
486 >            ForkJoinTask<?> t = ts.get(i);
487 >            if (t != null) {
488 >                if (ex != null)
489 >                    t.cancel(false);
490 >                else {
491 >                    t.quietlyJoin();
492 >                    if (ex == null && t.status < NORMAL)
493 >                        ex = t.getException();
494 >                }
495 >            }
496 >        }
497 >        if (ex != null)
498 >            UNSAFE.throwException(ex);
499 >        return tasks;
500      }
501  
502      /**
503 <     * Returns result or throws exception using j.u.c.Future conventions
504 <     * with timeouts
503 >     * Attempts to cancel execution of this task. This attempt will
504 >     * fail if the task has already completed, has already been
505 >     * cancelled, or could not be cancelled for some other reason. If
506 >     * successful, and this task has not started when cancel is
507 >     * called, execution of this task is suppressed, {@link
508 >     * #isCancelled} will report true, and {@link #join} will result
509 >     * in a {@code CancellationException} being thrown.
510 >     *
511 >     * <p>This method may be overridden in subclasses, but if so, must
512 >     * still ensure that these minimal properties hold. In particular,
513 >     * the {@code cancel} method itself must not throw exceptions.
514 >     *
515 >     * <p>This method is designed to be invoked by <em>other</em>
516 >     * tasks. To terminate the current task, you can just return or
517 >     * throw an unchecked exception from its computation method, or
518 >     * invoke {@link #completeExceptionally}.
519 >     *
520 >     * @param mayInterruptIfRunning this value is ignored in the
521 >     * default implementation because tasks are not
522 >     * cancelled via interruption
523 >     *
524 >     * @return {@code true} if this task is now cancelled
525       */
526 <    private V reportTimedFutureResult()
527 <        throws InterruptedException, ExecutionException, TimeoutException {
528 <        Throwable ex;
378 <        int s = status & COMPLETION_MASK;
379 <        if (s == NORMAL)
380 <            return getRawResult();
381 <        if (s == CANCELLED)
382 <            throw new CancellationException();
383 <        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
384 <            throw new ExecutionException(ex);
385 <        if (Thread.interrupted())
386 <            throw new InterruptedException();
387 <        throw new TimeoutException();
526 >    public boolean cancel(boolean mayInterruptIfRunning) {
527 >        setCompletion(CANCELLED);
528 >        return status == CANCELLED;
529      }
530  
390    // internal execution methods
391
531      /**
532 <     * Calls exec, recording completion, and rethrowing exception if
533 <     * encountered. Caller should normally check status before calling
534 <     * @return true if completed normally
532 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
533 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
534 >     * exceptions, but if it does anyway, we have no recourse during
535 >     * shutdown, so guard against this case.
536       */
537 <    private boolean tryExec() {
538 <        try { // try block must contain only call to exec
539 <            if (!exec())
540 <                return false;
401 <        } catch (Throwable rex) {
402 <            setDoneExceptionally(rex);
403 <            rethrowException(rex);
404 <            return false; // not reached
537 >    final void cancelIgnoringExceptions() {
538 >        try {
539 >            cancel(false);
540 >        } catch (Throwable ignore) {
541          }
406        setNormalCompletion();
407        return true;
542      }
543  
544      /**
545 <     * Main execution method used by worker threads. Invokes
546 <     * base computation unless already complete
545 >     * Cancels if current thread is a terminating worker thread,
546 >     * ignoring any exceptions thrown by cancel.
547       */
548 <    final void quietlyExec() {
549 <        if (status >= 0) {
548 >    final void cancelIfTerminating() {
549 >        Thread t = Thread.currentThread();
550 >        if ((t instanceof ForkJoinWorkerThread) &&
551 >            ((ForkJoinWorkerThread) t).isTerminating()) {
552              try {
553 <                if (!exec())
554 <                    return;
419 <            } catch(Throwable rex) {
420 <                setDoneExceptionally(rex);
421 <                return;
553 >                cancel(false);
554 >            } catch (Throwable ignore) {
555              }
423            setNormalCompletion();
556          }
557      }
558  
559 <    /**
560 <     * Calls exec, recording but not rethrowing exception
561 <     * Caller should normally check status before calling
562 <     * @return true if completed normally
563 <     */
564 <    private boolean tryQuietlyInvoke() {
433 <        try {
434 <            if (!exec())
435 <                return false;
436 <        } catch (Throwable rex) {
437 <            setDoneExceptionally(rex);
438 <            return false;
439 <        }
440 <        setNormalCompletion();
441 <        return true;
559 >    public final boolean isDone() {
560 >        return status < 0;
561 >    }
562 >
563 >    public final boolean isCancelled() {
564 >        return status == CANCELLED;
565      }
566  
567      /**
568 <     * Cancel, ignoring any exceptions it throws
568 >     * Returns {@code true} if this task threw an exception or was cancelled.
569 >     *
570 >     * @return {@code true} if this task threw an exception or was cancelled
571       */
572 <    final void cancelIgnoreExceptions() {
573 <        try {
449 <            cancel(false);
450 <        } catch(Throwable ignore) {
451 <        }
572 >    public final boolean isCompletedAbnormally() {
573 >        return status < NORMAL;
574      }
575  
454    // public methods
455
576      /**
577 <     * Arranges to asynchronously execute this task.  While it is not
578 <     * necessarily enforced, it is a usage error to fork a task more
579 <     * than once unless it has completed and been reinitialized.  This
580 <     * method may be invoked only from within other ForkJoinTask
581 <     * computations. Attempts to invoke in other contexts result in
462 <     * exceptions or errors including ClassCastException.
577 >     * Returns {@code true} if this task completed without throwing an
578 >     * exception and was not cancelled.
579 >     *
580 >     * @return {@code true} if this task completed without throwing an
581 >     * exception and was not cancelled
582       */
583 <    public final void fork() {
584 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
583 >    public final boolean isCompletedNormally() {
584 >        return status == NORMAL;
585      }
586  
587      /**
588 <     * Returns the result of the computation when it is ready.
589 <     * This method differs from <tt>get</tt> in that abnormal
590 <     * completion results in RuntimeExceptions or Errors, not
472 <     * ExecutionExceptions.
588 >     * Returns the exception thrown by the base computation, or a
589 >     * {@code CancellationException} if cancelled, or {@code null} if
590 >     * none or if the method has not yet completed.
591       *
592 <     * @return the computed result
592 >     * @return the exception, or {@code null} if none
593       */
594 <    public final V join() {
595 <        ForkJoinWorkerThread w = getWorker();
596 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
597 <            reportException(awaitDone(w, true));
598 <        return getRawResult();
594 >    public final Throwable getException() {
595 >        int s = status;
596 >        return ((s >= NORMAL)    ? null :
597 >                (s == CANCELLED) ? new CancellationException() :
598 >                exceptionMap.get(this));
599      }
600  
601 <    public final V get() throws InterruptedException, ExecutionException {
602 <        ForkJoinWorkerThread w = getWorker();
603 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
604 <            awaitDone(w, true);
605 <        return reportFutureResult();
601 >    /**
602 >     * Completes this task abnormally, and if not already aborted or
603 >     * cancelled, causes it to throw the given exception upon
604 >     * {@code join} and related operations. This method may be used
605 >     * to induce exceptions in asynchronous tasks, or to force
606 >     * completion of tasks that would not otherwise complete.  Its use
607 >     * in other situations is discouraged.  This method is
608 >     * overridable, but overridden versions must invoke {@code super}
609 >     * implementation to maintain guarantees.
610 >     *
611 >     * @param ex the exception to throw. If this exception is not a
612 >     * {@code RuntimeException} or {@code Error}, the actual exception
613 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
614 >     */
615 >    public void completeExceptionally(Throwable ex) {
616 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
617 >                                 (ex instanceof Error) ? ex :
618 >                                 new RuntimeException(ex));
619      }
620  
621 <    public final V get(long timeout, TimeUnit unit)
622 <        throws InterruptedException, ExecutionException, TimeoutException {
623 <        ForkJoinWorkerThread w = getWorker();
624 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
625 <            awaitDone(w, unit.toNanos(timeout));
626 <        return reportTimedFutureResult();
621 >    /**
622 >     * Completes this task, and if not already aborted or cancelled,
623 >     * returning the given value as the result of subsequent
624 >     * invocations of {@code join} and related operations. This method
625 >     * may be used to provide results for asynchronous tasks, or to
626 >     * provide alternative handling for tasks that would not otherwise
627 >     * complete normally. Its use in other situations is
628 >     * discouraged. This method is overridable, but overridden
629 >     * versions must invoke {@code super} implementation to maintain
630 >     * guarantees.
631 >     *
632 >     * @param value the result value for this task
633 >     */
634 >    public void complete(V value) {
635 >        try {
636 >            setRawResult(value);
637 >        } catch (Throwable rex) {
638 >            setExceptionalCompletion(rex);
639 >            return;
640 >        }
641 >        setCompletion(NORMAL);
642      }
643  
644      /**
645 <     * Possibly executes other tasks until this task is ready, then
646 <     * returns the result of the computation.  This method may be more
647 <     * 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).
645 >     * Waits if necessary for the computation to complete, and then
646 >     * retrieves its result.
647 >     *
648       * @return the computed result
649 +     * @throws CancellationException if the computation was cancelled
650 +     * @throws ExecutionException if the computation threw an
651 +     * exception
652 +     * @throws InterruptedException if the current thread is not a
653 +     * member of a ForkJoinPool and was interrupted while waiting
654       */
655 <    public final V helpJoin() {
656 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
657 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
658 <            reportException(w.helpJoinTask(this));
655 >    public final V get() throws InterruptedException, ExecutionException {
656 >        int s;
657 >        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
658 >            quietlyJoin();
659 >            s = status;
660 >        }
661 >        else {
662 >            while ((s = status) >= 0) {
663 >                synchronized (this) { // interruptible form of awaitDone
664 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
665 >                                                 s, SIGNAL)) {
666 >                        while (status >= 0)
667 >                            wait();
668 >                    }
669 >                }
670 >            }
671 >        }
672 >        if (s < NORMAL) {
673 >            Throwable ex;
674 >            if (s == CANCELLED)
675 >                throw new CancellationException();
676 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
677 >                throw new ExecutionException(ex);
678 >        }
679          return getRawResult();
680      }
681  
682      /**
683 <     * Performs this task, awaits its completion if necessary, and
684 <     * return its result.
685 <     * @throws Throwable (a RuntimeException, Error, or unchecked
686 <     * exception) if the underlying computation did so.
683 >     * Waits if necessary for at most the given time for the computation
684 >     * to complete, and then retrieves its result, if available.
685 >     *
686 >     * @param timeout the maximum time to wait
687 >     * @param unit the time unit of the timeout argument
688       * @return the computed result
689 +     * @throws CancellationException if the computation was cancelled
690 +     * @throws ExecutionException if the computation threw an
691 +     * exception
692 +     * @throws InterruptedException if the current thread is not a
693 +     * member of a ForkJoinPool and was interrupted while waiting
694 +     * @throws TimeoutException if the wait timed out
695       */
696 <    public final V invoke() {
697 <        if (status >= 0 && tryExec())
698 <            return getRawResult();
696 >    public final V get(long timeout, TimeUnit unit)
697 >        throws InterruptedException, ExecutionException, TimeoutException {
698 >        Thread t = Thread.currentThread();
699 >        ForkJoinPool pool;
700 >        if (t instanceof ForkJoinWorkerThread) {
701 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
702 >            if (status >= 0 && w.unpushTask(this))
703 >                quietlyExec();
704 >            pool = w.pool;
705 >        }
706          else
707 <            return join();
707 >            pool = null;
708 >        /*
709 >         * Timed wait loop intermixes cases for FJ (pool != null) and
710 >         * non FJ threads. For FJ, decrement pool count but don't try
711 >         * for replacement; increment count on completion. For non-FJ,
712 >         * deal with interrupts. This is messy, but a little less so
713 >         * than is splitting the FJ and nonFJ cases.
714 >         */
715 >        boolean interrupted = false;
716 >        boolean dec = false; // true if pool count decremented
717 >        long nanos = unit.toNanos(timeout);
718 >        for (;;) {
719 >            if (pool == null && Thread.interrupted()) {
720 >                interrupted = true;
721 >                break;
722 >            }
723 >            int s = status;
724 >            if (s < 0)
725 >                break;
726 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
727 >                long startTime = System.nanoTime();
728 >                long nt; // wait time
729 >                while (status >= 0 &&
730 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
731 >                    if (pool != null && !dec)
732 >                        dec = pool.tryDecrementRunningCount();
733 >                    else {
734 >                        long ms = nt / 1000000;
735 >                        int ns = (int) (nt % 1000000);
736 >                        try {
737 >                            synchronized (this) {
738 >                                if (status >= 0)
739 >                                    wait(ms, ns);
740 >                            }
741 >                        } catch (InterruptedException ie) {
742 >                            if (pool != null)
743 >                                cancelIfTerminating();
744 >                            else {
745 >                                interrupted = true;
746 >                                break;
747 >                            }
748 >                        }
749 >                    }
750 >                }
751 >                break;
752 >            }
753 >        }
754 >        if (pool != null && dec)
755 >            pool.incrementRunningCount();
756 >        if (interrupted)
757 >            throw new InterruptedException();
758 >        int es = status;
759 >        if (es != NORMAL) {
760 >            Throwable ex;
761 >            if (es == CANCELLED)
762 >                throw new CancellationException();
763 >            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
764 >                throw new ExecutionException(ex);
765 >            throw new TimeoutException();
766 >        }
767 >        return getRawResult();
768      }
769  
770      /**
771 <     * Joins this task, without returning its result or throwing an
771 >     * Joins this task, without returning its result or throwing its
772       * exception. This method may be useful when processing
773       * collections of tasks when some have been cancelled or otherwise
774       * known to have aborted.
775       */
776      public final void quietlyJoin() {
777 <        if (status >= 0) {
778 <            ForkJoinWorkerThread w = getWorker();
779 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
780 <                awaitDone(w, true);
777 >        Thread t;
778 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
779 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
780 >            if (status >= 0) {
781 >                if (w.unpushTask(this)) {
782 >                    boolean completed;
783 >                    try {
784 >                        completed = exec();
785 >                    } catch (Throwable rex) {
786 >                        setExceptionalCompletion(rex);
787 >                        return;
788 >                    }
789 >                    if (completed) {
790 >                        setCompletion(NORMAL);
791 >                        return;
792 >                    }
793 >                }
794 >                w.joinTask(this);
795 >            }
796          }
797 +        else
798 +            externalAwaitDone();
799      }
800  
801      /**
802 <     * Possibly executes other tasks until this task is ready.
802 >     * Commences performing this task and awaits its completion if
803 >     * necessary, without returning its result or throwing its
804 >     * exception.
805       */
806 <    public final void quietlyHelpJoin() {
806 >    public final void quietlyInvoke() {
807          if (status >= 0) {
808 <            ForkJoinWorkerThread w =
809 <                (ForkJoinWorkerThread)(Thread.currentThread());
810 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
811 <                w.helpJoinTask(this);
808 >            boolean completed;
809 >            try {
810 >                completed = exec();
811 >            } catch (Throwable rex) {
812 >                setExceptionalCompletion(rex);
813 >                return;
814 >            }
815 >            if (completed)
816 >                setCompletion(NORMAL);
817 >            else
818 >                quietlyJoin();
819          }
820      }
821  
822      /**
823 <     * Performs this task and awaits its completion if necessary,
824 <     * without returning its result or throwing an exception. This
825 <     * method may be useful when processing collections of tasks when
826 <     * some have been cancelled or otherwise known to have aborted.
823 >     * Possibly executes tasks until the pool hosting the current task
824 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
825 >     * be of use in designs in which many tasks are forked, but none
826 >     * are explicitly joined, instead executing them until all are
827 >     * processed.
828 >     *
829 >     * <p>This method may be invoked only from within {@code
830 >     * ForkJoinTask} computations (as may be determined using method
831 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
832 >     * result in exceptions or errors, possibly including {@code
833 >     * ClassCastException}.
834       */
835 <    public final void quietlyInvoke() {
836 <        if (status >= 0 && !tryQuietlyInvoke())
837 <            quietlyJoin();
835 >    public static void helpQuiesce() {
836 >        ((ForkJoinWorkerThread) Thread.currentThread())
837 >            .helpQuiescePool();
838      }
839  
840      /**
841 <     * Returns true if the computation performed by this task has
842 <     * completed (or has been cancelled).
843 <     * @return true if this computation has completed
841 >     * Resets the internal bookkeeping state of this task, allowing a
842 >     * subsequent {@code fork}. This method allows repeated reuse of
843 >     * this task, but only if reuse occurs when this task has either
844 >     * never been forked, or has been forked, then completed and all
845 >     * outstanding joins of this task have also completed. Effects
846 >     * under any other usage conditions are not guaranteed.
847 >     * This method may be useful when executing
848 >     * pre-constructed trees of subtasks in loops.
849       */
850 <    public final boolean isDone() {
851 <        return status < 0;
850 >    public void reinitialize() {
851 >        if (status == EXCEPTIONAL)
852 >            exceptionMap.remove(this);
853 >        status = 0;
854      }
855  
856      /**
857 <     * Returns true if this task was cancelled.
858 <     * @return true if this task was cancelled
857 >     * Returns the pool hosting the current task execution, or null
858 >     * if this task is executing outside of any ForkJoinPool.
859 >     *
860 >     * @see #inForkJoinPool
861 >     * @return the pool, or {@code null} if none
862       */
863 <    public final boolean isCancelled() {
864 <        return (status & COMPLETION_MASK) == CANCELLED;
863 >    public static ForkJoinPool getPool() {
864 >        Thread t = Thread.currentThread();
865 >        return (t instanceof ForkJoinWorkerThread) ?
866 >            ((ForkJoinWorkerThread) t).pool : null;
867      }
868  
869      /**
870 <     * Returns true if this task threw an exception or was cancelled
871 <     * @return true if this task threw an exception or was cancelled
870 >     * Returns {@code true} if the current thread is executing as a
871 >     * ForkJoinPool computation.
872 >     *
873 >     * @return {@code true} if the current thread is executing as a
874 >     * ForkJoinPool computation, or false otherwise
875       */
876 <    public final boolean completedAbnormally() {
877 <        return (status & COMPLETION_MASK) < NORMAL;
876 >    public static boolean inForkJoinPool() {
877 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
878      }
879  
880      /**
881 <     * Returns the exception thrown by the base computation, or a
882 <     * CancellationException if cancelled, or null if none or if the
883 <     * method has not yet completed.
884 <     * @return the exception, or null if none
881 >     * Tries to unschedule this task for execution. This method will
882 >     * typically succeed if this task is the most recently forked task
883 >     * by the current thread, and has not commenced executing in
884 >     * another thread.  This method may be useful when arranging
885 >     * alternative local processing of tasks that could have been, but
886 >     * were not, stolen.
887 >     *
888 >     * <p>This method may be invoked only from within {@code
889 >     * ForkJoinTask} computations (as may be determined using method
890 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
891 >     * result in exceptions or errors, possibly including {@code
892 >     * ClassCastException}.
893 >     *
894 >     * @return {@code true} if unforked
895       */
896 <    public final Throwable getException() {
897 <        int s = status & COMPLETION_MASK;
898 <        if (s >= NORMAL)
600 <            return null;
601 <        if (s == CANCELLED)
602 <            return new CancellationException();
603 <        return exceptionMap.get(this);
896 >    public boolean tryUnfork() {
897 >        return ((ForkJoinWorkerThread) Thread.currentThread())
898 >            .unpushTask(this);
899      }
900  
901      /**
902 <     * Asserts that the results of this task's computation will not be
903 <     * used. If a cancellation occurs before this task is processed,
904 <     * then its <tt>compute</tt> method will not be executed,
905 <     * <tt>isCancelled</tt> will report true, and <tt>join</tt> will
611 <     * result in a CancellationException being thrown. Otherwise, when
612 <     * cancellation races with completion, there are no guarantees
613 <     * about whether <tt>isCancelled</tt> will report true, whether
614 <     * <tt>join</tt> will return normally or via an exception, or
615 <     * whether these behaviors will remain consistent upon repeated
616 <     * invocation.
902 >     * Returns an estimate of the number of tasks that have been
903 >     * forked by the current worker thread but not yet executed. This
904 >     * value may be useful for heuristic decisions about whether to
905 >     * fork other tasks.
906       *
907 <     * <p>This method may be overridden in subclasses, but if so, must
908 <     * still ensure that these minimal properties hold. In particular,
909 <     * the cancel method itself must not throw exceptions.
907 >     * <p>This method may be invoked only from within {@code
908 >     * ForkJoinTask} computations (as may be determined using method
909 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
910 >     * result in exceptions or errors, possibly including {@code
911 >     * ClassCastException}.
912       *
913 <     * <p> This method is designed to be invoked by <em>other</em>
914 <     * tasks. To terminate the current task, you can just return or
915 <     * throw an unchecked exception from its computation method, or
916 <     * invoke <tt>completeExceptionally(someException)</tt>.
913 >     * @return the number of tasks
914 >     */
915 >    public static int getQueuedTaskCount() {
916 >        return ((ForkJoinWorkerThread) Thread.currentThread())
917 >            .getQueueSize();
918 >    }
919 >
920 >    /**
921 >     * Returns an estimate of how many more locally queued tasks are
922 >     * held by the current worker thread than there are other worker
923 >     * threads that might steal them.  This value may be useful for
924 >     * heuristic decisions about whether to fork other tasks. In many
925 >     * usages of ForkJoinTasks, at steady state, each worker should
926 >     * aim to maintain a small constant surplus (for example, 3) of
927 >     * tasks, and to process computations locally if this threshold is
928 >     * exceeded.
929       *
930 <     * @param mayInterruptIfRunning this value is ignored in the
931 <     * default implementation because tasks are not in general
932 <     * cancelled via interruption.
930 >     * <p>This method may be invoked only from within {@code
931 >     * ForkJoinTask} computations (as may be determined using method
932 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
933 >     * result in exceptions or errors, possibly including {@code
934 >     * ClassCastException}.
935       *
936 <     * @return true if this task is now cancelled
936 >     * @return the surplus number of tasks, which may be negative
937       */
938 <    public boolean cancel(boolean mayInterruptIfRunning) {
939 <        setCompletion(CANCELLED);
940 <        return (status & COMPLETION_MASK) == CANCELLED;
938 >    public static int getSurplusQueuedTaskCount() {
939 >        return ((ForkJoinWorkerThread) Thread.currentThread())
940 >            .getEstimatedSurplusTaskCount();
941      }
942  
943 +    // Extension methods
944 +
945      /**
946 <     * Completes this task abnormally, and if not already aborted or
947 <     * cancelled, causes it to throw the given exception upon
948 <     * <tt>join</tt> and related operations. This method may be used
949 <     * to induce exceptions in asynchronous tasks, or to force
950 <     * completion of tasks that would not otherwise complete.  This
951 <     * method is overridable, but overridden versions must invoke
952 <     * <tt>super</tt> implementation to maintain guarantees.
646 <     * @param ex the exception to throw. If this exception is
647 <     * not a RuntimeException or Error, the actual exception thrown
648 <     * will be a RuntimeException with cause ex.
946 >     * Returns the result that would be returned by {@link #join}, even
947 >     * if this task completed abnormally, or {@code null} if this task
948 >     * is not known to have been completed.  This method is designed
949 >     * to aid debugging, as well as to support extensions. Its use in
950 >     * any other context is discouraged.
951 >     *
952 >     * @return the result, or {@code null} if not completed
953       */
954 <    public void completeExceptionally(Throwable ex) {
651 <        setDoneExceptionally((ex instanceof RuntimeException) ||
652 <                             (ex instanceof Error)? ex :
653 <                             new RuntimeException(ex));
654 <    }
954 >    public abstract V getRawResult();
955  
956      /**
957 <     * Completes this task, and if not already aborted or cancelled,
958 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
959 <     * operations. This method may be used to provide results for
660 <     * asynchronous tasks, or to provide alternative handling for
661 <     * tasks that would not otherwise complete normally.
957 >     * Forces the given value to be returned as a result.  This method
958 >     * is designed to support extensions, and should not in general be
959 >     * called otherwise.
960       *
961 <     * @param value the result value for this task.
961 >     * @param value the value
962       */
963 <    public void complete(V value) {
666 <        try {
667 <            setRawResult(value);
668 <        } catch(Throwable rex) {
669 <            setDoneExceptionally(rex);
670 <            return;
671 <        }
672 <        setNormalCompletion();
673 <    }
963 >    protected abstract void setRawResult(V value);
964  
965      /**
966 <     * Resets the internal bookkeeping state of this task, allowing a
967 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
968 <     * this task, but only if reuse occurs when this task has either
969 <     * never been forked, or has been forked, then completed and all
970 <     * outstanding joins of this task have also completed. Effects
971 <     * under any other usage conditions are not guaranteed, and are
972 <     * almost surely wrong. This method may be useful when executing
973 <     * pre-constructed trees of subtasks in loops.
966 >     * Immediately performs the base action of this task.  This method
967 >     * is designed to support extensions, and should not in general be
968 >     * called otherwise. The return value controls whether this task
969 >     * is considered to be done normally. It may return false in
970 >     * asynchronous actions that require explicit invocations of
971 >     * {@link #complete} to become joinable. It may also throw an
972 >     * (unchecked) exception to indicate abnormal exit.
973 >     *
974 >     * @return {@code true} if completed normally
975       */
976 <    public void reinitialize() {
686 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
687 <            exceptionMap.remove(this);
688 <        status = 0;
689 <    }
976 >    protected abstract boolean exec();
977  
978      /**
979 <     * Tries to unschedule this task for execution. This method will
980 <     * typically succeed if this task is the next task that would be
981 <     * executed by the current thread, and will typically fail (return
982 <     * false) otherwise. This method may be useful when arranging
983 <     * faster local processing of tasks that could have been, but were
984 <     * not, stolen.
985 <     * @return true if unforked
979 >     * Returns, but does not unschedule or execute, a task queued by
980 >     * the current thread but not yet executed, if one is immediately
981 >     * available. There is no guarantee that this task will actually
982 >     * be polled or executed next. Conversely, this method may return
983 >     * null even if a task exists but cannot be accessed without
984 >     * contention with other threads.  This method is designed
985 >     * primarily to support extensions, and is unlikely to be useful
986 >     * otherwise.
987 >     *
988 >     * <p>This method may be invoked only from within {@code
989 >     * ForkJoinTask} computations (as may be determined using method
990 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
991 >     * result in exceptions or errors, possibly including {@code
992 >     * ClassCastException}.
993 >     *
994 >     * @return the next task, or {@code null} if none are available
995       */
996 <    public boolean tryUnfork() {
997 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
996 >    protected static ForkJoinTask<?> peekNextLocalTask() {
997 >        return ((ForkJoinWorkerThread) Thread.currentThread())
998 >            .peekTask();
999      }
1000  
1001      /**
1002 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
1003 <     * of them or an exception is encountered. This method may be
1004 <     * invoked only from within other ForkJoinTask
1005 <     * computations. Attempts to invoke in other contexts result in
1006 <     * exceptions or errors including ClassCastException.
1007 <     * @param t1 one task
1008 <     * @param t2 the other task
1009 <     * @throws NullPointerException if t1 or t2 are null
1010 <     * @throws RuntimeException or Error if either task did so.
1002 >     * Unschedules and returns, without executing, the next task
1003 >     * queued by the current thread but not yet executed.  This method
1004 >     * is designed primarily to support extensions, and is unlikely to
1005 >     * be useful otherwise.
1006 >     *
1007 >     * <p>This method may be invoked only from within {@code
1008 >     * ForkJoinTask} computations (as may be determined using method
1009 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1010 >     * result in exceptions or errors, possibly including {@code
1011 >     * ClassCastException}.
1012 >     *
1013 >     * @return the next task, or {@code null} if none are available
1014       */
1015 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
1016 <        t2.fork();
1017 <        t1.invoke();
718 <        t2.join();
1015 >    protected static ForkJoinTask<?> pollNextLocalTask() {
1016 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1017 >            .pollLocalTask();
1018      }
1019  
1020      /**
1021 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
1022 <     * all of them. If any task encounters an exception, others may be
1023 <     * cancelled.  This method may be invoked only from within other
1024 <     * ForkJoinTask computations. Attempts to invoke in other contexts
1025 <     * result in exceptions or errors including ClassCastException.
1026 <     * @param tasks the array of tasks
1027 <     * @throws NullPointerException if tasks or any element are null.
1028 <     * @throws RuntimeException or Error if any task did so.
1021 >     * Unschedules and returns, without executing, the next task
1022 >     * queued by the current thread but not yet executed, if one is
1023 >     * available, or if not available, a task that was forked by some
1024 >     * other thread, if available. Availability may be transient, so a
1025 >     * {@code null} result does not necessarily imply quiescence
1026 >     * of the pool this task is operating in.  This method is designed
1027 >     * primarily to support extensions, and is unlikely to be useful
1028 >     * otherwise.
1029 >     *
1030 >     * <p>This method may be invoked only from within {@code
1031 >     * ForkJoinTask} computations (as may be determined using method
1032 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1033 >     * result in exceptions or errors, possibly including {@code
1034 >     * ClassCastException}.
1035 >     *
1036 >     * @return a task, or {@code null} if none are available
1037       */
1038 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
1039 <        Throwable ex = null;
1040 <        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);
1038 >    protected static ForkJoinTask<?> pollTask() {
1039 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1040 >            .pollTask();
1041      }
1042  
1043      /**
1044 <     * Forks all tasks in the collection, returning when
1045 <     * <tt>isDone</tt> holds for all of them. If any task encounters
1046 <     * an exception, others may be cancelled.  This method may be
768 <     * invoked only from within other ForkJoinTask
769 <     * computations. Attempts to invoke in other contexts result in
770 <     * exceptions or errors including ClassCastException.
771 <     * @param tasks the collection of tasks
772 <     * @throws NullPointerException if tasks or any element are null.
773 <     * @throws RuntimeException or Error if any task did so.
1044 >     * Adaptor for Runnables. This implements RunnableFuture
1045 >     * to be compliant with AbstractExecutorService constraints
1046 >     * when used in ForkJoinPool.
1047       */
1048 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
1049 <        if (!(tasks instanceof List)) {
1050 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
1051 <            return;
1052 <        }
1053 <        List<? extends ForkJoinTask<?>> ts =
1054 <            (List<? extends ForkJoinTask<?>>)tasks;
1055 <        Throwable ex = null;
1056 <        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 <            }
1048 >    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1049 >        implements RunnableFuture<T> {
1050 >        final Runnable runnable;
1051 >        final T resultOnCompletion;
1052 >        T result;
1053 >        AdaptedRunnable(Runnable runnable, T result) {
1054 >            if (runnable == null) throw new NullPointerException();
1055 >            this.runnable = runnable;
1056 >            this.resultOnCompletion = result;
1057          }
1058 <        for (int i = 1; i <= last; ++i) {
1059 <            ForkJoinTask<?> t = ts.get(i);
1060 <            if (t != null) {
1061 <                if (ex != null)
1062 <                    t.cancel(false);
1063 <                else {
804 <                    t.quietlyJoin();
805 <                    if (ex == null)
806 <                        ex = t.getException();
807 <                }
808 <            }
1058 >        public T getRawResult() { return result; }
1059 >        public void setRawResult(T v) { result = v; }
1060 >        public boolean exec() {
1061 >            runnable.run();
1062 >            result = resultOnCompletion;
1063 >            return true;
1064          }
1065 <        if (ex != null)
1066 <            rethrowException(ex);
1065 >        public void run() { invoke(); }
1066 >        private static final long serialVersionUID = 5232453952276885070L;
1067      }
1068  
1069      /**
1070 <     * Possibly executes tasks until the pool hosting the current task
816 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
817 <     * designs in which many tasks are forked, but none are explicitly
818 <     * joined, instead executing them until all are processed.
1070 >     * Adaptor for Callables
1071       */
1072 <    public static void helpQuiesce() {
1073 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
1074 <            helpQuiescePool();
1072 >    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1073 >        implements RunnableFuture<T> {
1074 >        final Callable<? extends T> callable;
1075 >        T result;
1076 >        AdaptedCallable(Callable<? extends T> callable) {
1077 >            if (callable == null) throw new NullPointerException();
1078 >            this.callable = callable;
1079 >        }
1080 >        public T getRawResult() { return result; }
1081 >        public void setRawResult(T v) { result = v; }
1082 >        public boolean exec() {
1083 >            try {
1084 >                result = callable.call();
1085 >                return true;
1086 >            } catch (Error err) {
1087 >                throw err;
1088 >            } catch (RuntimeException rex) {
1089 >                throw rex;
1090 >            } catch (Exception ex) {
1091 >                throw new RuntimeException(ex);
1092 >            }
1093 >        }
1094 >        public void run() { invoke(); }
1095 >        private static final long serialVersionUID = 2838392045355241008L;
1096      }
1097  
1098      /**
1099 <     * Returns a estimate of how many more locally queued tasks are
1100 <     * held by the current worker thread than there are other worker
1101 <     * threads that might want to steal them.  This value may be
1102 <     * useful for heuristic decisions about whether to fork other
1103 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
1104 <     * worker should aim to maintain a small constant surplus (for
832 <     * example, 3) of tasks, and to process computations locally if
833 <     * this threshold is exceeded.
834 <     * @return the surplus number of tasks, which may be negative
1099 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1100 >     * method of the given {@code Runnable} as its action, and returns
1101 >     * a null result upon {@link #join}.
1102 >     *
1103 >     * @param runnable the runnable action
1104 >     * @return the task
1105       */
1106 <    public static int surplus() {
1107 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
838 <            .getEstimatedSurplusTaskCount();
1106 >    public static ForkJoinTask<?> adapt(Runnable runnable) {
1107 >        return new AdaptedRunnable<Void>(runnable, null);
1108      }
1109  
841    // Extension kit
842
1110      /**
1111 <     * Returns the result that would be returned by <tt>join</tt>, or
1112 <     * null if this task is not known to have been completed.  This
1113 <     * method is designed to aid debugging, as well as to support
847 <     * extensions. Its use in any other context is discouraged.
1111 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1112 >     * method of the given {@code Runnable} as its action, and returns
1113 >     * the given result upon {@link #join}.
1114       *
1115 <     * @return the result, or null if not completed.
1115 >     * @param runnable the runnable action
1116 >     * @param result the result upon completion
1117 >     * @return the task
1118       */
1119 <    public abstract V getRawResult();
1119 >    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1120 >        return new AdaptedRunnable<T>(runnable, result);
1121 >    }
1122  
1123      /**
1124 <     * Forces the given value to be returned as a result.  This method
1125 <     * is designed to support extensions, and should not in general be
1126 <     * called otherwise.
1124 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1125 >     * method of the given {@code Callable} as its action, and returns
1126 >     * its result upon {@link #join}, translating any checked exceptions
1127 >     * encountered into {@code RuntimeException}.
1128       *
1129 <     * @param value the value
1130 <     */
860 <    protected abstract void setRawResult(V value);
861 <
862 <    /**
863 <     * Immediately performs the base action of this task.  This method
864 <     * is designed to support extensions, and should not in general be
865 <     * called otherwise. The return value controls whether this task
866 <     * is considered to be done normally. It may return false in
867 <     * asynchronous actions that require explicit invocations of
868 <     * <tt>complete</tt> to become joinable. It may throw exceptions
869 <     * to indicate abnormal exit.
870 <     * @return true if completed normally
871 <     * @throws Error or RuntimeException if encountered during computation
1129 >     * @param callable the callable action
1130 >     * @return the task
1131       */
1132 <    protected abstract boolean exec();
1132 >    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1133 >        return new AdaptedCallable<T>(callable);
1134 >    }
1135  
1136      // Serialization support
1137  
1138      private static final long serialVersionUID = -7721805057305804111L;
1139  
1140      /**
1141 <     * Save the state to a stream.
1141 >     * Saves the state to a stream (that is, serializes it).
1142       *
1143       * @serialData the current run status and the exception thrown
1144 <     * during execution, or null if none.
1144 >     * during execution, or {@code null} if none
1145       * @param s the stream
1146       */
1147      private void writeObject(java.io.ObjectOutputStream s)
# Line 890 | Line 1151 | public abstract class ForkJoinTask<V> im
1151      }
1152  
1153      /**
1154 <     * Reconstitute the instance from a stream.
1154 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1155 >     *
1156       * @param s the stream
1157       */
1158      private void readObject(java.io.ObjectInputStream s)
1159          throws java.io.IOException, ClassNotFoundException {
1160          s.defaultReadObject();
899        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1161          Object ex = s.readObject();
1162          if (ex != null)
1163 <            setDoneExceptionally((Throwable)ex);
1163 >            setExceptionalCompletion((Throwable) ex);
1164      }
1165  
1166 <    // Temporary Unsafe mechanics for preliminary release
1166 >    // Unsafe mechanics
1167  
1168 <    static final Unsafe _unsafe;
1169 <    static final long statusOffset;
1168 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1169 >    private static final long statusOffset =
1170 >        objectFieldOffset("status", ForkJoinTask.class);
1171  
1172 <    static {
1172 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1173          try {
1174 <            if (ForkJoinTask.class.getClassLoader() != null) {
1175 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1176 <                f.setAccessible(true);
1177 <                _unsafe = (Unsafe)f.get(null);
1178 <            }
1179 <            else
1180 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
920 <                (ForkJoinTask.class.getDeclaredField("status"));
921 <        } catch (Exception ex) { throw new Error(ex); }
1174 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1175 >        } catch (NoSuchFieldException e) {
1176 >            // Convert Exception to corresponding Error
1177 >            NoSuchFieldError error = new NoSuchFieldError(field);
1178 >            error.initCause(e);
1179 >            throw error;
1180 >        }
1181      }
1182  
1183 +    /**
1184 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1185 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1186 +     * into a jdk.
1187 +     *
1188 +     * @return a sun.misc.Unsafe
1189 +     */
1190 +    private static sun.misc.Unsafe getUnsafe() {
1191 +        try {
1192 +            return sun.misc.Unsafe.getUnsafe();
1193 +        } catch (SecurityException se) {
1194 +            try {
1195 +                return java.security.AccessController.doPrivileged
1196 +                    (new java.security
1197 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1198 +                        public sun.misc.Unsafe run() throws Exception {
1199 +                            java.lang.reflect.Field f = sun.misc
1200 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1201 +                            f.setAccessible(true);
1202 +                            return (sun.misc.Unsafe) f.get(null);
1203 +                        }});
1204 +            } catch (java.security.PrivilegedActionException e) {
1205 +                throw new RuntimeException("Could not initialize intrinsics",
1206 +                                           e.getCause());
1207 +            }
1208 +        }
1209 +    }
1210   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines