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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines