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.73 by jsr166, Sun Nov 28 21:21:03 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines