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.86 by dl, Mon Feb 20 18:20:06 2012 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8   import java.io.Serializable;
9 < import java.util.*;
10 < import java.util.concurrent.*;
11 < import java.util.concurrent.atomic.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
9 > import java.util.Collection;
10 > import java.util.List;
11 > import java.util.RandomAccess;
12 > import java.lang.ref.WeakReference;
13 > import java.lang.ref.ReferenceQueue;
14 > import java.util.concurrent.Callable;
15 > import java.util.concurrent.CancellationException;
16 > import java.util.concurrent.ExecutionException;
17 > import java.util.concurrent.Future;
18 > import java.util.concurrent.RejectedExecutionException;
19 > import java.util.concurrent.RunnableFuture;
20 > import java.util.concurrent.TimeUnit;
21 > import java.util.concurrent.TimeoutException;
22 > import java.util.concurrent.locks.ReentrantLock;
23 > import java.lang.reflect.Constructor;
24  
25   /**
26 < * Abstract base class for tasks that run within a ForkJoinPool.  A
27 < * ForkJoinTask is a thread-like entity that is much lighter weight
28 < * than a normal thread.  Huge numbers of tasks and subtasks may be
29 < * hosted by a small number of actual threads in a ForkJoinPool,
30 < * at the price of some usage limitations.
31 < *
32 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
33 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
34 < * set of restrictions (that are only partially statically
35 < * enforceable) reflecting their intended use as computational tasks
36 < * calculating pure functions or operating on purely isolated objects.
37 < * The primary coordination mechanisms supported for ForkJoinTasks are
38 < * <tt>fork</tt>, that arranges asynchronous execution, and
39 < * <tt>join</tt>, that doesn't proceed until the task's result has
40 < * been computed. (Cancellation is also supported).  The computation
41 < * defined in the <tt>compute</tt> method should avoid
42 < * <tt>synchronized</tt> methods or blocks, and should minimize
43 < * blocking synchronization apart from joining other tasks or using
44 < * synchronizers such as Phasers that are advertised to cooperate with
45 < * fork/join scheduling. Tasks should also not perform blocking IO,
46 < * and should ideally access variables that are completely independent
47 < * of those accessed by other running tasks. Minor breaches of these
48 < * restrictions, for example using shared output streams, may be
49 < * tolerable in practice, but frequent use may result in poor
50 < * performance, and the potential to indefinitely stall if the number
51 < * of threads not waiting for external synchronization becomes
52 < * exhausted. This usage restriction is in part enforced by not
53 < * permitting checked exceptions such as IOExceptions to be
26 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
27 > * A {@code ForkJoinTask} is a thread-like entity that is much
28 > * lighter weight than a normal thread.  Huge numbers of tasks and
29 > * subtasks may be hosted by a small number of actual threads in a
30 > * ForkJoinPool, at the price of some usage limitations.
31 > *
32 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
33 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
34 > * start other subtasks.  As indicated by the name of this class,
35 > * many programs using {@code ForkJoinTask} employ only methods
36 > * {@link #fork} and {@link #join}, or derivatives such as {@link
37 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
38 > * provides a number of other methods that can come into play in
39 > * advanced usages, as well as extension mechanics that allow
40 > * support of new forms of fork/join processing.
41 > *
42 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
43 > * The efficiency of {@code ForkJoinTask}s stems from a set of
44 > * restrictions (that are only partially statically enforceable)
45 > * reflecting their main use as computational tasks calculating pure
46 > * functions or operating on purely isolated objects.  The primary
47 > * coordination mechanisms are {@link #fork}, that arranges
48 > * asynchronous execution, and {@link #join}, that doesn't proceed
49 > * until the task's result has been computed.  Computations should
50 > * ideally avoid {@code synchronized} methods or blocks, and should
51 > * minimize other blocking synchronization apart from joining other
52 > * tasks or using synchronizers such as Phasers that are advertised to
53 > * cooperate with fork/join scheduling. Subdividable tasks should also
54 > * not perform blocking IO, and should ideally access variables that
55 > * are completely independent of those accessed by other running
56 > * tasks. These guidelines are loosely enforced by not permitting
57 > * checked exceptions such as {@code IOExceptions} to be
58   * thrown. However, computations may still encounter unchecked
59 < * exceptions, that are rethrown to callers attempting join
60 < * them. These exceptions may additionally include
61 < * RejectedExecutionExceptions stemming from internal resource
62 < * exhaustion such as failure to allocate internal task queues.
63 < *
64 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
65 < * subclassed.  Instead, you subclass one of the abstract classes that
66 < * support different styles of fork/join processing.  Normally, a
67 < * concrete ForkJoinTask subclass declares fields comprising its
68 < * parameters, established in a constructor, and then defines a
69 < * <tt>compute</tt> method that somehow uses the control methods
70 < * supplied by this base class. While these methods have
71 < * <tt>public</tt> access, some of them may only be called from within
72 < * other ForkJoinTasks. Attempts to invoke them in other contexts
73 < * result in exceptions or errors including ClassCastException.  The
74 < * only way to invoke a "main" driver task is to submit it to a
75 < * ForkJoinPool. Once started, this will usually in turn start other
76 < * subtasks.
77 < *
78 < * <p>Most base support methods are <tt>final</tt> because their
79 < * implementations are intrinsically tied to the underlying
80 < * lightweight task scheduling framework, and so cannot be overridden.
81 < * Developers creating new basic styles of fork/join processing should
82 < * minimally implement protected methods <tt>exec</tt>,
83 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
84 < * introducing an abstract computational method that can be
85 < * implemented in its subclasses. To support such extensions,
86 < * instances of ForkJoinTasks maintain an atomically updated
87 < * <tt>short</tt> representing user-defined control state.  Control
88 < * state is guaranteed initially to be zero, and to be negative upon
89 < * completion, but may otherwise be used for any other control
90 < * purposes, such as maintaining join counts.  The {@link
91 < * ForkJoinWorkerThread} class supports additional inspection and
92 < * tuning methods that can be useful when developing extensions.
59 > * exceptions, that are rethrown to callers attempting to join
60 > * them. These exceptions may additionally include {@link
61 > * RejectedExecutionException} stemming from internal resource
62 > * exhaustion, such as failure to allocate internal task
63 > * queues. Rethrown exceptions behave in the same way as regular
64 > * exceptions, but, when possible, contain stack traces (as displayed
65 > * for example using {@code ex.printStackTrace()}) of both the thread
66 > * that initiated the computation as well as the thread actually
67 > * encountering the exception; minimally only the latter.
68 > *
69 > * <p>It is possible to define and use ForkJoinTasks that may block,
70 > * but doing do requires three further considerations: (1) Completion
71 > * of few if any <em>other</em> tasks should be dependent on a task
72 > * that blocks on external synchronization or IO. Event-style async
73 > * tasks that are never joined often fall into this category.  (2) To
74 > * minimize resource impact, tasks should be small; ideally performing
75 > * only the (possibly) blocking action. (3) Unless the {@link
76 > * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
77 > * blocked tasks is known to be less than the pool's {@link
78 > * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
79 > * enough threads will be available to ensure progress or good
80 > * performance.
81 > *
82 > * <p>The primary method for awaiting completion and extracting
83 > * results of a task is {@link #join}, but there are several variants:
84 > * The {@link Future#get} methods support interruptible and/or timed
85 > * waits for completion and report results using {@code Future}
86 > * conventions. Method {@link #invoke} is semantically
87 > * equivalent to {@code fork(); join()} but always attempts to begin
88 > * execution in the current thread. The "<em>quiet</em>" forms of
89 > * these methods do not extract results or report exceptions. These
90 > * may be useful when a set of tasks are being executed, and you need
91 > * to delay processing of results or exceptions until all complete.
92 > * Method {@code invokeAll} (available in multiple versions)
93 > * performs the most common form of parallel invocation: forking a set
94 > * of tasks and joining them all.
95 > *
96 > * <p>In the most typical usages, a fork-join pair act like a call
97 > * (fork) and return (join) from a parallel recursive function. As is
98 > * the case with other forms of recursive calls, returns (joins)
99 > * should be performed innermost-first. For example, {@code a.fork();
100 > * b.fork(); b.join(); a.join();} is likely to be substantially more
101 > * efficient than joining {@code a} before {@code b}.
102 > *
103 > * <p>The execution status of tasks may be queried at several levels
104 > * of detail: {@link #isDone} is true if a task completed in any way
105 > * (including the case where a task was cancelled without executing);
106 > * {@link #isCompletedNormally} is true if a task completed without
107 > * cancellation or encountering an exception; {@link #isCancelled} is
108 > * true if the task was cancelled (in which case {@link #getException}
109 > * returns a {@link java.util.concurrent.CancellationException}); and
110 > * {@link #isCompletedAbnormally} is true if a task was either
111 > * cancelled or encountered an exception, in which case {@link
112 > * #getException} will return either the encountered exception or
113 > * {@link java.util.concurrent.CancellationException}.
114 > *
115 > * <p>The ForkJoinTask class is not usually directly subclassed.
116 > * Instead, you subclass one of the abstract classes that support a
117 > * particular style of fork/join processing, typically {@link
118 > * RecursiveAction} for computations that do not return results, or
119 > * {@link RecursiveTask} for those that do.  Normally, a concrete
120 > * ForkJoinTask subclass declares fields comprising its parameters,
121 > * established in a constructor, and then defines a {@code compute}
122 > * method that somehow uses the control methods supplied by this base
123 > * class. While these methods have {@code public} access (to allow
124 > * instances of different task subclasses to call each other's
125 > * methods), some of them may only be called from within other
126 > * ForkJoinTasks (as may be determined using method {@link
127 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
128 > * result in exceptions or errors, possibly including
129 > * {@code ClassCastException}.
130 > *
131 > * <p>Method {@link #join} and its variants are appropriate for use
132 > * only when completion dependencies are acyclic; that is, the
133 > * parallel computation can be described as a directed acyclic graph
134 > * (DAG). Otherwise, executions may encounter a form of deadlock as
135 > * tasks cyclically wait for each other.  However, this framework
136 > * supports other methods and techniques (for example the use of
137 > * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
138 > * may be of use in constructing custom subclasses for problems that
139 > * are not statically structured as DAGs. To support such usages a
140 > * ForkJoinTask may be atomically <em>marked</em> using {@link
141 > * #markForkJoinTask} and checked for marking using {@link
142 > * #isMarkedForkJoinTask}. The ForkJoinTask implementation does not
143 > * use these {@code protected} methods or marks for any purpose, but
144 > * they may be of use in the construction of specialized subclasses.
145 > * For example, parallel graph traversals can use the supplied methods
146 > * to avoid revisiting nodes/tasks that have already been processed.
147 > * Also, completion based designs can use them to record that one
148 > * subtask has completed. (Method names for marking are bulky in part
149 > * to encourage definition of methods that reflect their usage
150 > * patterns.)
151 > *
152 > * <p>Most base support methods are {@code final}, to prevent
153 > * overriding of implementations that are intrinsically tied to the
154 > * underlying lightweight task scheduling framework.  Developers
155 > * creating new basic styles of fork/join processing should minimally
156 > * implement {@code protected} methods {@link #exec}, {@link
157 > * #setRawResult}, and {@link #getRawResult}, while also introducing
158 > * an abstract computational method that can be implemented in its
159 > * subclasses, possibly relying on other {@code protected} methods
160 > * provided by this class.
161   *
162   * <p>ForkJoinTasks should perform relatively small amounts of
163 < * computations, othewise splitting into smaller tasks. As a very
164 < * rough rule of thumb, a task should perform more than 100 and less
165 < * than 10000 basic computational steps. If tasks are too big, then
166 < * parellelism cannot improve throughput. If too small, then memory
167 < * and internal task maintenance overhead may overwhelm processing.
168 < *
169 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
170 < * be used in extensions such as remote execution frameworks. However,
171 < * it is in general safe to serialize tasks only before or after, but
172 < * not during execution. Serialization is not relied on during
173 < * execution itself.
163 > * computation. Large tasks should be split into smaller subtasks,
164 > * usually via recursive decomposition. As a very rough rule of thumb,
165 > * a task should perform more than 100 and less than 10000 basic
166 > * computational steps, and should avoid indefinite looping. If tasks
167 > * are too big, then parallelism cannot improve throughput. If too
168 > * small, then memory and internal task maintenance overhead may
169 > * overwhelm processing.
170 > *
171 > * <p>This class provides {@code adapt} methods for {@link Runnable}
172 > * and {@link Callable}, that may be of use when mixing execution of
173 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
174 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
175 > *
176 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
177 > * used in extensions such as remote execution frameworks. It is
178 > * sensible to serialize tasks only before or after, but not during,
179 > * execution. Serialization is not relied on during execution itself.
180 > *
181 > * @since 1.7
182 > * @author Doug Lea
183   */
184   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
94    /**
95     * Status field holding all run status. We pack this into a single
96     * int both to minimize footprint overhead and to ensure atomicity
97     * (updates are via CAS).
98     *
99     * Status is initially zero, and takes on nonnegative values until
100     * completed, upon which status holds COMPLETED. CANCELLED, or
101     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
102     * blocking waits by other threads have SIGNAL_MASK bits set --
103     * bit 15 for external (nonFJ) waits, and the rest a count of
104     * waiting FJ threads.  (This representation relies on
105     * ForkJoinPool max thread limits). Completion of a stolen task
106     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
107     * though suboptimal for some purposes, we use basic builtin
108     * wait/notify to take advantage of "monitor inflation" in JVMs
109     * that we would otherwise need to emulate to avoid adding further
110     * per-task bookkeeping overhead. Note that bits 16-28 are
111     * currently unused. Also value 0x80000000 is available as spare
112     * completion value.
113     */
114    volatile int status; // accessed directy by pool and workers
115
116    static final int COMPLETION_MASK      = 0xe0000000;
117    static final int NORMAL               = 0xe0000000; // == mask
118    static final int CANCELLED            = 0xc0000000;
119    static final int EXCEPTIONAL          = 0xa0000000;
120    static final int SIGNAL_MASK          = 0x0000ffff;
121    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
122    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
185  
186 <    /**
187 <     * Table of exceptions thrown by tasks, to enable reporting by
188 <     * callers. Because exceptions are rare, we don't directly keep
189 <     * them with task objects, but instead us a weak ref table.  Note
190 <     * that cancellation exceptions don't appear in the table, but are
191 <     * instead recorded as status values.
192 <     * Todo: Use ConcurrentReferenceHashMap
186 >    /*
187 >     * See the internal documentation of class ForkJoinPool for a
188 >     * general implementation overview.  ForkJoinTasks are mainly
189 >     * responsible for maintaining their "status" field amidst relays
190 >     * to methods in ForkJoinWorkerThread and ForkJoinPool.
191 >     *
192 >     * The methods of this class are more-or-less layered into
193 >     * (1) basic status maintenance
194 >     * (2) execution and awaiting completion
195 >     * (3) user-level methods that additionally report results.
196 >     * This is sometimes hard to see because this file orders exported
197 >     * methods in a way that flows well in javadocs.
198 >     */
199 >
200 >    /*
201 >     * The status field holds run control status bits packed into a
202 >     * single int to minimize footprint and to ensure atomicity (via
203 >     * CAS).  Status is initially zero, and takes on nonnegative
204 >     * values until completed, upon which status (anded with
205 >     * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks
206 >     * undergoing blocking waits by other threads have the SIGNAL bit
207 >     * set.  Completion of a stolen task with SIGNAL set awakens any
208 >     * waiters via notifyAll. Even though suboptimal for some
209 >     * purposes, we use basic builtin wait/notify to take advantage of
210 >     * "monitor inflation" in JVMs that we would otherwise need to
211 >     * emulate to avoid adding further per-task bookkeeping overhead.
212 >     * We want these monitors to be "fat", i.e., not use biasing or
213 >     * thin-lock techniques, so use some odd coding idioms that tend
214 >     * to avoid them, mainly by arranging that every synchronized
215 >     * block performs a wait, notifyAll or both.
216 >     */
217 >
218 >    /** The run status of this task */
219 >    volatile int status; // accessed directly by pool and workers
220 >    static final int DONE_MASK   = 0xf0000000;  // mask out non-completion bits
221 >    static final int NORMAL      = 0xf0000000;  // must be negative
222 >    static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
223 >    static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
224 >    static final int SIGNAL      = 0x00000001;
225 >    static final int MARKED      = 0x00000002;
226 >
227 >    /**
228 >     * Marks completion and wakes up threads waiting to join this
229 >     * task. A specialization for NORMAL completion is in method
230 >     * doExec.
231 >     *
232 >     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
233 >     * @return completion status on exit
234       */
235 <    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
236 <        Collections.synchronizedMap
237 <        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
238 <
239 <    // within-package utilities
235 >    private int setCompletion(int completion) {
236 >        for (int s;;) {
237 >            if ((s = status) < 0)
238 >                return s;
239 >            if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
240 >                if ((s & SIGNAL) != 0)
241 >                    synchronized (this) { notifyAll(); }
242 >                return completion;
243 >            }
244 >        }
245 >    }
246  
247      /**
248 <     * Get current worker thread, or null if not a worker thread
248 >     * Primary execution method for stolen tasks. Unless done, calls
249 >     * exec and records status if completed, but doesn't wait for
250 >     * completion otherwise.
251 >     *
252 >     * @return status on exit from this method
253       */
254 <    static ForkJoinWorkerThread getWorker() {
255 <        Thread t = Thread.currentThread();
256 <        return ((t instanceof ForkJoinWorkerThread)?
257 <                (ForkJoinWorkerThread)t : null);
254 >    final int doExec() {
255 >        int s; boolean completed;
256 >        if ((s = status) >= 0) {
257 >            try {
258 >                completed = exec();
259 >            } catch (Throwable rex) {
260 >                return setExceptionalCompletion(rex);
261 >            }
262 >            while ((s = status) >= 0 && completed) {
263 >                if (U.compareAndSwapInt(this, STATUS, s, s | NORMAL)) {
264 >                    if ((s & SIGNAL) != 0)
265 >                        synchronized (this) { notifyAll(); }
266 >                    return NORMAL;
267 >                }
268 >            }
269 >        }
270 >        return s;
271      }
272  
273      /**
274 <     * Get pool of current worker thread, or null if not a worker thread
274 >     * Tries to set SIGNAL status. Used by ForkJoinPool. Other
275 >     * variants are directly incorporated into externalAwaitDone etc.
276 >     *
277 >     * @return true if successful
278       */
279 <    static ForkJoinPool getWorkerPool() {
280 <        Thread t = Thread.currentThread();
281 <        return ((t instanceof ForkJoinWorkerThread)?
153 <                ((ForkJoinWorkerThread)t).pool : null);
279 >    final boolean trySetSignal() {
280 >        int s;
281 >        return U.compareAndSwapInt(this, STATUS, s = status, s | SIGNAL);
282      }
283  
284 <    final boolean casStatus(int cmp, int val) {
285 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
284 >    /**
285 >     * Blocks a non-worker-thread until completion.
286 >     * @return status upon completion
287 >     */
288 >    private int externalAwaitDone() {
289 >        boolean interrupted = false;
290 >        int s;
291 >        while ((s = status) >= 0) {
292 >            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293 >                synchronized (this) {
294 >                    if (status >= 0) {
295 >                        try {
296 >                            wait();
297 >                        } catch (InterruptedException ie) {
298 >                            interrupted = true;
299 >                        }
300 >                    }
301 >                    else
302 >                        notifyAll();
303 >                }
304 >            }
305 >        }
306 >        if (interrupted)
307 >            Thread.currentThread().interrupt();
308 >        return s;
309      }
310  
311      /**
312 <     * Workaround for not being able to rethrow unchecked exceptions.
312 >     * Blocks a non-worker-thread until completion or interruption.
313       */
314 <    static void rethrowException(Throwable ex) {
315 <        if (ex != null)
316 <            _unsafe.throwException(ex);
314 >    private int externalInterruptibleAwaitDone() throws InterruptedException {
315 >        int s;
316 >        if (Thread.interrupted())
317 >            throw new InterruptedException();
318 >        while ((s = status) >= 0) {
319 >            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
320 >                synchronized (this) {
321 >                    if (status >= 0)
322 >                        wait();
323 >                    else
324 >                        notifyAll();
325 >                }
326 >            }
327 >        }
328 >        return s;
329      }
330  
168    // Setting completion status
331  
332      /**
333 <     * Mark completion and wake up threads waiting to join this task.
334 <     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
333 >     * Implementation for join, get, quietlyJoin. Directly handles
334 >     * only cases of already-completed, external wait, and
335 >     * unfork+exec.  Others are relayed to ForkJoinPool.awaitJoin.
336 >     *
337 >     * @return status upon completion
338       */
339 <    final void setCompletion(int completion) {
340 <        ForkJoinPool pool = getWorkerPool();
341 <        if (pool != null) {
342 <            int s; // Clear signal bits while setting completion status
343 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
344 <
345 <            if ((s & SIGNAL_MASK) != 0) {
181 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
182 <                    pool.updateRunningCount(s);
183 <                synchronized(this) { notifyAll(); }
339 >    private int doJoin() {
340 >        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
341 >        if ((s = status) >= 0) {
342 >            if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
343 >                if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
344 >                    tryUnpush(this) || (s = doExec()) >= 0)
345 >                    s = wt.pool.awaitJoin(w, this);
346              }
347 +            else
348 +                s = externalAwaitDone();
349          }
350 <        else
187 <            externallySetCompletion(completion);
350 >        return s;
351      }
352  
353      /**
354 <     * Version of setCompletion for non-FJ threads.  Leaves signal
355 <     * bits for unblocked threads to adjust, and always notifies.
354 >     * Implementation for invoke, quietlyInvoke.
355 >     *
356 >     * @return status upon completion
357       */
358 <    private void externallySetCompletion(int completion) {
359 <        int s;
360 <        do;while ((s = status) >= 0 &&
361 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
362 <        synchronized(this) { notifyAll(); }
358 >    private int doInvoke() {
359 >        int s; Thread t; ForkJoinWorkerThread wt;
360 >        if ((s = doExec()) >= 0) {
361 >            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
362 >                s = (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue,
363 >                                                                  this);
364 >            else
365 >                s = externalAwaitDone();
366 >        }
367 >        return s;
368      }
369  
370 +    // Exception table support
371 +
372      /**
373 <     * Sets status to indicate normal completion
373 >     * Table of exceptions thrown by tasks, to enable reporting by
374 >     * callers. Because exceptions are rare, we don't directly keep
375 >     * them with task objects, but instead use a weak ref table.  Note
376 >     * that cancellation exceptions don't appear in the table, but are
377 >     * instead recorded as status values.
378 >     *
379 >     * Note: These statics are initialized below in static block.
380       */
381 <    final void setNormalCompletion() {
382 <        // Try typical fast case -- single CAS, no signal, not already done.
383 <        // Manually expand casStatus to improve chances of inlining it
207 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
208 <            setCompletion(NORMAL);
209 <    }
381 >    private static final ExceptionNode[] exceptionTable;
382 >    private static final ReentrantLock exceptionTableLock;
383 >    private static final ReferenceQueue<Object> exceptionTableRefQueue;
384  
385 <    // internal waiting and notification
385 >    /**
386 >     * Fixed capacity for exceptionTable.
387 >     */
388 >    private static final int EXCEPTION_MAP_CAPACITY = 32;
389  
390      /**
391 <     * Performs the actual monitor wait for awaitDone
391 >     * Key-value nodes for exception table.  The chained hash table
392 >     * uses identity comparisons, full locking, and weak references
393 >     * for keys. The table has a fixed capacity because it only
394 >     * maintains task exceptions long enough for joiners to access
395 >     * them, so should never become very large for sustained
396 >     * periods. However, since we do not know when the last joiner
397 >     * completes, we must use weak references and expunge them. We do
398 >     * so on each operation (hence full locking). Also, some thread in
399 >     * any ForkJoinPool will call helpExpungeStaleExceptions when its
400 >     * pool becomes isQuiescent.
401       */
402 <    private void doAwaitDone() {
403 <        // Minimize lock bias and in/de-flation effects by maximizing
404 <        // chances of waiting inside sync
405 <        try {
406 <            while (status >= 0)
407 <                synchronized(this) { if (status >= 0) wait(); }
408 <        } catch (InterruptedException ie) {
409 <            onInterruptedWait();
402 >    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
403 >        final Throwable ex;
404 >        ExceptionNode next;
405 >        final long thrower;  // use id not ref to avoid weak cycles
406 >        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
407 >            super(task, exceptionTableRefQueue);
408 >            this.ex = ex;
409 >            this.next = next;
410 >            this.thrower = Thread.currentThread().getId();
411          }
412      }
413  
414      /**
415 <     * Performs the actual monitor wait for awaitDone
415 >     * Records exception and sets exceptional completion.
416 >     *
417 >     * @return status on exit
418       */
419 <    private void doAwaitDone(long startTime, long nanos) {
420 <        synchronized(this) {
421 <            try {
422 <                while (status >= 0) {
423 <                    long nt = nanos - System.nanoTime() - startTime;
424 <                    if (nt <= 0)
425 <                        break;
426 <                    wait(nt / 1000000, (int)(nt % 1000000));
419 >    private int setExceptionalCompletion(Throwable ex) {
420 >        int h = System.identityHashCode(this);
421 >        final ReentrantLock lock = exceptionTableLock;
422 >        lock.lock();
423 >        try {
424 >            expungeStaleExceptions();
425 >            ExceptionNode[] t = exceptionTable;
426 >            int i = h & (t.length - 1);
427 >            for (ExceptionNode e = t[i]; ; e = e.next) {
428 >                if (e == null) {
429 >                    t[i] = new ExceptionNode(this, ex, t[i]);
430 >                    break;
431                  }
432 <            } catch (InterruptedException ie) {
433 <                onInterruptedWait();
432 >                if (e.get() == this) // already present
433 >                    break;
434              }
435 +        } finally {
436 +            lock.unlock();
437          }
438 +        return setCompletion(EXCEPTIONAL);
439      }
440  
245    // Awaiting completion
246
441      /**
442 <     * Sets status to indicate there is joiner, then waits for join,
443 <     * surrounded with pool notifications.
444 <     * @return status upon exit
442 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
443 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
444 >     * exceptions, but if it does anyway, we have no recourse during
445 >     * shutdown, so guard against this case.
446       */
447 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
448 <        ForkJoinPool pool = w == null? null : w.pool;
449 <        int s;
450 <        while ((s = status) >= 0) {
451 <            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;
447 >    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
448 >        if (t != null && t.status >= 0) {
449 >            try {
450 >                t.cancel(false);
451 >            } catch (Throwable ignore) {
452              }
453          }
264        return s;
454      }
455  
456      /**
457 <     * Timed version of awaitDone
269 <     * @return status upon exit
457 >     * Removes exception node and clears status
458       */
459 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
460 <        ForkJoinPool pool = w == null? null : w.pool;
461 <        int s;
462 <        while ((s = status) >= 0) {
463 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
464 <                long startTime = System.nanoTime();
465 <                if (pool == null || !pool.preJoin(this, false))
466 <                    doAwaitDone(startTime, nanos);
467 <                if ((s = status) >= 0) {
468 <                    adjustPoolCountsOnCancelledWait(pool);
469 <                    s = status;
459 >    private void clearExceptionalCompletion() {
460 >        int h = System.identityHashCode(this);
461 >        final ReentrantLock lock = exceptionTableLock;
462 >        lock.lock();
463 >        try {
464 >            ExceptionNode[] t = exceptionTable;
465 >            int i = h & (t.length - 1);
466 >            ExceptionNode e = t[i];
467 >            ExceptionNode pred = null;
468 >            while (e != null) {
469 >                ExceptionNode next = e.next;
470 >                if (e.get() == this) {
471 >                    if (pred == null)
472 >                        t[i] = next;
473 >                    else
474 >                        pred.next = next;
475 >                    break;
476                  }
477 <                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
478 <                    adjustPoolCountsOnUnblock(pool);
285 <                break;
477 >                pred = e;
478 >                e = next;
479              }
480 +            expungeStaleExceptions();
481 +            status = 0;
482 +        } finally {
483 +            lock.unlock();
484          }
288        return s;
485      }
486  
487      /**
488 <     * Notify pool that thread is unblocked. Called by signalled
489 <     * threads when woken by non-FJ threads (which is atypical).
488 >     * Returns a rethrowable exception for the given task, if
489 >     * available. To provide accurate stack traces, if the exception
490 >     * was not thrown by the current thread, we try to create a new
491 >     * exception of the same type as the one thrown, but with the
492 >     * recorded exception as its cause. If there is no such
493 >     * constructor, we instead try to use a no-arg constructor,
494 >     * followed by initCause, to the same effect. If none of these
495 >     * apply, or any fail due to other exceptions, we return the
496 >     * recorded exception, which is still correct, although it may
497 >     * contain a misleading stack trace.
498 >     *
499 >     * @return the exception, or null if none
500       */
501 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
502 <        int s;
503 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
504 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
505 <            pool.updateRunningCount(s);
501 >    private Throwable getThrowableException() {
502 >        if ((status & DONE_MASK) != EXCEPTIONAL)
503 >            return null;
504 >        int h = System.identityHashCode(this);
505 >        ExceptionNode e;
506 >        final ReentrantLock lock = exceptionTableLock;
507 >        lock.lock();
508 >        try {
509 >            expungeStaleExceptions();
510 >            ExceptionNode[] t = exceptionTable;
511 >            e = t[h & (t.length - 1)];
512 >            while (e != null && e.get() != this)
513 >                e = e.next;
514 >        } finally {
515 >            lock.unlock();
516 >        }
517 >        Throwable ex;
518 >        if (e == null || (ex = e.ex) == null)
519 >            return null;
520 >        if (e.thrower != Thread.currentThread().getId()) {
521 >            Class<? extends Throwable> ec = ex.getClass();
522 >            try {
523 >                Constructor<?> noArgCtor = null;
524 >                Constructor<?>[] cs = ec.getConstructors();// public ctors only
525 >                for (int i = 0; i < cs.length; ++i) {
526 >                    Constructor<?> c = cs[i];
527 >                    Class<?>[] ps = c.getParameterTypes();
528 >                    if (ps.length == 0)
529 >                        noArgCtor = c;
530 >                    else if (ps.length == 1 && ps[0] == Throwable.class)
531 >                        return (Throwable)(c.newInstance(ex));
532 >                }
533 >                if (noArgCtor != null) {
534 >                    Throwable wx = (Throwable)(noArgCtor.newInstance());
535 >                    wx.initCause(ex);
536 >                    return wx;
537 >                }
538 >            } catch (Exception ignore) {
539 >            }
540 >        }
541 >        return ex;
542      }
543  
544      /**
545 <     * Notify pool to adjust counts on cancelled or timed out wait
545 >     * Poll stale refs and remove them. Call only while holding lock.
546       */
547 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
548 <        if (pool != null) {
549 <            int s;
550 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
551 <                if (casStatus(s, s - 1)) {
552 <                    pool.updateRunningCount(1);
553 <                    break;
547 >    private static void expungeStaleExceptions() {
548 >        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
549 >            if (x instanceof ExceptionNode) {
550 >                ForkJoinTask<?> key = ((ExceptionNode)x).get();
551 >                ExceptionNode[] t = exceptionTable;
552 >                int i = System.identityHashCode(key) & (t.length - 1);
553 >                ExceptionNode e = t[i];
554 >                ExceptionNode pred = null;
555 >                while (e != null) {
556 >                    ExceptionNode next = e.next;
557 >                    if (e == x) {
558 >                        if (pred == null)
559 >                            t[i] = next;
560 >                        else
561 >                            pred.next = next;
562 >                        break;
563 >                    }
564 >                    pred = e;
565 >                    e = next;
566                  }
567              }
568          }
569      }
570  
571 <    private void onInterruptedWait() {
572 <        Thread t = Thread.currentThread();
573 <        if (t instanceof ForkJoinWorkerThread) {
574 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
575 <            if (w.isTerminating())
576 <                cancelIgnoreExceptions();
577 <        }
324 <        else { // re-interrupt
571 >    /**
572 >     * If lock is available, poll stale refs and remove them.
573 >     * Called from ForkJoinPool when pools become quiescent.
574 >     */
575 >    static final void helpExpungeStaleExceptions() {
576 >        final ReentrantLock lock = exceptionTableLock;
577 >        if (lock.tryLock()) {
578              try {
579 <                t.interrupt();
580 <            } catch (SecurityException ignore) {
579 >                expungeStaleExceptions();
580 >            } finally {
581 >                lock.unlock();
582              }
583          }
584      }
585  
586 <    // Recording and reporting exceptions
587 <
588 <    private void setDoneExceptionally(Throwable rex) {
589 <        exceptionMap.put(this, rex);
590 <        setCompletion(EXCEPTIONAL);
586 >    /**
587 >     * Throws exception, if any, associated with the given status.
588 >     */
589 >    private void reportException(int s) {
590 >        Throwable ex = ((s == CANCELLED) ?  new CancellationException() :
591 >                        (s == EXCEPTIONAL) ? getThrowableException() :
592 >                        null);
593 >        if (ex != null)
594 >            U.throwException(ex);
595      }
596  
597 +    // public methods
598 +
599      /**
600 <     * Throws the exception associated with status s;
601 <     * @throws the exception
600 >     * Arranges to asynchronously execute this task.  While it is not
601 >     * necessarily enforced, it is a usage error to fork a task more
602 >     * than once unless it has completed and been reinitialized.
603 >     * Subsequent modifications to the state of this task or any data
604 >     * it operates on are not necessarily consistently observable by
605 >     * any thread other than the one executing it unless preceded by a
606 >     * call to {@link #join} or related methods, or a call to {@link
607 >     * #isDone} returning {@code true}.
608 >     *
609 >     * <p>This method may be invoked only from within {@code
610 >     * ForkJoinPool} computations (as may be determined using method
611 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
612 >     * result in exceptions or errors, possibly including {@code
613 >     * ClassCastException}.
614 >     *
615 >     * @return {@code this}, to simplify usage
616       */
617 <    private void reportException(int s) {
618 <        if ((s &= COMPLETION_MASK) < NORMAL) {
619 <            if (s == CANCELLED)
346 <                throw new CancellationException();
347 <            else
348 <                rethrowException(exceptionMap.get(this));
349 <        }
617 >    public final ForkJoinTask<V> fork() {
618 >        ((ForkJoinWorkerThread)Thread.currentThread()).workQueue.push(this);
619 >        return this;
620      }
621  
622      /**
623 <     * Returns result or throws exception using j.u.c.Future conventions
624 <     * Only call when isDone known to be true.
623 >     * Returns the result of the computation when it {@link #isDone is
624 >     * done}.  This method differs from {@link #get()} in that
625 >     * abnormal completion results in {@code RuntimeException} or
626 >     * {@code Error}, not {@code ExecutionException}, and that
627 >     * interrupts of the calling thread do <em>not</em> cause the
628 >     * method to abruptly return by throwing {@code
629 >     * InterruptedException}.
630 >     *
631 >     * @return the computed result
632       */
633 <    private V reportFutureResult()
634 <        throws ExecutionException, InterruptedException {
635 <        int s = status & COMPLETION_MASK;
636 <        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 <        }
633 >    public final V join() {
634 >        int s;
635 >        if ((s = doJoin() & DONE_MASK) != NORMAL)
636 >            reportException(s);
637          return getRawResult();
638      }
639  
640      /**
641 <     * Returns result or throws exception using j.u.c.Future conventions
642 <     * with timeouts
641 >     * Commences performing this task, awaits its completion if
642 >     * necessary, and returns its result, or throws an (unchecked)
643 >     * {@code RuntimeException} or {@code Error} if the underlying
644 >     * computation did so.
645 >     *
646 >     * @return the computed result
647       */
648 <    private V reportTimedFutureResult()
649 <        throws InterruptedException, ExecutionException, TimeoutException {
650 <        Throwable ex;
651 <        int s = status & COMPLETION_MASK;
652 <        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();
648 >    public final V invoke() {
649 >        int s;
650 >        if ((s = doInvoke() & DONE_MASK) != NORMAL)
651 >            reportException(s);
652 >        return getRawResult();
653      }
654  
390    // internal execution methods
391
655      /**
656 <     * Calls exec, recording completion, and rethrowing exception if
657 <     * encountered. Caller should normally check status before calling
658 <     * @return true if completed normally
656 >     * Forks the given tasks, returning when {@code isDone} holds for
657 >     * each task or an (unchecked) exception is encountered, in which
658 >     * case the exception is rethrown. If more than one task
659 >     * encounters an exception, then this method throws any one of
660 >     * these exceptions. If any task encounters an exception, the
661 >     * other may be cancelled. However, the execution status of
662 >     * individual tasks is not guaranteed upon exceptional return. The
663 >     * status of each task may be obtained using {@link
664 >     * #getException()} and related methods to check if they have been
665 >     * cancelled, completed normally or exceptionally, or left
666 >     * unprocessed.
667 >     *
668 >     * <p>This method may be invoked only from within {@code
669 >     * ForkJoinPool} computations (as may be determined using method
670 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
671 >     * result in exceptions or errors, possibly including {@code
672 >     * ClassCastException}.
673 >     *
674 >     * @param t1 the first task
675 >     * @param t2 the second task
676 >     * @throws NullPointerException if any task is null
677       */
678 <    private boolean tryExec() {
679 <        try { // try block must contain only call to exec
680 <            if (!exec())
681 <                return false;
682 <        } catch (Throwable rex) {
683 <            setDoneExceptionally(rex);
684 <            rethrowException(rex);
404 <            return false; // not reached
405 <        }
406 <        setNormalCompletion();
407 <        return true;
678 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
679 >        int s1, s2;
680 >        t2.fork();
681 >        if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL)
682 >            t1.reportException(s1);
683 >        if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL)
684 >            t2.reportException(s2);
685      }
686  
687      /**
688 <     * Main execution method used by worker threads. Invokes
689 <     * base computation unless already complete
688 >     * Forks the given tasks, returning when {@code isDone} holds for
689 >     * each task or an (unchecked) exception is encountered, in which
690 >     * case the exception is rethrown. If more than one task
691 >     * encounters an exception, then this method throws any one of
692 >     * these exceptions. If any task encounters an exception, others
693 >     * may be cancelled. However, the execution status of individual
694 >     * tasks is not guaranteed upon exceptional return. The status of
695 >     * each task may be obtained using {@link #getException()} and
696 >     * related methods to check if they have been cancelled, completed
697 >     * normally or exceptionally, or left unprocessed.
698 >     *
699 >     * <p>This method may be invoked only from within {@code
700 >     * ForkJoinPool} computations (as may be determined using method
701 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
702 >     * result in exceptions or errors, possibly including {@code
703 >     * ClassCastException}.
704 >     *
705 >     * @param tasks the tasks
706 >     * @throws NullPointerException if any task is null
707       */
708 <    final void quietlyExec() {
709 <        if (status >= 0) {
710 <            try {
711 <                if (!exec())
712 <                    return;
713 <            } catch(Throwable rex) {
714 <                setDoneExceptionally(rex);
715 <                return;
708 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
709 >        Throwable ex = null;
710 >        int last = tasks.length - 1;
711 >        for (int i = last; i >= 0; --i) {
712 >            ForkJoinTask<?> t = tasks[i];
713 >            if (t == null) {
714 >                if (ex == null)
715 >                    ex = new NullPointerException();
716 >            }
717 >            else if (i != 0)
718 >                t.fork();
719 >            else if (t.doInvoke() < NORMAL && ex == null)
720 >                ex = t.getException();
721 >        }
722 >        for (int i = 1; i <= last; ++i) {
723 >            ForkJoinTask<?> t = tasks[i];
724 >            if (t != null) {
725 >                if (ex != null)
726 >                    t.cancel(false);
727 >                else if (t.doJoin() < NORMAL)
728 >                    ex = t.getException();
729              }
423            setNormalCompletion();
730          }
731 +        if (ex != null)
732 +            U.throwException(ex);
733      }
734  
735      /**
736 <     * Calls exec, recording but not rethrowing exception
737 <     * Caller should normally check status before calling
738 <     * @return true if completed normally
736 >     * Forks all tasks in the specified collection, returning when
737 >     * {@code isDone} holds for each task or an (unchecked) exception
738 >     * is encountered, in which case the exception is rethrown. If
739 >     * more than one task encounters an exception, then this method
740 >     * throws any one of these exceptions. If any task encounters an
741 >     * exception, others may be cancelled. However, the execution
742 >     * status of individual tasks is not guaranteed upon exceptional
743 >     * return. The status of each task may be obtained using {@link
744 >     * #getException()} and related methods to check if they have been
745 >     * cancelled, completed normally or exceptionally, or left
746 >     * unprocessed.
747 >     *
748 >     * <p>This method may be invoked only from within {@code
749 >     * ForkJoinPool} computations (as may be determined using method
750 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
751 >     * result in exceptions or errors, possibly including {@code
752 >     * ClassCastException}.
753 >     *
754 >     * @param tasks the collection of tasks
755 >     * @return the tasks argument, to simplify usage
756 >     * @throws NullPointerException if tasks or any element are null
757       */
758 <    private boolean tryQuietlyInvoke() {
759 <        try {
760 <            if (!exec())
761 <                return false;
762 <        } catch (Throwable rex) {
763 <            setDoneExceptionally(rex);
764 <            return false;
758 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
759 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
760 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
761 >            return tasks;
762 >        }
763 >        @SuppressWarnings("unchecked")
764 >        List<? extends ForkJoinTask<?>> ts =
765 >            (List<? extends ForkJoinTask<?>>) tasks;
766 >        Throwable ex = null;
767 >        int last = ts.size() - 1;
768 >        for (int i = last; i >= 0; --i) {
769 >            ForkJoinTask<?> t = ts.get(i);
770 >            if (t == null) {
771 >                if (ex == null)
772 >                    ex = new NullPointerException();
773 >            }
774 >            else if (i != 0)
775 >                t.fork();
776 >            else if (t.doInvoke() < NORMAL && ex == null)
777 >                ex = t.getException();
778 >        }
779 >        for (int i = 1; i <= last; ++i) {
780 >            ForkJoinTask<?> t = ts.get(i);
781 >            if (t != null) {
782 >                if (ex != null)
783 >                    t.cancel(false);
784 >                else if (t.doJoin() < NORMAL)
785 >                    ex = t.getException();
786 >            }
787          }
788 <        setNormalCompletion();
789 <        return true;
788 >        if (ex != null)
789 >            U.throwException(ex);
790 >        return tasks;
791      }
792  
793      /**
794 <     * Cancel, ignoring any exceptions it throws
794 >     * Attempts to cancel execution of this task. This attempt will
795 >     * fail if the task has already completed or could not be
796 >     * cancelled for some other reason. If successful, and this task
797 >     * has not started when {@code cancel} is called, execution of
798 >     * this task is suppressed. After this method returns
799 >     * successfully, unless there is an intervening call to {@link
800 >     * #reinitialize}, subsequent calls to {@link #isCancelled},
801 >     * {@link #isDone}, and {@code cancel} will return {@code true}
802 >     * and calls to {@link #join} and related methods will result in
803 >     * {@code CancellationException}.
804 >     *
805 >     * <p>This method may be overridden in subclasses, but if so, must
806 >     * still ensure that these properties hold. In particular, the
807 >     * {@code cancel} method itself must not throw exceptions.
808 >     *
809 >     * <p>This method is designed to be invoked by <em>other</em>
810 >     * tasks. To terminate the current task, you can just return or
811 >     * throw an unchecked exception from its computation method, or
812 >     * invoke {@link #completeExceptionally}.
813 >     *
814 >     * @param mayInterruptIfRunning this value has no effect in the
815 >     * default implementation because interrupts are not used to
816 >     * control cancellation.
817 >     *
818 >     * @return {@code true} if this task is now cancelled
819       */
820 <    final void cancelIgnoreExceptions() {
821 <        try {
449 <            cancel(false);
450 <        } catch(Throwable ignore) {
451 <        }
820 >    public boolean cancel(boolean mayInterruptIfRunning) {
821 >        return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED;
822      }
823  
824 <    // public methods
824 >    public final boolean isDone() {
825 >        return status < 0;
826 >    }
827 >
828 >    public final boolean isCancelled() {
829 >        return (status & DONE_MASK) == CANCELLED;
830 >    }
831  
832      /**
833 <     * Arranges to asynchronously execute this task.  While it is not
834 <     * necessarily enforced, it is a usage error to fork a task more
835 <     * than once unless it has completed and been reinitialized.  This
460 <     * method may be invoked only from within other ForkJoinTask
461 <     * computations. Attempts to invoke in other contexts result in
462 <     * exceptions or errors including ClassCastException.
833 >     * Returns {@code true} if this task threw an exception or was cancelled.
834 >     *
835 >     * @return {@code true} if this task threw an exception or was cancelled
836       */
837 <    public final void fork() {
838 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
837 >    public final boolean isCompletedAbnormally() {
838 >        return status < NORMAL;
839      }
840  
841      /**
842 <     * Returns the result of the computation when it is ready.
843 <     * This method differs from <tt>get</tt> in that abnormal
471 <     * completion results in RuntimeExceptions or Errors, not
472 <     * ExecutionExceptions.
842 >     * Returns {@code true} if this task completed without throwing an
843 >     * exception and was not cancelled.
844       *
845 <     * @return the computed result
845 >     * @return {@code true} if this task completed without throwing an
846 >     * exception and was not cancelled
847       */
848 <    public final V join() {
849 <        ForkJoinWorkerThread w = getWorker();
478 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
479 <            reportException(awaitDone(w, true));
480 <        return getRawResult();
848 >    public final boolean isCompletedNormally() {
849 >        return (status & DONE_MASK) == NORMAL;
850      }
851  
852 <    public final V get() throws InterruptedException, ExecutionException {
853 <        ForkJoinWorkerThread w = getWorker();
854 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
855 <            awaitDone(w, true);
856 <        return reportFutureResult();
852 >    /**
853 >     * Returns the exception thrown by the base computation, or a
854 >     * {@code CancellationException} if cancelled, or {@code null} if
855 >     * none or if the method has not yet completed.
856 >     *
857 >     * @return the exception, or {@code null} if none
858 >     */
859 >    public final Throwable getException() {
860 >        int s = status & DONE_MASK;
861 >        return ((s >= NORMAL)    ? null :
862 >                (s == CANCELLED) ? new CancellationException() :
863 >                getThrowableException());
864      }
865  
866 <    public final V get(long timeout, TimeUnit unit)
867 <        throws InterruptedException, ExecutionException, TimeoutException {
868 <        ForkJoinWorkerThread w = getWorker();
869 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
870 <            awaitDone(w, unit.toNanos(timeout));
871 <        return reportTimedFutureResult();
866 >    /**
867 >     * Completes this task abnormally, and if not already aborted or
868 >     * cancelled, causes it to throw the given exception upon
869 >     * {@code join} and related operations. This method may be used
870 >     * to induce exceptions in asynchronous tasks, or to force
871 >     * completion of tasks that would not otherwise complete.  Its use
872 >     * in other situations is discouraged.  This method is
873 >     * overridable, but overridden versions must invoke {@code super}
874 >     * implementation to maintain guarantees.
875 >     *
876 >     * @param ex the exception to throw. If this exception is not a
877 >     * {@code RuntimeException} or {@code Error}, the actual exception
878 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
879 >     */
880 >    public void completeExceptionally(Throwable ex) {
881 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
882 >                                 (ex instanceof Error) ? ex :
883 >                                 new RuntimeException(ex));
884      }
885  
886      /**
887 <     * Possibly executes other tasks until this task is ready, then
888 <     * returns the result of the computation.  This method may be more
889 <     * efficient than <tt>join</tt>, but is only applicable when there
890 <     * are no potemtial dependencies between continuation of the
891 <     * current task and that of any other task that might be executed
892 <     * while helping. (This usually holds for pure divide-and-conquer
893 <     * tasks).
887 >     * Completes this task, and if not already aborted or cancelled,
888 >     * returning the given value as the result of subsequent
889 >     * invocations of {@code join} and related operations. This method
890 >     * may be used to provide results for asynchronous tasks, or to
891 >     * provide alternative handling for tasks that would not otherwise
892 >     * complete normally. Its use in other situations is
893 >     * discouraged. This method is overridable, but overridden
894 >     * versions must invoke {@code super} implementation to maintain
895 >     * guarantees.
896 >     *
897 >     * @param value the result value for this task
898 >     */
899 >    public void complete(V value) {
900 >        try {
901 >            setRawResult(value);
902 >        } catch (Throwable rex) {
903 >            setExceptionalCompletion(rex);
904 >            return;
905 >        }
906 >        setCompletion(NORMAL);
907 >    }
908 >
909 >    /**
910 >     * Waits if necessary for the computation to complete, and then
911 >     * retrieves its result.
912 >     *
913       * @return the computed result
914 +     * @throws CancellationException if the computation was cancelled
915 +     * @throws ExecutionException if the computation threw an
916 +     * exception
917 +     * @throws InterruptedException if the current thread is not a
918 +     * member of a ForkJoinPool and was interrupted while waiting
919       */
920 <    public final V helpJoin() {
921 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
922 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
923 <            reportException(w.helpJoinTask(this));
920 >    public final V get() throws InterruptedException, ExecutionException {
921 >        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
922 >            doJoin() : externalInterruptibleAwaitDone();
923 >        Throwable ex;
924 >        if ((s &= DONE_MASK) == CANCELLED)
925 >            throw new CancellationException();
926 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
927 >            throw new ExecutionException(ex);
928          return getRawResult();
929      }
930  
931      /**
932 <     * Performs this task, awaits its completion if necessary, and
933 <     * return its result.
934 <     * @throws Throwable (a RuntimeException, Error, or unchecked
935 <     * exception) if the underlying computation did so.
932 >     * Waits if necessary for at most the given time for the computation
933 >     * to complete, and then retrieves its result, if available.
934 >     *
935 >     * @param timeout the maximum time to wait
936 >     * @param unit the time unit of the timeout argument
937       * @return the computed result
938 +     * @throws CancellationException if the computation was cancelled
939 +     * @throws ExecutionException if the computation threw an
940 +     * exception
941 +     * @throws InterruptedException if the current thread is not a
942 +     * member of a ForkJoinPool and was interrupted while waiting
943 +     * @throws TimeoutException if the wait timed out
944       */
945 <    public final V invoke() {
946 <        if (status >= 0 && tryExec())
947 <            return getRawResult();
948 <        else
949 <            return join();
945 >    public final V get(long timeout, TimeUnit unit)
946 >        throws InterruptedException, ExecutionException, TimeoutException {
947 >        if (Thread.interrupted())
948 >            throw new InterruptedException();
949 >        // Messy in part because we measure in nanosecs, but wait in millisecs
950 >        int s; long ns, ms;
951 >        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
952 >            long deadline = System.nanoTime() + ns;
953 >            ForkJoinPool p = null;
954 >            ForkJoinPool.WorkQueue w = null;
955 >            Thread t = Thread.currentThread();
956 >            if (t instanceof ForkJoinWorkerThread) {
957 >                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
958 >                p = wt.pool;
959 >                w = wt.workQueue;
960 >                s = p.helpJoinOnce(w, this); // no retries on failure
961 >            }
962 >            boolean canBlock = false;
963 >            boolean interrupted = false;
964 >            try {
965 >                while ((s = status) >= 0) {
966 >                    if (w != null && w.runState < 0)
967 >                        cancelIgnoringExceptions(this);
968 >                    else if (!canBlock) {
969 >                        if (p == null || p.tryCompensate(this, null))
970 >                            canBlock = true;
971 >                    }
972 >                    else {
973 >                        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
974 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
975 >                            synchronized (this) {
976 >                                if (status >= 0) {
977 >                                    try {
978 >                                        wait(ms);
979 >                                    } catch (InterruptedException ie) {
980 >                                        if (p == null)
981 >                                            interrupted = true;
982 >                                    }
983 >                                }
984 >                                else
985 >                                    notifyAll();
986 >                            }
987 >                        }
988 >                        if ((s = status) < 0 || interrupted ||
989 >                            (ns = deadline - System.nanoTime()) <= 0L)
990 >                            break;
991 >                    }
992 >                }
993 >            } finally {
994 >                if (p != null && canBlock)
995 >                    p.incrementActiveCount();
996 >            }
997 >            if (interrupted)
998 >                throw new InterruptedException();
999 >        }
1000 >        if ((s &= DONE_MASK) != NORMAL) {
1001 >            Throwable ex;
1002 >            if (s == CANCELLED)
1003 >                throw new CancellationException();
1004 >            if (s != EXCEPTIONAL)
1005 >                throw new TimeoutException();
1006 >            if ((ex = getThrowableException()) != null)
1007 >                throw new ExecutionException(ex);
1008 >        }
1009 >        return getRawResult();
1010      }
1011  
1012      /**
1013 <     * Joins this task, without returning its result or throwing an
1013 >     * Joins this task, without returning its result or throwing its
1014       * exception. This method may be useful when processing
1015       * collections of tasks when some have been cancelled or otherwise
1016       * known to have aborted.
1017       */
1018      public final void quietlyJoin() {
1019 <        if (status >= 0) {
537 <            ForkJoinWorkerThread w = getWorker();
538 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
1019 >        doJoin();
1020      }
1021  
1022      /**
1023 <     * Possibly executes other tasks until this task is ready.
1023 >     * Commences performing this task and awaits its completion if
1024 >     * necessary, without returning its result or throwing its
1025 >     * exception.
1026       */
1027 <    public final void quietlyHelpJoin() {
1028 <        if (status >= 0) {
548 <            ForkJoinWorkerThread w =
549 <                (ForkJoinWorkerThread)(Thread.currentThread());
550 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
551 <                w.helpJoinTask(this);
552 <        }
1027 >    public final void quietlyInvoke() {
1028 >        doInvoke();
1029      }
1030  
1031      /**
1032 <     * Performs this task and awaits its completion if necessary,
1033 <     * without returning its result or throwing an exception. This
1034 <     * method may be useful when processing collections of tasks when
1035 <     * some have been cancelled or otherwise known to have aborted.
1032 >     * Possibly executes tasks until the pool hosting the current task
1033 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
1034 >     * be of use in designs in which many tasks are forked, but none
1035 >     * are explicitly joined, instead executing them until all are
1036 >     * processed.
1037 >     *
1038 >     * <p>This method may be invoked only from within {@code
1039 >     * ForkJoinPool} computations (as may be determined using method
1040 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1041 >     * result in exceptions or errors, possibly including {@code
1042 >     * ClassCastException}.
1043       */
1044 <    public final void quietlyInvoke() {
1045 <        if (status >= 0 && !tryQuietlyInvoke())
1046 <            quietlyJoin();
1044 >    public static void helpQuiesce() {
1045 >        ForkJoinWorkerThread wt =
1046 >            (ForkJoinWorkerThread)Thread.currentThread();
1047 >        wt.pool.helpQuiescePool(wt.workQueue);
1048      }
1049  
1050      /**
1051 <     * Returns true if the computation performed by this task has
1052 <     * completed (or has been cancelled).
1053 <     * @return true if this computation has completed
1051 >     * Resets the internal bookkeeping state of this task, allowing a
1052 >     * subsequent {@code fork}. This method allows repeated reuse of
1053 >     * this task, but only if reuse occurs when this task has either
1054 >     * never been forked, or has been forked, then completed and all
1055 >     * outstanding joins of this task have also completed. Effects
1056 >     * under any other usage conditions are not guaranteed.
1057 >     * This method may be useful when executing
1058 >     * pre-constructed trees of subtasks in loops.
1059 >     *
1060 >     * <p>Upon completion of this method, {@code isDone()} reports
1061 >     * {@code false}, and {@code getException()} reports {@code
1062 >     * null}. However, the value returned by {@code getRawResult} is
1063 >     * unaffected. To clear this value, you can invoke {@code
1064 >     * setRawResult(null)}.
1065       */
1066 <    public final boolean isDone() {
1067 <        return status < 0;
1066 >    public void reinitialize() {
1067 >        if ((status & DONE_MASK) == EXCEPTIONAL)
1068 >            clearExceptionalCompletion();
1069 >        else
1070 >            status = 0;
1071      }
1072  
1073      /**
1074 <     * Returns true if this task was cancelled.
1075 <     * @return true if this task was cancelled
1074 >     * Returns the pool hosting the current task execution, or null
1075 >     * if this task is executing outside of any ForkJoinPool.
1076 >     *
1077 >     * @see #inForkJoinPool
1078 >     * @return the pool, or {@code null} if none
1079       */
1080 <    public final boolean isCancelled() {
1081 <        return (status & COMPLETION_MASK) == CANCELLED;
1080 >    public static ForkJoinPool getPool() {
1081 >        Thread t = Thread.currentThread();
1082 >        return (t instanceof ForkJoinWorkerThread) ?
1083 >            ((ForkJoinWorkerThread) t).pool : null;
1084      }
1085  
1086      /**
1087 <     * Returns true if this task threw an exception or was cancelled
1088 <     * @return true if this task threw an exception or was cancelled
1087 >     * Returns {@code true} if the current thread is a {@link
1088 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1089 >     *
1090 >     * @return {@code true} if the current thread is a {@link
1091 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1092 >     * or {@code false} otherwise
1093       */
1094 <    public final boolean completedAbnormally() {
1095 <        return (status & COMPLETION_MASK) < NORMAL;
1094 >    public static boolean inForkJoinPool() {
1095 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
1096      }
1097  
1098      /**
1099 <     * Returns the exception thrown by the base computation, or a
1100 <     * CancellationException if cancelled, or null if none or if the
1101 <     * method has not yet completed.
1102 <     * @return the exception, or null if none
1099 >     * Tries to unschedule this task for execution. This method will
1100 >     * typically succeed if this task is the most recently forked task
1101 >     * by the current thread, and has not commenced executing in
1102 >     * another thread.  This method may be useful when arranging
1103 >     * alternative local processing of tasks that could have been, but
1104 >     * were not, stolen.
1105 >     *
1106 >     * <p>This method may be invoked only from within {@code
1107 >     * ForkJoinPool} computations (as may be determined using method
1108 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1109 >     * result in exceptions or errors, possibly including {@code
1110 >     * ClassCastException}.
1111 >     *
1112 >     * @return {@code true} if unforked
1113       */
1114 <    public final Throwable getException() {
1115 <        int s = status & COMPLETION_MASK;
1116 <        if (s >= NORMAL)
600 <            return null;
601 <        if (s == CANCELLED)
602 <            return new CancellationException();
603 <        return exceptionMap.get(this);
1114 >    public boolean tryUnfork() {
1115 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1116 >            .workQueue.tryUnpush(this);
1117      }
1118  
1119      /**
1120 <     * Asserts that the results of this task's computation will not be
1121 <     * used. If a cancellation occurs before this task is processed,
1122 <     * then its <tt>compute</tt> method will not be executed,
1123 <     * <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.
1120 >     * Returns an estimate of the number of tasks that have been
1121 >     * forked by the current worker thread but not yet executed. This
1122 >     * value may be useful for heuristic decisions about whether to
1123 >     * fork other tasks.
1124       *
1125 <     * <p>This method may be overridden in subclasses, but if so, must
1126 <     * still ensure that these minimal properties hold. In particular,
1127 <     * the cancel method itself must not throw exceptions.
1125 >     * <p>This method may be invoked only from within {@code
1126 >     * ForkJoinPool} computations (as may be determined using method
1127 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1128 >     * result in exceptions or errors, possibly including {@code
1129 >     * ClassCastException}.
1130       *
1131 <     * <p> This method is designed to be invoked by <em>other</em>
1132 <     * tasks. To terminate the current task, you can just return or
1133 <     * throw an unchecked exception from its computation method, or
1134 <     * invoke <tt>completeExceptionally(someException)</tt>.
1131 >     * @return the number of tasks
1132 >     */
1133 >    public static int getQueuedTaskCount() {
1134 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1135 >            .workQueue.queueSize();
1136 >    }
1137 >
1138 >    /**
1139 >     * Returns an estimate of how many more locally queued tasks are
1140 >     * held by the current worker thread than there are other worker
1141 >     * threads that might steal them.  This value may be useful for
1142 >     * heuristic decisions about whether to fork other tasks. In many
1143 >     * usages of ForkJoinTasks, at steady state, each worker should
1144 >     * aim to maintain a small constant surplus (for example, 3) of
1145 >     * tasks, and to process computations locally if this threshold is
1146 >     * exceeded.
1147       *
1148 <     * @param mayInterruptIfRunning this value is ignored in the
1149 <     * default implementation because tasks are not in general
1150 <     * cancelled via interruption.
1148 >     * <p>This method may be invoked only from within {@code
1149 >     * ForkJoinPool} computations (as may be determined using method
1150 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1151 >     * result in exceptions or errors, possibly including {@code
1152 >     * ClassCastException}.
1153       *
1154 <     * @return true if this task is now cancelled
1154 >     * @return the surplus number of tasks, which may be negative
1155       */
1156 <    public boolean cancel(boolean mayInterruptIfRunning) {
1157 <        setCompletion(CANCELLED);
1158 <        return (status & COMPLETION_MASK) == CANCELLED;
1159 <    }
1156 >    public static int getSurplusQueuedTaskCount() {
1157 >        /*
1158 >         * The aim of this method is to return a cheap heuristic guide
1159 >         * for task partitioning when programmers, frameworks, tools,
1160 >         * or languages have little or no idea about task granularity.
1161 >         * In essence by offering this method, we ask users only about
1162 >         * tradeoffs in overhead vs expected throughput and its
1163 >         * variance, rather than how finely to partition tasks.
1164 >         *
1165 >         * In a steady state strict (tree-structured) computation,
1166 >         * each thread makes available for stealing enough tasks for
1167 >         * other threads to remain active. Inductively, if all threads
1168 >         * play by the same rules, each thread should make available
1169 >         * only a constant number of tasks.
1170 >         *
1171 >         * The minimum useful constant is just 1. But using a value of
1172 >         * 1 would require immediate replenishment upon each steal to
1173 >         * maintain enough tasks, which is infeasible.  Further,
1174 >         * partitionings/granularities of offered tasks should
1175 >         * minimize steal rates, which in general means that threads
1176 >         * nearer the top of computation tree should generate more
1177 >         * than those nearer the bottom. In perfect steady state, each
1178 >         * thread is at approximately the same level of computation
1179 >         * tree. However, producing extra tasks amortizes the
1180 >         * uncertainty of progress and diffusion assumptions.
1181 >         *
1182 >         * So, users will want to use values larger, but not much
1183 >         * larger than 1 to both smooth over transient shortages and
1184 >         * hedge against uneven progress; as traded off against the
1185 >         * cost of extra task overhead. We leave the user to pick a
1186 >         * threshold value to compare with the results of this call to
1187 >         * guide decisions, but recommend values such as 3.
1188 >         *
1189 >         * When all threads are active, it is on average OK to
1190 >         * estimate surplus strictly locally. In steady-state, if one
1191 >         * thread is maintaining say 2 surplus tasks, then so are
1192 >         * others. So we can just use estimated queue length.
1193 >         * However, this strategy alone leads to serious mis-estimates
1194 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1195 >         * other stalls). We can detect many of these by further
1196 >         * considering the number of "idle" threads, that are known to
1197 >         * have zero queued tasks, so compensate by a factor of
1198 >         * (#idle/#active) threads.
1199 >         */
1200 >        ForkJoinWorkerThread wt =
1201 >            (ForkJoinWorkerThread)Thread.currentThread();
1202 >        return wt.workQueue.queueSize() - wt.pool.idlePerActive();
1203 >    }
1204 >
1205 >    // Extension methods
1206 >
1207 >    /**
1208 >     * Returns the result that would be returned by {@link #join}, even
1209 >     * if this task completed abnormally, or {@code null} if this task
1210 >     * is not known to have been completed.  This method is designed
1211 >     * to aid debugging, as well as to support extensions. Its use in
1212 >     * any other context is discouraged.
1213 >     *
1214 >     * @return the result, or {@code null} if not completed
1215 >     */
1216 >    public abstract V getRawResult();
1217  
1218      /**
1219 <     * Completes this task abnormally, and if not already aborted or
1220 <     * cancelled, causes it to throw the given exception upon
1221 <     * <tt>join</tt> and related operations. This method may be used
1222 <     * to induce exceptions in asynchronous tasks, or to force
1223 <     * completion of tasks that would not otherwise complete.  This
644 <     * method is overridable, but overridden versions must invoke
645 <     * <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.
1219 >     * Forces the given value to be returned as a result.  This method
1220 >     * is designed to support extensions, and should not in general be
1221 >     * called otherwise.
1222 >     *
1223 >     * @param value the value
1224       */
1225 <    public void completeExceptionally(Throwable ex) {
651 <        setDoneExceptionally((ex instanceof RuntimeException) ||
652 <                             (ex instanceof Error)? ex :
653 <                             new RuntimeException(ex));
654 <    }
1225 >    protected abstract void setRawResult(V value);
1226  
1227      /**
1228 <     * Completes this task, and if not already aborted or cancelled,
1229 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
1230 <     * operations. This method may be used to provide results for
1231 <     * asynchronous tasks, or to provide alternative handling for
1232 <     * tasks that would not otherwise complete normally.
1228 >     * Immediately performs the base action of this task.  This method
1229 >     * is designed to support extensions, and should not in general be
1230 >     * called otherwise. The return value controls whether this task
1231 >     * is considered to be done normally. It may return false in
1232 >     * asynchronous actions that require explicit invocations of
1233 >     * {@link #complete} to become joinable. It may also throw an
1234 >     * (unchecked) exception to indicate abnormal exit.
1235       *
1236 <     * @param value the result value for this task.
1236 >     * @return {@code true} if completed normally
1237       */
1238 <    public void complete(V value) {
1239 <        try {
1240 <            setRawResult(value);
1241 <        } catch(Throwable rex) {
1242 <            setDoneExceptionally(rex);
1243 <            return;
1244 <        }
1245 <        setNormalCompletion();
1238 >    protected abstract boolean exec();
1239 >
1240 >    /**
1241 >     * Returns, but does not unschedule or execute, a task queued by
1242 >     * the current thread but not yet executed, if one is immediately
1243 >     * available. There is no guarantee that this task will actually
1244 >     * be polled or executed next. Conversely, this method may return
1245 >     * null even if a task exists but cannot be accessed without
1246 >     * contention with other threads.  This method is designed
1247 >     * primarily to support extensions, and is unlikely to be useful
1248 >     * otherwise.
1249 >     *
1250 >     * <p>This method may be invoked only from within {@code
1251 >     * ForkJoinPool} computations (as may be determined using method
1252 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1253 >     * result in exceptions or errors, possibly including {@code
1254 >     * ClassCastException}.
1255 >     *
1256 >     * @return the next task, or {@code null} if none are available
1257 >     */
1258 >    protected static ForkJoinTask<?> peekNextLocalTask() {
1259 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1260      }
1261  
1262      /**
1263 <     * Resets the internal bookkeeping state of this task, allowing a
1264 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
1265 <     * this task, but only if reuse occurs when this task has either
1266 <     * never been forked, or has been forked, then completed and all
1267 <     * outstanding joins of this task have also completed. Effects
1268 <     * under any other usage conditions are not guaranteed, and are
1269 <     * almost surely wrong. This method may be useful when executing
1270 <     * pre-constructed trees of subtasks in loops.
1263 >     * Unschedules and returns, without executing, the next task
1264 >     * queued by the current thread but not yet executed.  This method
1265 >     * is designed primarily to support extensions, and is unlikely to
1266 >     * be useful otherwise.
1267 >     *
1268 >     * <p>This method may be invoked only from within {@code
1269 >     * ForkJoinPool} computations (as may be determined using method
1270 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1271 >     * result in exceptions or errors, possibly including {@code
1272 >     * ClassCastException}.
1273 >     *
1274 >     * @return the next task, or {@code null} if none are available
1275       */
1276 <    public void reinitialize() {
1277 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
1278 <            exceptionMap.remove(this);
688 <        status = 0;
1276 >    protected static ForkJoinTask<?> pollNextLocalTask() {
1277 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1278 >            .workQueue.nextLocalTask();
1279      }
1280  
1281      /**
1282 <     * Tries to unschedule this task for execution. This method will
1283 <     * typically succeed if this task is the next task that would be
1284 <     * executed by the current thread, and will typically fail (return
1285 <     * false) otherwise. This method may be useful when arranging
1286 <     * faster local processing of tasks that could have been, but were
1287 <     * not, stolen.
1288 <     * @return true if unforked
1282 >     * Unschedules and returns, without executing, the next task
1283 >     * queued by the current thread but not yet executed, if one is
1284 >     * available, or if not available, a task that was forked by some
1285 >     * other thread, if available. Availability may be transient, so a
1286 >     * {@code null} result does not necessarily imply quiescence
1287 >     * of the pool this task is operating in.  This method is designed
1288 >     * primarily to support extensions, and is unlikely to be useful
1289 >     * otherwise.
1290 >     *
1291 >     * <p>This method may be invoked only from within {@code
1292 >     * ForkJoinPool} computations (as may be determined using method
1293 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1294 >     * result in exceptions or errors, possibly including {@code
1295 >     * ClassCastException}.
1296 >     *
1297 >     * @return a task, or {@code null} if none are available
1298       */
1299 <    public boolean tryUnfork() {
1300 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
1299 >    protected static ForkJoinTask<?> pollTask() {
1300 >        ForkJoinWorkerThread wt =
1301 >            (ForkJoinWorkerThread)Thread.currentThread();
1302 >        return wt.pool.nextTaskFor(wt.workQueue);
1303      }
1304  
1305 +    // Mark-bit operations
1306 +
1307      /**
1308 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
1309 <     * of them or an exception is encountered. This method may be
1310 <     * invoked only from within other ForkJoinTask
1311 <     * computations. Attempts to invoke in other contexts result in
709 <     * exceptions or errors including ClassCastException.
710 <     * @param t1 one task
711 <     * @param t2 the other task
712 <     * @throws NullPointerException if t1 or t2 are null
713 <     * @throws RuntimeException or Error if either task did so.
1308 >     * Returns true if this task is marked.
1309 >     *
1310 >     * @return true if this task is marked
1311 >     * @since 1.8
1312       */
1313 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
1314 <        t2.fork();
717 <        t1.invoke();
718 <        t2.join();
1313 >    public final boolean isMarkedForkJoinTask() {
1314 >        return (status & MARKED) != 0;
1315      }
1316  
1317      /**
1318 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
1319 <     * all of them. If any task encounters an exception, others may be
1320 <     * cancelled.  This method may be invoked only from within other
1321 <     * ForkJoinTask computations. Attempts to invoke in other contexts
726 <     * result in exceptions or errors including ClassCastException.
727 <     * @param tasks the array of tasks
728 <     * @throws NullPointerException if tasks or any element are null.
729 <     * @throws RuntimeException or Error if any task did so.
1318 >     * Atomically sets the mark on this task.
1319 >     *
1320 >     * @return true if this task was previously unmarked
1321 >     * @since 1.8
1322       */
1323 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
1324 <        Throwable ex = null;
1325 <        int last = tasks.length - 1;
1326 <        for (int i = last; i >= 0; --i) {
1327 <            ForkJoinTask<?> t = tasks[i];
1328 <            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 <            }
1323 >    public final boolean markForkJoinTask() {
1324 >        for (int s;;) {
1325 >            if (((s = status) & MARKED) != 0)
1326 >                return false;
1327 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1328 >                return true;
1329          }
760        if (ex != null)
761            rethrowException(ex);
1330      }
1331  
1332      /**
1333 <     * Forks all tasks in the collection, returning when
1334 <     * <tt>isDone</tt> holds for all of them. If any task encounters
1335 <     * an exception, others may be cancelled.  This method may be
1336 <     * 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.
1333 >     * Atomically clears the mark on this task.
1334 >     *
1335 >     * @return true if this task was previously marked
1336 >     * @since 1.8
1337       */
1338 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
1339 <        if (!(tasks instanceof List)) {
1340 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
1341 <            return;
1342 <        }
1343 <        List<? extends ForkJoinTask<?>> ts =
781 <            (List<? extends ForkJoinTask<?>>)tasks;
782 <        Throwable ex = null;
783 <        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 <            }
797 <        }
798 <        for (int i = 1; i <= last; ++i) {
799 <            ForkJoinTask<?> t = ts.get(i);
800 <            if (t != null) {
801 <                if (ex != null)
802 <                    t.cancel(false);
803 <                else {
804 <                    t.quietlyJoin();
805 <                    if (ex == null)
806 <                        ex = t.getException();
807 <                }
808 <            }
1338 >    public final boolean unmarkForkJoinTask() {
1339 >        for (int s;;) {
1340 >            if (((s = status) & MARKED) == 0)
1341 >                return false;
1342 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1343 >                return true;
1344          }
810        if (ex != null)
811            rethrowException(ex);
1345      }
1346  
1347      /**
1348 <     * Possibly executes tasks until the pool hosting the current task
1349 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
1350 <     * designs in which many tasks are forked, but none are explicitly
818 <     * joined, instead executing them until all are processed.
1348 >     * Adaptor for Runnables. This implements RunnableFuture
1349 >     * to be compliant with AbstractExecutorService constraints
1350 >     * when used in ForkJoinPool.
1351       */
1352 <    public static void helpQuiesce() {
1353 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
1354 <            helpQuiescePool();
1352 >    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1353 >        implements RunnableFuture<T> {
1354 >        final Runnable runnable;
1355 >        T result;
1356 >        AdaptedRunnable(Runnable runnable, T result) {
1357 >            if (runnable == null) throw new NullPointerException();
1358 >            this.runnable = runnable;
1359 >            this.result = result; // OK to set this even before completion
1360 >        }
1361 >        public final T getRawResult() { return result; }
1362 >        public final void setRawResult(T v) { result = v; }
1363 >        public final boolean exec() { runnable.run(); return true; }
1364 >        public final void run() { invoke(); }
1365 >        private static final long serialVersionUID = 5232453952276885070L;
1366      }
1367  
1368      /**
1369 <     * Returns a estimate of how many more locally queued tasks are
827 <     * held by the current worker thread than there are other worker
828 <     * threads that might want to steal them.  This value may be
829 <     * useful for heuristic decisions about whether to fork other
830 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
831 <     * 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
1369 >     * Adaptor for Runnables without results
1370       */
1371 <    public static int surplus() {
1372 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
1373 <            .getEstimatedSurplusTaskCount();
1371 >    static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1372 >        implements RunnableFuture<Void> {
1373 >        final Runnable runnable;
1374 >        AdaptedRunnableAction(Runnable runnable) {
1375 >            if (runnable == null) throw new NullPointerException();
1376 >            this.runnable = runnable;
1377 >        }
1378 >        public final Void getRawResult() { return null; }
1379 >        public final void setRawResult(Void v) { }
1380 >        public final boolean exec() { runnable.run(); return true; }
1381 >        public final void run() { invoke(); }
1382 >        private static final long serialVersionUID = 5232453952276885070L;
1383      }
1384  
1385 <    // Extension kit
1385 >    /**
1386 >     * Adaptor for Callables
1387 >     */
1388 >    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1389 >        implements RunnableFuture<T> {
1390 >        final Callable<? extends T> callable;
1391 >        T result;
1392 >        AdaptedCallable(Callable<? extends T> callable) {
1393 >            if (callable == null) throw new NullPointerException();
1394 >            this.callable = callable;
1395 >        }
1396 >        public final T getRawResult() { return result; }
1397 >        public final void setRawResult(T v) { result = v; }
1398 >        public final boolean exec() {
1399 >            try {
1400 >                result = callable.call();
1401 >                return true;
1402 >            } catch (Error err) {
1403 >                throw err;
1404 >            } catch (RuntimeException rex) {
1405 >                throw rex;
1406 >            } catch (Exception ex) {
1407 >                throw new RuntimeException(ex);
1408 >            }
1409 >        }
1410 >        public final void run() { invoke(); }
1411 >        private static final long serialVersionUID = 2838392045355241008L;
1412 >    }
1413  
1414      /**
1415 <     * Returns the result that would be returned by <tt>join</tt>, or
1416 <     * null if this task is not known to have been completed.  This
1417 <     * method is designed to aid debugging, as well as to support
847 <     * extensions. Its use in any other context is discouraged.
1415 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1416 >     * method of the given {@code Runnable} as its action, and returns
1417 >     * a null result upon {@link #join}.
1418       *
1419 <     * @return the result, or null if not completed.
1419 >     * @param runnable the runnable action
1420 >     * @return the task
1421       */
1422 <    public abstract V getRawResult();
1422 >    public static ForkJoinTask<?> adapt(Runnable runnable) {
1423 >        return new AdaptedRunnableAction(runnable);
1424 >    }
1425  
1426      /**
1427 <     * Forces the given value to be returned as a result.  This method
1428 <     * is designed to support extensions, and should not in general be
1429 <     * called otherwise.
1427 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1428 >     * method of the given {@code Runnable} as its action, and returns
1429 >     * the given result upon {@link #join}.
1430       *
1431 <     * @param value the value
1431 >     * @param runnable the runnable action
1432 >     * @param result the result upon completion
1433 >     * @return the task
1434       */
1435 <    protected abstract void setRawResult(V value);
1435 >    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1436 >        return new AdaptedRunnable<T>(runnable, result);
1437 >    }
1438  
1439      /**
1440 <     * Immediately performs the base action of this task.  This method
1441 <     * is designed to support extensions, and should not in general be
1442 <     * called otherwise. The return value controls whether this task
1443 <     * is considered to be done normally. It may return false in
1444 <     * asynchronous actions that require explicit invocations of
1445 <     * <tt>complete</tt> to become joinable. It may throw exceptions
1446 <     * to indicate abnormal exit.
870 <     * @return true if completed normally
871 <     * @throws Error or RuntimeException if encountered during computation
1440 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1441 >     * method of the given {@code Callable} as its action, and returns
1442 >     * its result upon {@link #join}, translating any checked exceptions
1443 >     * encountered into {@code RuntimeException}.
1444 >     *
1445 >     * @param callable the callable action
1446 >     * @return the task
1447       */
1448 <    protected abstract boolean exec();
1448 >    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1449 >        return new AdaptedCallable<T>(callable);
1450 >    }
1451  
1452      // Serialization support
1453  
1454      private static final long serialVersionUID = -7721805057305804111L;
1455  
1456      /**
1457 <     * Save the state to a stream.
1457 >     * Saves this task to a stream (that is, serializes it).
1458       *
1459       * @serialData the current run status and the exception thrown
1460 <     * during execution, or null if none.
884 <     * @param s the stream
1460 >     * during execution, or {@code null} if none
1461       */
1462      private void writeObject(java.io.ObjectOutputStream s)
1463          throws java.io.IOException {
# Line 890 | Line 1466 | public abstract class ForkJoinTask<V> im
1466      }
1467  
1468      /**
1469 <     * Reconstitute the instance from a stream.
894 <     * @param s the stream
1469 >     * Reconstitutes this task from a stream (that is, deserializes it).
1470       */
1471      private void readObject(java.io.ObjectInputStream s)
1472          throws java.io.IOException, ClassNotFoundException {
1473          s.defaultReadObject();
899        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1474          Object ex = s.readObject();
1475          if (ex != null)
1476 <            setDoneExceptionally((Throwable)ex);
1476 >            setExceptionalCompletion((Throwable)ex);
1477      }
1478  
1479 <    // Temporary Unsafe mechanics for preliminary release
1480 <
1481 <    static final Unsafe _unsafe;
908 <    static final long statusOffset;
909 <
1479 >    // Unsafe mechanics
1480 >    private static final sun.misc.Unsafe U;
1481 >    private static final long STATUS;
1482      static {
1483 +        exceptionTableLock = new ReentrantLock();
1484 +        exceptionTableRefQueue = new ReferenceQueue<Object>();
1485 +        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1486          try {
1487 <            if (ForkJoinTask.class.getClassLoader() != null) {
1488 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
914 <                f.setAccessible(true);
915 <                _unsafe = (Unsafe)f.get(null);
916 <            }
917 <            else
918 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
1487 >            U = getUnsafe();
1488 >            STATUS = U.objectFieldOffset
1489                  (ForkJoinTask.class.getDeclaredField("status"));
1490 <        } catch (Exception ex) { throw new Error(ex); }
1490 >        } catch (Exception e) {
1491 >            throw new Error(e);
1492 >        }
1493      }
1494  
1495 +    /**
1496 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1497 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1498 +     * into a jdk.
1499 +     *
1500 +     * @return a sun.misc.Unsafe
1501 +     */
1502 +    private static sun.misc.Unsafe getUnsafe() {
1503 +        try {
1504 +            return sun.misc.Unsafe.getUnsafe();
1505 +        } catch (SecurityException se) {
1506 +            try {
1507 +                return java.security.AccessController.doPrivileged
1508 +                    (new java.security
1509 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1510 +                        public sun.misc.Unsafe run() throws Exception {
1511 +                            java.lang.reflect.Field f = sun.misc
1512 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1513 +                            f.setAccessible(true);
1514 +                            return (sun.misc.Unsafe) f.get(null);
1515 +                        }});
1516 +            } catch (java.security.PrivilegedActionException e) {
1517 +                throw new RuntimeException("Could not initialize intrinsics",
1518 +                                           e.getCause());
1519 +            }
1520 +        }
1521 +    }
1522   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines