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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines