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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines