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.48 by dl, Thu May 27 16:46:48 2010 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.io.Serializable;
9 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import sun.misc.Unsafe;
12 < import java.lang.reflect.*;
10 >
11 > import java.io.Serializable;
12 > import java.util.Collection;
13 > import java.util.Collections;
14 > import java.util.List;
15 > import java.util.RandomAccess;
16 > import java.util.Map;
17 > import java.util.WeakHashMap;
18  
19   /**
20 < * Abstract base class for tasks that run within a ForkJoinPool.  A
21 < * ForkJoinTask is a thread-like entity that is much lighter weight
22 < * than a normal thread.  Huge numbers of tasks and subtasks may be
23 < * hosted by a small number of actual threads in a ForkJoinPool,
24 < * at the price of some usage limitations.
20 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
21 > * A {@code ForkJoinTask} is a thread-like entity that is much
22 > * lighter weight than a normal thread.  Huge numbers of tasks and
23 > * subtasks may be hosted by a small number of actual threads in a
24 > * ForkJoinPool, at the price of some usage limitations.
25   *
26 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
27 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
28 < * set of restrictions (that are only partially statically
29 < * enforceable) reflecting their intended use as computational tasks
30 < * calculating pure functions or operating on purely isolated objects.
31 < * The primary coordination mechanisms supported for ForkJoinTasks are
32 < * <tt>fork</tt>, that arranges asynchronous execution, and
33 < * <tt>join</tt>, that doesn't proceed until the task's result has
34 < * been computed. (Cancellation is also supported).  The computation
31 < * defined in the <tt>compute</tt> method should avoid
32 < * <tt>synchronized</tt> methods or blocks, and should minimize
33 < * blocking synchronization apart from joining other tasks or using
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.
26 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
28 > * start other subtasks.  As indicated by the name of this class,
29 > * many programs using {@code ForkJoinTask} employ only methods
30 > * {@link #fork} and {@link #join}, or derivatives such as {@link
31 > * #invokeAll}.  However, this class also provides a number of other
32 > * methods that can come into play in advanced usages, as well as
33 > * extension mechanics that allow support of new forms of fork/join
34 > * processing.
35   *
36 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
37 < * subclassed.  Instead, you subclass one of the abstract classes that
38 < * support different styles of fork/join processing.  Normally, a
39 < * concrete ForkJoinTask subclass declares fields comprising its
40 < * parameters, established in a constructor, and then defines a
41 < * <tt>compute</tt> method that somehow uses the control methods
42 < * supplied by this base class. While these methods have
43 < * <tt>public</tt> access, some of them may only be called from within
44 < * other ForkJoinTasks. Attempts to invoke them in other contexts
45 < * result in exceptions or errors including ClassCastException.  The
46 < * only way to invoke a "main" driver task is to submit it to a
47 < * ForkJoinPool. Once started, this will usually in turn start other
48 < * subtasks.
36 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37 > * The efficiency of {@code ForkJoinTask}s stems from a set of
38 > * restrictions (that are only partially statically enforceable)
39 > * reflecting their intended use as computational tasks calculating
40 > * pure functions or operating on purely isolated objects.  The
41 > * primary coordination mechanisms are {@link #fork}, that arranges
42 > * asynchronous execution, and {@link #join}, that doesn't proceed
43 > * until the task's result has been computed.  Computations should
44 > * avoid {@code synchronized} methods or blocks, and should minimize
45 > * other blocking synchronization apart from joining other tasks or
46 > * using synchronizers such as Phasers that are advertised to
47 > * cooperate with fork/join scheduling. Tasks should also not perform
48 > * blocking IO, and should ideally access variables that are
49 > * completely independent of those accessed by other running
50 > * tasks. Minor breaches of these restrictions, for example using
51 > * shared output streams, may be tolerable in practice, but frequent
52 > * use may result in poor performance, and the potential to
53 > * indefinitely stall if the number of threads not waiting for IO or
54 > * other external synchronization becomes exhausted. This usage
55 > * restriction is in part enforced by not permitting checked
56 > * exceptions such as {@code IOExceptions} to be thrown. However,
57 > * computations may still encounter unchecked exceptions, that are
58 > * rethrown to callers attempting to join them. These exceptions may
59 > * additionally include {@link RejectedExecutionException} stemming
60 > * from internal resource exhaustion, such as failure to allocate
61 > * internal task queues.
62   *
63 < * <p>Most base support methods are <tt>final</tt> because their
64 < * implementations are intrinsically tied to the underlying
65 < * lightweight task scheduling framework, and so cannot be overridden.
66 < * Developers creating new basic styles of fork/join processing should
67 < * minimally implement protected methods <tt>exec</tt>,
68 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
69 < * introducing an abstract computational method that can be
70 < * implemented in its subclasses. To support such extensions,
71 < * instances of ForkJoinTasks maintain an atomically updated
72 < * <tt>short</tt> representing user-defined control state.  Control
73 < * state is guaranteed initially to be zero, and to be negative upon
74 < * completion, but may otherwise be used for any other control
75 < * purposes, such as maintaining join counts.  The {@link
76 < * ForkJoinWorkerThread} class supports additional inspection and
77 < * tuning methods that can be useful when developing extensions.
63 > * <p>The primary method for awaiting completion and extracting
64 > * results of a task is {@link #join}, but there are several variants:
65 > * The {@link Future#get} methods support interruptible and/or timed
66 > * waits for completion and report results using {@code Future}
67 > * conventions. Method {@link #helpJoin} enables callers to actively
68 > * execute other tasks while awaiting joins, which is sometimes more
69 > * efficient but only applies when all subtasks are known to be
70 > * strictly tree-structured. Method {@link #invoke} is semantically
71 > * equivalent to {@code fork(); join()} but always attempts to begin
72 > * execution in the current thread. The "<em>quiet</em>" forms of
73 > * these methods do not extract results or report exceptions. These
74 > * may be useful when a set of tasks are being executed, and you need
75 > * to delay processing of results or exceptions until all complete.
76 > * Method {@code invokeAll} (available in multiple versions)
77 > * performs the most common form of parallel invocation: forking a set
78 > * of tasks and joining them all.
79 > *
80 > * <p>The execution status of tasks may be queried at several levels
81 > * of detail: {@link #isDone} is true if a task completed in any way
82 > * (including the case where a task was cancelled without executing);
83 > * {@link #isCompletedNormally} is true if a task completed without
84 > * cancellation or encountering an exception; {@link #isCancelled} is
85 > * true if the task was cancelled (in which case {@link #getException}
86 > * returns a {@link java.util.concurrent.CancellationException}); and
87 > * {@link #isCompletedAbnormally} is true if a task was either
88 > * cancelled or encountered an exception, in which case {@link
89 > * #getException} will return either the encountered exception or
90 > * {@link java.util.concurrent.CancellationException}.
91 > *
92 > * <p>The ForkJoinTask class is not usually directly subclassed.
93 > * Instead, you subclass one of the abstract classes that support a
94 > * particular style of fork/join processing, typically {@link
95 > * RecursiveAction} for computations that do not return results, or
96 > * {@link RecursiveTask} for those that do.  Normally, a concrete
97 > * ForkJoinTask subclass declares fields comprising its parameters,
98 > * established in a constructor, and then defines a {@code compute}
99 > * method that somehow uses the control methods supplied by this base
100 > * class. While these methods have {@code public} access (to allow
101 > * instances of different task subclasses to call each other's
102 > * methods), some of them may only be called from within other
103 > * ForkJoinTasks (as may be determined using method {@link
104 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
105 > * result in exceptions or errors, possibly including
106 > * ClassCastException.
107 > *
108 > * <p>Most base support methods are {@code final}, to prevent
109 > * overriding of implementations that are intrinsically tied to the
110 > * underlying lightweight task scheduling framework.  Developers
111 > * creating new basic styles of fork/join processing should minimally
112 > * implement {@code protected} methods {@link #exec}, {@link
113 > * #setRawResult}, and {@link #getRawResult}, while also introducing
114 > * an abstract computational method that can be implemented in its
115 > * subclasses, possibly relying on other {@code protected} methods
116 > * provided by this class.
117   *
118   * <p>ForkJoinTasks should perform relatively small amounts of
119 < * computations, othewise splitting into smaller tasks. As a very
120 < * rough rule of thumb, a task should perform more than 100 and less
121 < * than 10000 basic computational steps. If tasks are too big, then
122 < * parellelism cannot improve throughput. If too small, then memory
123 < * and internal task maintenance overhead may overwhelm processing.
119 > * computation. Large tasks should be split into smaller subtasks,
120 > * usually via recursive decomposition. As a very rough rule of thumb,
121 > * a task should perform more than 100 and less than 10000 basic
122 > * computational steps. If tasks are too big, then parallelism cannot
123 > * improve throughput. If too small, then memory and internal task
124 > * maintenance overhead may overwhelm processing.
125 > *
126 > * <p>This class provides {@code adapt} methods for {@link Runnable}
127 > * and {@link Callable}, that may be of use when mixing execution of
128 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
129 > * are of this form, consider using a pool in
130 > * {@linkplain ForkJoinPool#setAsyncMode async mode}.
131   *
132 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
133 < * be used in extensions such as remote execution frameworks. However,
134 < * it is in general safe to serialize tasks only before or after, but
135 < * not during execution. Serialization is not relied on during
136 < * execution itself.
132 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
133 > * used in extensions such as remote execution frameworks. It is
134 > * sensible to serialize tasks only before or after, but not during,
135 > * execution. Serialization is not relied on during execution itself.
136 > *
137 > * @since 1.7
138 > * @author Doug Lea
139   */
140   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
141 +
142 +    /*
143 +     * See the internal documentation of class ForkJoinPool for a
144 +     * general implementation overview.  ForkJoinTasks are mainly
145 +     * responsible for maintaining their "status" field amidst relays
146 +     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
147 +     * methods of this class are more-or-less layered into (1) basic
148 +     * status maintenance (2) execution and awaiting completion (3)
149 +     * user-level methods that additionally report results. This is
150 +     * sometimes hard to see because this file orders exported methods
151 +     * in a way that flows well in javadocs.
152 +     */
153 +
154      /**
155 <     * Status field holding all run status. We pack this into a single
156 <     * int both to minimize footprint overhead and to ensure atomicity
157 <     * (updates are via CAS).
98 <     *
99 <     * Status is initially zero, and takes on nonnegative values until
155 >     * Run control status bits packed into a single int to minimize
156 >     * footprint and to ensure atomicity (via CAS).  Status is
157 >     * initially zero, and takes on nonnegative values until
158       * completed, upon which status holds COMPLETED. CANCELLED, or
159       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
160 <     * blocking waits by other threads have SIGNAL_MASK bits set --
161 <     * bit 15 for external (nonFJ) waits, and the rest a count of
162 <     * waiting FJ threads.  (This representation relies on
163 <     * ForkJoinPool max thread limits). Completion of a stolen task
164 <     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
165 <     * though suboptimal for some purposes, we use basic builtin
166 <     * wait/notify to take advantage of "monitor inflation" in JVMs
167 <     * that we would otherwise need to emulate to avoid adding further
168 <     * per-task bookkeeping overhead. Note that bits 16-28 are
169 <     * currently unused. Also value 0x80000000 is available as spare
170 <     * completion value.
171 <     */
172 <    volatile int status; // accessed directy by pool and workers
173 <
174 <    static final int COMPLETION_MASK      = 0xe0000000;
175 <    static final int NORMAL               = 0xe0000000; // == mask
176 <    static final int CANCELLED            = 0xc0000000;
177 <    static final int EXCEPTIONAL          = 0xa0000000;
178 <    static final int SIGNAL_MASK          = 0x0000ffff;
179 <    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
180 <    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
160 >     * blocking waits by other threads have the SIGNAL bit set.
161 >     *
162 >     * Completion of a stolen task with SIGNAL set awakens any waiters
163 >     * via notifyAll. Even though suboptimal for some purposes, we use
164 >     * basic builtin wait/notify to take advantage of "monitor
165 >     * inflation" in JVMs that we would otherwise need to emulate to
166 >     * avoid adding further per-task bookkeeping overhead.  We want
167 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
168 >     * techniques, so use some odd coding idioms that tend to avoid
169 >     * them.
170 >     *
171 >     * Note that bits 1-28 are currently unused. Also value
172 >     * 0x80000000 is available as spare completion value.
173 >     */
174 >    volatile int status; // accessed directly by pool and workers
175 >
176 >    private static final int COMPLETION_MASK      = 0xe0000000;
177 >    private static final int NORMAL               = 0xe0000000; // == mask
178 >    private static final int CANCELLED            = 0xc0000000;
179 >    private static final int EXCEPTIONAL          = 0xa0000000;
180 >    private static final int SIGNAL               = 0x00000001;
181  
182      /**
183       * Table of exceptions thrown by tasks, to enable reporting by
184       * callers. Because exceptions are rare, we don't directly keep
185 <     * them with task objects, but instead us a weak ref table.  Note
185 >     * them with task objects, but instead use a weak ref table.  Note
186       * that cancellation exceptions don't appear in the table, but are
187       * instead recorded as status values.
188 <     * Todo: Use ConcurrentReferenceHashMap
188 >     * TODO: Use ConcurrentReferenceHashMap
189       */
190      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
191          Collections.synchronizedMap
192          (new WeakHashMap<ForkJoinTask<?>, Throwable>());
193  
194 <    // within-package utilities
194 >    // Maintaining completion status
195  
196      /**
197 <     * Get current worker thread, or null if not a worker thread
197 >     * Marks completion and wakes up threads waiting to join this task,
198 >     * also clearing signal request bits.
199 >     *
200 >     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
201 >     * @return status on exit
202       */
203 <    static ForkJoinWorkerThread getWorker() {
204 <        Thread t = Thread.currentThread();
205 <        return ((t instanceof ForkJoinWorkerThread)?
206 <                (ForkJoinWorkerThread)t : null);
203 >    private int setCompletion(int completion) {
204 >        int s;
205 >        while ((s = status) >= 0) {
206 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
207 >                if ((s & SIGNAL) != 0)
208 >                    synchronized (this) { notifyAll(); }
209 >                return completion;
210 >            }
211 >        }
212 >        return s;
213      }
214  
215      /**
216 <     * Get pool of current worker thread, or null if not a worker thread
216 >     * Record exception and set exceptional completion
217 >     * @return status on exit
218       */
219 <    static ForkJoinPool getWorkerPool() {
220 <        Thread t = Thread.currentThread();
221 <        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);
219 >    private int setExceptionalCompletion(Throwable rex) {
220 >        exceptionMap.put(this, rex);
221 >        return setCompletion(EXCEPTIONAL);
222      }
223  
224      /**
225 <     * Workaround for not being able to rethrow unchecked exceptions.
225 >     * Blocks a worker thread until completion. Called only by pool.
226       */
227 <    static void rethrowException(Throwable ex) {
228 <        if (ex != null)
229 <            _unsafe.throwException(ex);
227 >    final void internalAwaitDone() {
228 >        int s;
229 >        while ((s = status) >= 0) {
230 >            synchronized(this) {
231 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
232 >                    do {
233 >                        try {
234 >                            wait();
235 >                        } catch (InterruptedException ie) {
236 >                            cancelIfTerminating();
237 >                        }
238 >                    } while (status >= 0);
239 >                    break;
240 >                }
241 >            }
242 >        }
243      }
244  
168    // Setting completion status
169
245      /**
246 <     * Mark completion and wake up threads waiting to join this task.
247 <     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
246 >     * Blocks a non-worker-thread until completion.
247 >     * @return status on exit
248       */
249 <    final void setCompletion(int completion) {
250 <        ForkJoinPool pool = getWorkerPool();
251 <        if (pool != null) {
252 <            int s; // Clear signal bits while setting completion status
253 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
254 <
255 <            if ((s & SIGNAL_MASK) != 0) {
256 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
257 <                    pool.updateRunningCount(s);
258 <                synchronized(this) { notifyAll(); }
249 >    private int externalAwaitDone() {
250 >        int s;
251 >        while ((s = status) >= 0) {
252 >            synchronized(this) {
253 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
254 >                    boolean interrupted = false;
255 >                    do {
256 >                        try {
257 >                            wait();
258 >                        } catch (InterruptedException ie) {
259 >                            interrupted = true;
260 >                        }
261 >                    } while ((s = status) >= 0);
262 >                    if (interrupted)
263 >                        Thread.currentThread().interrupt();
264 >                    break;
265 >                }
266              }
267          }
268 <        else
187 <            externallySetCompletion(completion);
268 >        return s;
269      }
270  
271      /**
272 <     * Version of setCompletion for non-FJ threads.  Leaves signal
273 <     * bits for unblocked threads to adjust, and always notifies.
272 >     * Unless done, calls exec and records status if completed, but
273 >     * doesn't wait for completion otherwise.
274       */
275 <    private void externallySetCompletion(int completion) {
276 <        int s;
277 <        do;while ((s = status) >= 0 &&
278 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
279 <        synchronized(this) { notifyAll(); }
275 >    final void tryExec() {
276 >        try {
277 >            if (status < 0 || !exec())
278 >                return;
279 >        } catch (Throwable rex) {
280 >            setExceptionalCompletion(rex);
281 >            return;
282 >        }
283 >        setCompletion(NORMAL); // must be outside try block
284      }
285  
286      /**
287 <     * Sets status to indicate normal completion
287 >     * If not done and this task is next in worker queue, runs it,
288 >     * else waits for it.
289 >     * @return status on exit
290       */
291 <    final void setNormalCompletion() {
292 <        // Try typical fast case -- single CAS, no signal, not already done.
293 <        // Manually expand casStatus to improve chances of inlining it
294 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
295 <            setCompletion(NORMAL);
291 >    private int waitingJoin() {
292 >        int s = status;
293 >        if (s < 0)
294 >            return s;
295 >        Thread t = Thread.currentThread();
296 >        if (t instanceof ForkJoinWorkerThread) {
297 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
298 >            if (w.unpushTask(this)) {
299 >                boolean completed;
300 >                try {
301 >                    completed = exec();
302 >                } catch (Throwable rex) {
303 >                    return setExceptionalCompletion(rex);
304 >                }
305 >                if (completed)
306 >                    return setCompletion(NORMAL);
307 >            }
308 >            return w.pool.awaitJoin(this);
309 >        }
310 >        else
311 >            return externalAwaitDone();
312      }
313  
211    // internal waiting and notification
212
314      /**
315 <     * Performs the actual monitor wait for awaitDone
315 >     * Unless done, calls exec and records status if completed, or
316 >     * waits for completion otherwise.
317 >     * @return status on exit
318       */
319 <    private void doAwaitDone() {
320 <        // Minimize lock bias and in/de-flation effects by maximizing
321 <        // chances of waiting inside sync
319 >    private int waitingInvoke() {
320 >        int s = status;
321 >        if (s < 0)
322 >            return s;
323 >        boolean completed;
324          try {
325 <            while (status >= 0)
326 <                synchronized(this) { if (status >= 0) wait(); }
327 <        } catch (InterruptedException ie) {
223 <            onInterruptedWait();
325 >            completed = exec();
326 >        } catch (Throwable rex) {
327 >            return setExceptionalCompletion(rex);
328          }
329 +        if (completed)
330 +            return setCompletion(NORMAL);
331 +        return waitingJoin();
332      }
333  
334      /**
335 <     * Performs the actual monitor wait for awaitDone
335 >     * If this task is next in worker queue, runs it, else processes other
336 >     * tasks until complete.
337 >     * @return status on exit
338       */
339 <    private void doAwaitDone(long startTime, long nanos) {
340 <        synchronized(this) {
339 >    private int busyJoin() {
340 >        int s = status;
341 >        if (s < 0)
342 >            return s;
343 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
344 >        if (w.unpushTask(this)) {
345 >            boolean completed;
346              try {
347 <                while (status >= 0) {
348 <                    long nt = nanos - System.nanoTime() - startTime;
349 <                    if (nt <= 0)
236 <                        break;
237 <                    wait(nt / 1000000, (int)(nt % 1000000));
238 <                }
239 <            } catch (InterruptedException ie) {
240 <                onInterruptedWait();
347 >                completed = exec();
348 >            } catch (Throwable rex) {
349 >                return setExceptionalCompletion(rex);
350              }
351 +            if (completed)
352 +                return setCompletion(NORMAL);
353          }
354 +        return w.execWhileJoining(this);
355      }
356  
245    // Awaiting completion
246
357      /**
358 <     * Sets status to indicate there is joiner, then waits for join,
359 <     * surrounded with pool notifications.
250 <     * @return status upon exit
358 >     * Returns result or throws exception associated with given status.
359 >     * @param s the status
360       */
361 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
362 <        ForkJoinPool pool = w == null? null : w.pool;
363 <        int s;
364 <        while ((s = status) >= 0) {
365 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
257 <                if (pool == null || !pool.preJoin(this, maintainParallelism))
258 <                    doAwaitDone();
259 <                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
260 <                    adjustPoolCountsOnUnblock(pool);
261 <                break;
262 <            }
263 <        }
264 <        return s;
361 >    private V reportResult(int s) {
362 >        Throwable ex;
363 >        if (s < NORMAL && (ex = getException()) != null)
364 >            UNSAFE.throwException(ex);
365 >        return getRawResult();
366      }
367  
368 +    // public methods
369 +
370      /**
371 <     * Timed version of awaitDone
372 <     * @return status upon exit
371 >     * Arranges to asynchronously execute this task.  While it is not
372 >     * necessarily enforced, it is a usage error to fork a task more
373 >     * than once unless it has completed and been reinitialized.
374 >     * Subsequent modifications to the state of this task or any data
375 >     * it operates on are not necessarily consistently observable by
376 >     * any thread other than the one executing it unless preceded by a
377 >     * call to {@link #join} or related methods, or a call to {@link
378 >     * #isDone} returning {@code true}.
379 >     *
380 >     * <p>This method may be invoked only from within {@code
381 >     * ForkJoinTask} computations (as may be determined using method
382 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
383 >     * result in exceptions or errors, possibly including {@code
384 >     * ClassCastException}.
385 >     *
386 >     * @return {@code this}, to simplify usage
387       */
388 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
389 <        ForkJoinPool pool = w == null? null : w.pool;
390 <        int s;
391 <        while ((s = status) >= 0) {
275 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
276 <                long startTime = System.nanoTime();
277 <                if (pool == null || !pool.preJoin(this, false))
278 <                    doAwaitDone(startTime, nanos);
279 <                if ((s = status) >= 0) {
280 <                    adjustPoolCountsOnCancelledWait(pool);
281 <                    s = status;
282 <                }
283 <                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
284 <                    adjustPoolCountsOnUnblock(pool);
285 <                break;
286 <            }
287 <        }
288 <        return s;
388 >    public final ForkJoinTask<V> fork() {
389 >        ((ForkJoinWorkerThread) Thread.currentThread())
390 >            .pushTask(this);
391 >        return this;
392      }
393  
394      /**
395 <     * Notify pool that thread is unblocked. Called by signalled
396 <     * threads when woken by non-FJ threads (which is atypical).
395 >     * Returns the result of the computation when it {@link #isDone is done}.
396 >     * This method differs from {@link #get()} in that
397 >     * abnormal completion results in {@code RuntimeException} or
398 >     * {@code Error}, not {@code ExecutionException}.
399 >     *
400 >     * @return the computed result
401       */
402 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
403 <        int s;
297 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
298 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
299 <            pool.updateRunningCount(s);
402 >    public final V join() {
403 >        return reportResult(waitingJoin());
404      }
405  
406      /**
407 <     * Notify pool to adjust counts on cancelled or timed out wait
407 >     * Commences performing this task, awaits its completion if
408 >     * necessary, and return its result, or throws an (unchecked)
409 >     * exception if the underlying computation did so.
410 >     *
411 >     * @return the computed result
412       */
413 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
414 <        if (pool != null) {
307 <            int s;
308 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
309 <                if (casStatus(s, s - 1)) {
310 <                    pool.updateRunningCount(1);
311 <                    break;
312 <                }
313 <            }
314 <        }
315 <    }
316 <
317 <    private void onInterruptedWait() {
318 <        Thread t = Thread.currentThread();
319 <        if (t instanceof ForkJoinWorkerThread) {
320 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
321 <            if (w.isTerminating())
322 <                cancelIgnoreExceptions();
323 <        }
324 <        else { // re-interrupt
325 <            try {
326 <                t.interrupt();
327 <            } catch (SecurityException ignore) {
328 <            }
329 <        }
413 >    public final V invoke() {
414 >        return reportResult(waitingInvoke());
415      }
416  
417 <    // Recording and reporting exceptions
418 <
419 <    private void setDoneExceptionally(Throwable rex) {
420 <        exceptionMap.put(this, rex);
421 <        setCompletion(EXCEPTIONAL);
417 >    /**
418 >     * Forks the given tasks, returning when {@code isDone} holds for
419 >     * each task or an (unchecked) exception is encountered, in which
420 >     * case the exception is rethrown.  If either task encounters an
421 >     * exception, the other one may be, but is not guaranteed to be,
422 >     * cancelled.  If both tasks throw an exception, then this method
423 >     * throws one of them.  The individual status of each task may be
424 >     * checked using {@link #getException()} and related methods.
425 >     *
426 >     * <p>This method may be invoked only from within {@code
427 >     * ForkJoinTask} computations (as may be determined using method
428 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
429 >     * result in exceptions or errors, possibly including {@code
430 >     * ClassCastException}.
431 >     *
432 >     * @param t1 the first task
433 >     * @param t2 the second task
434 >     * @throws NullPointerException if any task is null
435 >     */
436 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
437 >        t2.fork();
438 >        t1.invoke();
439 >        t2.join();
440      }
441  
442      /**
443 <     * Throws the exception associated with status s;
444 <     * @throws the exception
443 >     * Forks the given tasks, returning when {@code isDone} holds for
444 >     * each task or an (unchecked) exception is encountered, in which
445 >     * case the exception is rethrown. If any task encounters an
446 >     * exception, others may be, but are not guaranteed to be,
447 >     * cancelled.  If more than one task encounters an exception, then
448 >     * this method throws any one of these exceptions.  The individual
449 >     * status of each task may be checked using {@link #getException()}
450 >     * and related methods.
451 >     *
452 >     * <p>This method may be invoked only from within {@code
453 >     * ForkJoinTask} computations (as may be determined using method
454 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
455 >     * result in exceptions or errors, possibly including {@code
456 >     * ClassCastException}.
457 >     *
458 >     * @param tasks the tasks
459 >     * @throws NullPointerException if any task is null
460       */
461 <    private void reportException(int s) {
462 <        if ((s &= COMPLETION_MASK) < NORMAL) {
463 <            if (s == CANCELLED)
464 <                throw new CancellationException();
465 <            else
466 <                rethrowException(exceptionMap.get(this));
461 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
462 >        Throwable ex = null;
463 >        int last = tasks.length - 1;
464 >        for (int i = last; i >= 0; --i) {
465 >            ForkJoinTask<?> t = tasks[i];
466 >            if (t == null) {
467 >                if (ex == null)
468 >                    ex = new NullPointerException();
469 >            }
470 >            else if (i != 0)
471 >                t.fork();
472 >            else if (t.waitingInvoke() < NORMAL && ex == null)
473 >                ex = t.getException();
474          }
475 +        for (int i = 1; i <= last; ++i) {
476 +            ForkJoinTask<?> t = tasks[i];
477 +            if (t != null) {
478 +                if (ex != null)
479 +                    t.cancel(false);
480 +                else if (t.waitingJoin() < NORMAL && ex == null)
481 +                    ex = t.getException();
482 +            }
483 +        }
484 +        if (ex != null)
485 +            UNSAFE.throwException(ex);
486      }
487  
488      /**
489 <     * Returns result or throws exception using j.u.c.Future conventions
490 <     * Only call when isDone known to be true.
489 >     * Forks all tasks in the specified collection, returning when
490 >     * {@code isDone} holds for each task or an (unchecked) exception
491 >     * is encountered.  If any task encounters an exception, others
492 >     * may be, but are not guaranteed to be, cancelled.  If more than
493 >     * one task encounters an exception, then this method throws any
494 >     * one of these exceptions.  The individual status of each task
495 >     * may be checked using {@link #getException()} and related
496 >     * methods.  The behavior of this operation is undefined if the
497 >     * specified collection is modified while the operation is in
498 >     * progress.
499 >     *
500 >     * <p>This method may be invoked only from within {@code
501 >     * ForkJoinTask} computations (as may be determined using method
502 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
503 >     * result in exceptions or errors, possibly including {@code
504 >     * ClassCastException}.
505 >     *
506 >     * @param tasks the collection of tasks
507 >     * @return the tasks argument, to simplify usage
508 >     * @throws NullPointerException if tasks or any element are null
509       */
510 <    private V reportFutureResult()
511 <        throws ExecutionException, InterruptedException {
512 <        int s = status & COMPLETION_MASK;
513 <        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();
510 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
511 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
512 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
513 >            return tasks;
514          }
515 <        return getRawResult();
515 >        @SuppressWarnings("unchecked")
516 >        List<? extends ForkJoinTask<?>> ts =
517 >            (List<? extends ForkJoinTask<?>>) tasks;
518 >        Throwable ex = null;
519 >        int last = ts.size() - 1;
520 >        for (int i = last; i >= 0; --i) {
521 >            ForkJoinTask<?> t = ts.get(i);
522 >            if (t == null) {
523 >                if (ex == null)
524 >                    ex = new NullPointerException();
525 >            }
526 >            else if (i != 0)
527 >                t.fork();
528 >            else if (t.waitingInvoke() < NORMAL && ex == null)
529 >                ex = t.getException();
530 >        }
531 >        for (int i = 1; i <= last; ++i) {
532 >            ForkJoinTask<?> t = ts.get(i);
533 >            if (t != null) {
534 >                if (ex != null)
535 >                    t.cancel(false);
536 >                else if (t.waitingJoin() < NORMAL && ex == null)
537 >                    ex = t.getException();
538 >            }
539 >        }
540 >        if (ex != null)
541 >            UNSAFE.throwException(ex);
542 >        return tasks;
543      }
544  
545      /**
546 <     * Returns result or throws exception using j.u.c.Future conventions
547 <     * with timeouts
546 >     * Attempts to cancel execution of this task. This attempt will
547 >     * fail if the task has already completed, has already been
548 >     * cancelled, or could not be cancelled for some other reason. If
549 >     * successful, and this task has not started when cancel is
550 >     * called, execution of this task is suppressed, {@link
551 >     * #isCancelled} will report true, and {@link #join} will result
552 >     * in a {@code CancellationException} being thrown.
553 >     *
554 >     * <p>This method may be overridden in subclasses, but if so, must
555 >     * still ensure that these minimal properties hold. In particular,
556 >     * the {@code cancel} method itself must not throw exceptions.
557 >     *
558 >     * <p>This method is designed to be invoked by <em>other</em>
559 >     * tasks. To terminate the current task, you can just return or
560 >     * throw an unchecked exception from its computation method, or
561 >     * invoke {@link #completeExceptionally}.
562 >     *
563 >     * @param mayInterruptIfRunning this value is ignored in the
564 >     * default implementation because tasks are not
565 >     * cancelled via interruption
566 >     *
567 >     * @return {@code true} if this task is now cancelled
568       */
569 <    private V reportTimedFutureResult()
570 <        throws InterruptedException, ExecutionException, TimeoutException {
571 <        Throwable ex;
378 <        int s = status & COMPLETION_MASK;
379 <        if (s == NORMAL)
380 <            return getRawResult();
381 <        if (s == CANCELLED)
382 <            throw new CancellationException();
383 <        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
384 <            throw new ExecutionException(ex);
385 <        if (Thread.interrupted())
386 <            throw new InterruptedException();
387 <        throw new TimeoutException();
569 >    public boolean cancel(boolean mayInterruptIfRunning) {
570 >        setCompletion(CANCELLED);
571 >        return (status & COMPLETION_MASK) == CANCELLED;
572      }
573  
390    // internal execution methods
391
574      /**
575 <     * Calls exec, recording completion, and rethrowing exception if
576 <     * encountered. Caller should normally check status before calling
395 <     * @return true if completed normally
575 >     * Cancels, ignoring any exceptions it throws. Used during worker
576 >     * and pool shutdown.
577       */
578 <    private boolean tryExec() {
579 <        try { // try block must contain only call to exec
580 <            if (!exec())
581 <                return false;
401 <        } catch (Throwable rex) {
402 <            setDoneExceptionally(rex);
403 <            rethrowException(rex);
404 <            return false; // not reached
578 >    final void cancelIgnoringExceptions() {
579 >        try {
580 >            cancel(false);
581 >        } catch (Throwable ignore) {
582          }
406        setNormalCompletion();
407        return true;
583      }
584  
585      /**
586 <     * Main execution method used by worker threads. Invokes
412 <     * base computation unless already complete
586 >     * Cancels ignoring exceptions if worker is terminating
587       */
588 <    final void quietlyExec() {
589 <        if (status >= 0) {
588 >    private void cancelIfTerminating() {
589 >        Thread t = Thread.currentThread();
590 >        if ((t instanceof ForkJoinWorkerThread) &&
591 >            ((ForkJoinWorkerThread) t).isTerminating()) {
592              try {
593 <                if (!exec())
594 <                    return;
419 <            } catch(Throwable rex) {
420 <                setDoneExceptionally(rex);
421 <                return;
593 >                cancel(false);
594 >            } catch (Throwable ignore) {
595              }
423            setNormalCompletion();
596          }
597      }
598  
599 +    public final boolean isDone() {
600 +        return status < 0;
601 +    }
602 +
603 +    public final boolean isCancelled() {
604 +        return (status & COMPLETION_MASK) == CANCELLED;
605 +    }
606 +
607      /**
608 <     * Calls exec, recording but not rethrowing exception
609 <     * Caller should normally check status before calling
610 <     * @return true if completed normally
608 >     * Returns {@code true} if this task threw an exception or was cancelled.
609 >     *
610 >     * @return {@code true} if this task threw an exception or was cancelled
611       */
612 <    private boolean tryQuietlyInvoke() {
613 <        try {
434 <            if (!exec())
435 <                return false;
436 <        } catch (Throwable rex) {
437 <            setDoneExceptionally(rex);
438 <            return false;
439 <        }
440 <        setNormalCompletion();
441 <        return true;
612 >    public final boolean isCompletedAbnormally() {
613 >        return (status & COMPLETION_MASK) < NORMAL;
614      }
615  
616      /**
617 <     * Cancel, ignoring any exceptions it throws
617 >     * Returns {@code true} if this task completed without throwing an
618 >     * exception and was not cancelled.
619 >     *
620 >     * @return {@code true} if this task completed without throwing an
621 >     * exception and was not cancelled
622       */
623 <    final void cancelIgnoreExceptions() {
624 <        try {
449 <            cancel(false);
450 <        } catch(Throwable ignore) {
451 <        }
623 >    public final boolean isCompletedNormally() {
624 >        return (status & COMPLETION_MASK) == NORMAL;
625      }
626  
627 <    // public methods
627 >    /**
628 >     * Returns the exception thrown by the base computation, or a
629 >     * {@code CancellationException} if cancelled, or {@code null} if
630 >     * none or if the method has not yet completed.
631 >     *
632 >     * @return the exception, or {@code null} if none
633 >     */
634 >    public final Throwable getException() {
635 >        int s = status & COMPLETION_MASK;
636 >        return ((s >= NORMAL)    ? null :
637 >                (s == CANCELLED) ? new CancellationException() :
638 >                exceptionMap.get(this));
639 >    }
640  
641      /**
642 <     * Arranges to asynchronously execute this task.  While it is not
643 <     * necessarily enforced, it is a usage error to fork a task more
644 <     * than once unless it has completed and been reinitialized.  This
645 <     * method may be invoked only from within other ForkJoinTask
646 <     * computations. Attempts to invoke in other contexts result in
647 <     * exceptions or errors including ClassCastException.
642 >     * Completes this task abnormally, and if not already aborted or
643 >     * cancelled, causes it to throw the given exception upon
644 >     * {@code join} and related operations. This method may be used
645 >     * to induce exceptions in asynchronous tasks, or to force
646 >     * completion of tasks that would not otherwise complete.  Its use
647 >     * in other situations is discouraged.  This method is
648 >     * overridable, but overridden versions must invoke {@code super}
649 >     * implementation to maintain guarantees.
650 >     *
651 >     * @param ex the exception to throw. If this exception is not a
652 >     * {@code RuntimeException} or {@code Error}, the actual exception
653 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
654       */
655 <    public final void fork() {
656 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
655 >    public void completeExceptionally(Throwable ex) {
656 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
657 >                                 (ex instanceof Error) ? ex :
658 >                                 new RuntimeException(ex));
659      }
660  
661      /**
662 <     * Returns the result of the computation when it is ready.
663 <     * This method differs from <tt>get</tt> in that abnormal
664 <     * completion results in RuntimeExceptions or Errors, not
665 <     * ExecutionExceptions.
662 >     * Completes this task, and if not already aborted or cancelled,
663 >     * returning a {@code null} result upon {@code join} and related
664 >     * operations. This method may be used to provide results for
665 >     * asynchronous tasks, or to provide alternative handling for
666 >     * tasks that would not otherwise complete normally. Its use in
667 >     * other situations is discouraged. This method is
668 >     * overridable, but overridden versions must invoke {@code super}
669 >     * implementation to maintain guarantees.
670       *
671 <     * @return the computed result
671 >     * @param value the result value for this task
672       */
673 <    public final V join() {
674 <        ForkJoinWorkerThread w = getWorker();
675 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
676 <            reportException(awaitDone(w, true));
677 <        return getRawResult();
673 >    public void complete(V value) {
674 >        try {
675 >            setRawResult(value);
676 >        } catch (Throwable rex) {
677 >            setExceptionalCompletion(rex);
678 >            return;
679 >        }
680 >        setCompletion(NORMAL);
681      }
682  
683      public final V get() throws InterruptedException, ExecutionException {
684 <        ForkJoinWorkerThread w = getWorker();
685 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
686 <            awaitDone(w, true);
687 <        return reportFutureResult();
684 >        int s = waitingJoin() & COMPLETION_MASK;
685 >        if (Thread.interrupted())
686 >            throw new InterruptedException();
687 >        if (s < NORMAL) {
688 >            Throwable ex;
689 >            if (s == CANCELLED)
690 >                throw new CancellationException();
691 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
692 >                throw new ExecutionException(ex);
693 >        }
694 >        return getRawResult();
695      }
696  
697      public final V get(long timeout, TimeUnit unit)
698          throws InterruptedException, ExecutionException, TimeoutException {
699 <        ForkJoinWorkerThread w = getWorker();
700 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
701 <            awaitDone(w, unit.toNanos(timeout));
702 <        return reportTimedFutureResult();
699 >        Thread t = Thread.currentThread();
700 >        ForkJoinPool pool;
701 >        if (t instanceof ForkJoinWorkerThread) {
702 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
703 >            if (status >= 0 && w.unpushTask(this))
704 >                tryExec();
705 >            pool = w.pool;
706 >        }
707 >        else
708 >            pool = null;
709 >        /*
710 >         * Timed wait loop intermixes cases for fj (pool != null) and
711 >         * non FJ threads. For FJ, decrement pool count but don't try
712 >         * for replacement; increment count on completion. For non-FJ,
713 >         * deal with interrupts. This is messy, but a little less so
714 >         * than is splitting the FJ and nonFJ cases.
715 >         */
716 >        boolean interrupted = false;
717 >        boolean dec = false; // true if pool count decremented
718 >        for (;;) {
719 >            if (Thread.interrupted() && pool == null) {
720 >                interrupted = true;
721 >                break;
722 >            }
723 >            int s = status;
724 >            if (s < 0)
725 >                break;
726 >            if (UNSAFE.compareAndSwapInt(this, statusOffset,
727 >                                         s, s | SIGNAL)) {
728 >                long startTime = System.nanoTime();
729 >                long nanos = unit.toNanos(timeout);
730 >                long nt; // wait time
731 >                while (status >= 0 &&
732 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
733 >                    if (pool != null && !dec)
734 >                        dec = pool.tryDecrementRunningCount();
735 >                    else {
736 >                        long ms = nt / 1000000;
737 >                        int ns = (int) (nt % 1000000);
738 >                        try {
739 >                            synchronized(this) {
740 >                                if (status >= 0)
741 >                                    wait(ms, ns);
742 >                            }
743 >                        } catch (InterruptedException ie) {
744 >                            if (pool != null)
745 >                                cancelIfTerminating();
746 >                            else {
747 >                                interrupted = true;
748 >                                break;
749 >                            }
750 >                        }
751 >                    }
752 >                }
753 >                break;
754 >            }
755 >        }
756 >        if (pool != null && dec)
757 >            pool.updateRunningCount(1);
758 >        if (interrupted)
759 >            throw new InterruptedException();
760 >        int es = status & COMPLETION_MASK;
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 <     * Possibly executes other tasks until this task is ready, then
774 <     * returns the result of the computation.  This method may be more
775 <     * efficient than <tt>join</tt>, but is only applicable when there
776 <     * are no potemtial dependencies between continuation of the
777 <     * current task and that of any other task that might be executed
778 <     * while helping. (This usually holds for pure divide-and-conquer
779 <     * tasks).
773 >     * Possibly executes other tasks until this task {@link #isDone is
774 >     * done}, then returns the result of the computation.  This method
775 >     * may be more efficient than {@code join}, but is only applicable
776 >     * when there are no potential dependencies between continuation
777 >     * of the current task and that of any other task that might be
778 >     * executed while helping. (This usually holds for pure
779 >     * divide-and-conquer tasks).
780 >     *
781 >     * <p>This method may be invoked only from within {@code
782 >     * ForkJoinTask} computations (as may be determined using method
783 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
784 >     * result in exceptions or errors, possibly including {@code
785 >     * ClassCastException}.
786 >     *
787       * @return the computed result
788       */
789      public final V helpJoin() {
790 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
510 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
511 <            reportException(w.helpJoinTask(this));
512 <        return getRawResult();
790 >        return reportResult(busyJoin());
791      }
792  
793      /**
794 <     * Performs this task, awaits its completion if necessary, and
795 <     * return its result.
796 <     * @throws Throwable (a RuntimeException, Error, or unchecked
797 <     * exception) if the underlying computation did so.
798 <     * @return the computed result
794 >     * Possibly executes other tasks until this task {@link #isDone is
795 >     * done}.  This method may be useful when processing collections
796 >     * of tasks when some have been cancelled or otherwise known to
797 >     * have aborted.
798 >     *
799 >     * <p>This method may be invoked only from within {@code
800 >     * ForkJoinTask} computations (as may be determined using method
801 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
802 >     * result in exceptions or errors, possibly including {@code
803 >     * ClassCastException}.
804       */
805 <    public final V invoke() {
806 <        if (status >= 0 && tryExec())
524 <            return getRawResult();
525 <        else
526 <            return join();
805 >    public final void quietlyHelpJoin() {
806 >        busyJoin();
807      }
808  
809      /**
# Line 533 | Line 813 | public abstract class ForkJoinTask<V> im
813       * known to have aborted.
814       */
815      public final void quietlyJoin() {
816 <        if (status >= 0) {
537 <            ForkJoinWorkerThread w = getWorker();
538 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
816 >        waitingJoin();
817      }
818  
819      /**
820 <     * Possibly executes other tasks until this task is ready.
820 >     * Commences performing this task and awaits its completion if
821 >     * necessary, without returning its result or throwing an
822 >     * exception. This method may be useful when processing
823 >     * collections of tasks when some have been cancelled or otherwise
824 >     * known to have aborted.
825       */
826 <    public final void quietlyHelpJoin() {
827 <        if (status >= 0) {
548 <            ForkJoinWorkerThread w =
549 <                (ForkJoinWorkerThread)(Thread.currentThread());
550 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
551 <                w.helpJoinTask(this);
552 <        }
826 >    public final void quietlyInvoke() {
827 >        waitingInvoke();
828      }
829  
830      /**
831 <     * Performs this task and awaits its completion if necessary,
832 <     * without returning its result or throwing an exception. This
833 <     * method may be useful when processing collections of tasks when
834 <     * some have been cancelled or otherwise known to have aborted.
831 >     * Possibly executes tasks until the pool hosting the current task
832 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
833 >     * be of use in designs in which many tasks are forked, but none
834 >     * are explicitly joined, instead executing them until all are
835 >     * processed.
836 >     *
837 >     * <p>This method may be invoked only from within {@code
838 >     * ForkJoinTask} computations (as may be determined using method
839 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
840 >     * result in exceptions or errors, possibly including {@code
841 >     * ClassCastException}.
842       */
843 <    public final void quietlyInvoke() {
844 <        if (status >= 0 && !tryQuietlyInvoke())
845 <            quietlyJoin();
843 >    public static void helpQuiesce() {
844 >        ((ForkJoinWorkerThread) Thread.currentThread())
845 >            .helpQuiescePool();
846      }
847  
848      /**
849 <     * Returns true if the computation performed by this task has
850 <     * completed (or has been cancelled).
851 <     * @return true if this computation has completed
849 >     * Resets the internal bookkeeping state of this task, allowing a
850 >     * subsequent {@code fork}. This method allows repeated reuse of
851 >     * this task, but only if reuse occurs when this task has either
852 >     * never been forked, or has been forked, then completed and all
853 >     * outstanding joins of this task have also completed. Effects
854 >     * under any other usage conditions are not guaranteed.
855 >     * This method may be useful when executing
856 >     * pre-constructed trees of subtasks in loops.
857       */
858 <    public final boolean isDone() {
859 <        return status < 0;
858 >    public void reinitialize() {
859 >        if ((status & COMPLETION_MASK) == 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 >     * ForkJoinTask} 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 >     * ForkJoinTask} 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 >     * ForkJoinTask} 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 >     * ForkJoinTask} 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 >     * ForkJoinTask} 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 >     * ForkJoinTask} 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.
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.
1163 >     *
1164       * @param s the stream
1165       */
1166      private void readObject(java.io.ObjectInputStream s)
1167          throws java.io.IOException, ClassNotFoundException {
1168          s.defaultReadObject();
1169 <        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1169 >        status |= SIGNAL; // conservatively set external signal
1170          Object ex = s.readObject();
1171          if (ex != null)
1172 <            setDoneExceptionally((Throwable)ex);
1172 >            setExceptionalCompletion((Throwable) ex);
1173      }
1174  
1175 <    // Temporary Unsafe mechanics for preliminary release
1175 >    // Unsafe mechanics
1176  
1177 <    static final Unsafe _unsafe;
1178 <    static final long statusOffset;
1177 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1178 >    private static final long statusOffset =
1179 >        objectFieldOffset("status", ForkJoinTask.class);
1180  
1181 <    static {
1181 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1182          try {
1183 <            if (ForkJoinTask.class.getClassLoader() != null) {
1184 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1185 <                f.setAccessible(true);
1186 <                _unsafe = (Unsafe)f.get(null);
1187 <            }
1188 <            else
1189 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
920 <                (ForkJoinTask.class.getDeclaredField("status"));
921 <        } catch (Exception ex) { throw new Error(ex); }
1183 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1184 >        } catch (NoSuchFieldException e) {
1185 >            // Convert Exception to corresponding Error
1186 >            NoSuchFieldError error = new NoSuchFieldError(field);
1187 >            error.initCause(e);
1188 >            throw error;
1189 >        }
1190      }
1191  
1192 +    /**
1193 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1194 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1195 +     * into a jdk.
1196 +     *
1197 +     * @return a sun.misc.Unsafe
1198 +     */
1199 +    private static sun.misc.Unsafe getUnsafe() {
1200 +        try {
1201 +            return sun.misc.Unsafe.getUnsafe();
1202 +        } catch (SecurityException se) {
1203 +            try {
1204 +                return java.security.AccessController.doPrivileged
1205 +                    (new java.security
1206 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1207 +                        public sun.misc.Unsafe run() throws Exception {
1208 +                            java.lang.reflect.Field f = sun.misc
1209 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1210 +                            f.setAccessible(true);
1211 +                            return (sun.misc.Unsafe) f.get(null);
1212 +                        }});
1213 +            } catch (java.security.PrivilegedActionException e) {
1214 +                throw new RuntimeException("Could not initialize intrinsics",
1215 +                                           e.getCause());
1216 +            }
1217 +        }
1218 +    }
1219   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines