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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines