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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines