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.27 by dl, Sun Aug 2 11:54:31 2009 UTC vs.
Revision 1.46 by dl, Mon Apr 5 15:52:26 2010 UTC

# Line 12 | Line 12 | import java.io.Serializable;
12   import java.util.Collection;
13   import java.util.Collections;
14   import java.util.List;
15 + import java.util.RandomAccess;
16   import java.util.Map;
17   import java.util.WeakHashMap;
18  
# Line 22 | Line 23 | import java.util.WeakHashMap;
23   * subtasks may be hosted by a small number of actual threads in a
24   * ForkJoinPool, at the price of some usage limitations.
25   *
26 < * <p> A "main" ForkJoinTask begins execution when submitted to a
27 < * {@link ForkJoinPool}. Once started, it will usually in turn start
28 < * other subtasks.  As indicated by the name of this class, many
29 < * programs using ForkJoinTasks employ only methods {@code fork} and
30 < * {@code join}, or derivatives such as {@code invokeAll}.  However,
31 < * this class also provides a number of other methods that can come
32 < * into play in advanced usages, as well as extension mechanics that
33 < * allow support of new forms of fork/join processing.
26 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
28 > * start other subtasks.  As indicated by the name of this class,
29 > * many programs using {@code ForkJoinTask} employ only methods
30 > * {@link #fork} and {@link #join}, or derivatives such as {@link
31 > * #invokeAll}.  However, this class also provides a number of other
32 > * methods that can come into play in advanced usages, as well as
33 > * extension mechanics that allow support of new forms of fork/join
34 > * processing.
35   *
36 < * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
37 < * efficiency of ForkJoinTasks stems from a set of restrictions (that
38 < * are only partially statically enforceable) reflecting their
39 < * intended use as computational tasks calculating pure functions or
40 < * operating on purely isolated objects.  The primary coordination
41 < * mechanisms are {@link #fork}, that arranges asynchronous execution,
42 < * and {@link #join}, that doesn't proceed until the task's result has
43 < * been computed.  Computations should avoid {@code synchronized}
44 < * methods or blocks, and should minimize other blocking
45 < * synchronization apart from joining other tasks or using
46 < * synchronizers such as Phasers that are advertised to cooperate with
47 < * fork/join scheduling. Tasks should also not perform blocking IO,
48 < * and should ideally access variables that are completely independent
49 < * of those accessed by other running tasks. Minor breaches of these
50 < * restrictions, for example using shared output streams, may be
51 < * tolerable in practice, but frequent use may result in poor
52 < * performance, and the potential to indefinitely stall if the number
53 < * of threads not waiting for IO or other external synchronization
54 < * becomes exhausted. This usage restriction is in part enforced by
55 < * not permitting checked exceptions such as {@code IOExceptions}
56 < * to be thrown. However, computations may still encounter unchecked
57 < * exceptions, that are rethrown to callers attempting join
58 < * them. These exceptions may additionally include
59 < * RejectedExecutionExceptions stemming from internal resource
60 < * exhaustion such as failure to allocate internal task queues.
36 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37 > * The efficiency of {@code ForkJoinTask}s stems from a set of
38 > * restrictions (that are only partially statically enforceable)
39 > * reflecting their intended use as computational tasks calculating
40 > * pure functions or operating on purely isolated objects.  The
41 > * primary coordination mechanisms are {@link #fork}, that arranges
42 > * asynchronous execution, and {@link #join}, that doesn't proceed
43 > * until the task's result has been computed.  Computations should
44 > * avoid {@code synchronized} methods or blocks, and should minimize
45 > * other blocking synchronization apart from joining other tasks or
46 > * using synchronizers such as Phasers that are advertised to
47 > * cooperate with fork/join scheduling. Tasks should also not perform
48 > * blocking IO, and should ideally access variables that are
49 > * completely independent of those accessed by other running
50 > * tasks. Minor breaches of these restrictions, for example using
51 > * shared output streams, may be tolerable in practice, but frequent
52 > * use may result in poor performance, and the potential to
53 > * indefinitely stall if the number of threads not waiting for IO or
54 > * other external synchronization becomes exhausted. This usage
55 > * restriction is in part enforced by not permitting checked
56 > * exceptions such as {@code IOExceptions} to be thrown. However,
57 > * computations may still encounter unchecked exceptions, that are
58 > * rethrown to callers attempting to join them. These exceptions may
59 > * additionally include {@link RejectedExecutionException} stemming
60 > * from internal resource exhaustion, such as failure to allocate
61 > * internal task queues.
62   *
63   * <p>The primary method for awaiting completion and extracting
64   * results of a task is {@link #join}, but there are several variants:
# Line 65 | Line 68 | import java.util.WeakHashMap;
68   * execute other tasks while awaiting joins, which is sometimes more
69   * efficient but only applies when all subtasks are known to be
70   * strictly tree-structured. Method {@link #invoke} is semantically
71 < * equivalent to {@code fork(); join()} but always attempts to
72 < * begin execution in the current thread. The "<em>quiet</em>" forms
73 < * of these methods do not extract results or report exceptions. These
71 > * equivalent to {@code fork(); join()} but always attempts to begin
72 > * execution in the current thread. The "<em>quiet</em>" forms of
73 > * these methods do not extract results or report exceptions. These
74   * may be useful when a set of tasks are being executed, and you need
75   * to delay processing of results or exceptions until all complete.
76   * Method {@code invokeAll} (available in multiple versions)
77   * performs the most common form of parallel invocation: forking a set
78   * of tasks and joining them all.
79   *
80 < * <p> The ForkJoinTask class is not usually directly subclassed.
80 > * <p>The execution status of tasks may be queried at several levels
81 > * of detail: {@link #isDone} is true if a task completed in any way
82 > * (including the case where a task was cancelled without executing);
83 > * {@link #isCompletedNormally} is true if a task completed without
84 > * cancellation or encountering an exception; {@link #isCancelled} is
85 > * true if the task was cancelled (in which case {@link #getException}
86 > * returns a {@link java.util.concurrent.CancellationException}); and
87 > * {@link #isCompletedAbnormally} is true if a task was either
88 > * cancelled or encountered an exception, in which case {@link
89 > * #getException} will return either the encountered exception or
90 > * {@link java.util.concurrent.CancellationException}.
91 > *
92 > * <p>The ForkJoinTask class is not usually directly subclassed.
93   * Instead, you subclass one of the abstract classes that support a
94   * particular style of fork/join processing, typically {@link
95   * RecursiveAction} for computations that do not return results, or
# Line 83 | Line 98 | import java.util.WeakHashMap;
98   * established in a constructor, and then defines a {@code compute}
99   * method that somehow uses the control methods supplied by this base
100   * class. While these methods have {@code public} access (to allow
101 < * instances of different task subclasses to call each others
101 > * instances of different task subclasses to call each other's
102   * methods), some of them may only be called from within other
103   * ForkJoinTasks (as may be determined using method {@link
104   * #inForkJoinPool}).  Attempts to invoke them in other contexts
105   * result in exceptions or errors, possibly including
106   * ClassCastException.
107   *
108 < * <p>Most base support methods are {@code final} because their
109 < * implementations are intrinsically tied to the underlying
110 < * lightweight task scheduling framework, and so cannot be overridden.
111 < * Developers creating new basic styles of fork/join processing should
112 < * minimally implement {@code protected} methods
113 < * {@link #exec}, {@link #setRawResult}, and
114 < * {@link #getRawResult}, while also introducing an abstract
115 < * computational method that can be implemented in its subclasses,
116 < * possibly relying on other {@code protected} methods provided
102 < * by this class.
108 > * <p>Most base support methods are {@code final}, to prevent
109 > * overriding of implementations that are intrinsically tied to the
110 > * underlying lightweight task scheduling framework.  Developers
111 > * creating new basic styles of fork/join processing should minimally
112 > * implement {@code protected} methods {@link #exec}, {@link
113 > * #setRawResult}, and {@link #getRawResult}, while also introducing
114 > * an abstract computational method that can be implemented in its
115 > * subclasses, possibly relying on other {@code protected} methods
116 > * provided by this class.
117   *
118   * <p>ForkJoinTasks should perform relatively small amounts of
119 < * computations, otherwise splitting into smaller tasks. As a very
120 < * rough rule of thumb, a task should perform more than 100 and less
121 < * than 10000 basic computational steps. If tasks are too big, then
122 < * parallelism cannot improve throughput. If too small, then memory
123 < * and internal task maintenance overhead may overwhelm processing.
119 > * computation. Large tasks should be split into smaller subtasks,
120 > * usually via recursive decomposition. As a very rough rule of thumb,
121 > * a task should perform more than 100 and less than 10000 basic
122 > * computational steps. If tasks are too big, then parallelism cannot
123 > * improve throughput. If too small, then memory and internal task
124 > * maintenance overhead may overwhelm processing.
125   *
126 < * <p>This class provides {@code adapt} methods for {@link
127 < * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
128 < * may be of use when mixing execution of ForkJoinTasks with other
129 < * kinds of tasks. When all tasks are of this form, consider using a
130 < * pool in {@link ForkJoinPool#setAsyncMode}.
126 > * <p>This class provides {@code adapt} methods for {@link Runnable}
127 > * and {@link Callable}, that may be of use when mixing execution of
128 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
129 > * are of this form, consider using a pool in
130 > * {@linkplain ForkJoinPool#setAsyncMode async mode}.
131   *
132 < * <p>ForkJoinTasks are {@code Serializable}, which enables them
133 < * to be used in extensions such as remote execution frameworks. It is
134 < * in general sensible to serialize tasks only before or after, but
135 < * not during execution. Serialization is not relied on during
121 < * execution itself.
132 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
133 > * used in extensions such as remote execution frameworks. It is
134 > * sensible to serialize tasks only before or after, but not during,
135 > * execution. Serialization is not relied on during execution itself.
136   *
137   * @since 1.7
138   * @author Doug Lea
139   */
140   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
141  
142 +    /*
143 +     * See the internal documentation of class ForkJoinPool for a
144 +     * general implementation overview.  ForkJoinTasks are mainly
145 +     * responsible for maintaining their "status" field amidst relays
146 +     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
147 +     * methods of this class are more-or-less layered into (1) basic
148 +     * status maintenance (2) execution and awaiting completion (3)
149 +     * user-level methods that additionally report results. This is
150 +     * sometimes hard to see because this file orders exported methods
151 +     * in a way that flows well in javadocs.
152 +     */
153 +
154      /**
155       * Run control status bits packed into a single int to minimize
156       * footprint and to ensure atomicity (via CAS).  Status is
# Line 134 | Line 160 | public abstract class ForkJoinTask<V> im
160       * blocking waits by other threads have SIGNAL_MASK bits set --
161       * bit 15 for external (nonFJ) waits, and the rest a count of
162       * waiting FJ threads.  (This representation relies on
163 <     * ForkJoinPool max thread limits). Completion of a stolen task
164 <     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
165 <     * though suboptimal for some purposes, we use basic builtin
166 <     * wait/notify to take advantage of "monitor inflation" in JVMs
167 <     * that we would otherwise need to emulate to avoid adding further
168 <     * per-task bookkeeping overhead. Note that bits 16-28 are
169 <     * currently unused. Also value 0x80000000 is available as spare
170 <     * completion value.
163 >     * ForkJoinPool max thread limits). Signal counts are not directly
164 >     * incremented by ForkJoinTask methods, but instead via a call to
165 >     * requestSignal within ForkJoinPool.preJoin, once their need is
166 >     * established.
167 >     *
168 >     * Completion of a stolen task with SIGNAL_MASK bits set awakens
169 >     * any waiters via notifyAll. Even though suboptimal for some
170 >     * purposes, we use basic builtin wait/notify to take advantage of
171 >     * "monitor inflation" in JVMs that we would otherwise need to
172 >     * emulate to avoid adding further per-task bookkeeping overhead.
173 >     * We want these monitors to be "fat", i.e., not use biasing or
174 >     * thin-lock techniques, so use some odd coding idioms that tend
175 >     * to avoid them.
176 >     *
177 >     * Note that bits 16-28 are currently unused. Also value
178 >     * 0x80000000 is available as spare completion value.
179       */
180      volatile int status; // accessed directly by pool and workers
181  
182 <    static final int COMPLETION_MASK      = 0xe0000000;
183 <    static final int NORMAL               = 0xe0000000; // == mask
184 <    static final int CANCELLED            = 0xc0000000;
185 <    static final int EXCEPTIONAL          = 0xa0000000;
186 <    static final int SIGNAL_MASK          = 0x0000ffff;
187 <    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
188 <    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
182 >    private static final int COMPLETION_MASK      = 0xe0000000;
183 >    private static final int NORMAL               = 0xe0000000; // == mask
184 >    private static final int CANCELLED            = 0xc0000000;
185 >    private static final int EXCEPTIONAL          = 0xa0000000;
186 >    private static final int SIGNAL_MASK          = 0x0000ffff;
187 >    private static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
188 >    private static final int EXTERNAL_SIGNAL      = 0x00008000;
189  
190      /**
191       * Table of exceptions thrown by tasks, to enable reporting by
# Line 165 | Line 199 | public abstract class ForkJoinTask<V> im
199          Collections.synchronizedMap
200          (new WeakHashMap<ForkJoinTask<?>, Throwable>());
201  
202 <    // within-package utilities
202 >    // Maintaining completion status
203  
204      /**
205 <     * Gets current worker thread, or null if not a worker thread.
205 >     * Marks completion and wakes up threads waiting to join this task,
206 >     * also clearing signal request bits.
207 >     *
208 >     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
209       */
210 <    static ForkJoinWorkerThread getWorker() {
211 <        Thread t = Thread.currentThread();
212 <        return ((t instanceof ForkJoinWorkerThread) ?
213 <                (ForkJoinWorkerThread) t : null);
214 <    }
215 <
216 <    final boolean casStatus(int cmp, int val) {
217 <        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
210 >    private void setCompletion(int completion) {
211 >        int s;
212 >        while ((s = status) >= 0) {
213 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
214 >                if ((s & SIGNAL_MASK) != 0) {
215 >                    Thread t = Thread.currentThread();
216 >                    if (t instanceof ForkJoinWorkerThread)
217 >                        ((ForkJoinWorkerThread) t).pool.updateRunningCount
218 >                            (s & INTERNAL_SIGNAL_MASK);
219 >                    synchronized (this) { notifyAll(); }
220 >                }
221 >                return;
222 >            }
223 >        }
224      }
225  
226      /**
227 <     * Workaround for not being able to rethrow unchecked exceptions.
227 >     * Record exception and set exceptional completion
228       */
229 <    static void rethrowException(Throwable ex) {
230 <        if (ex != null)
231 <            UNSAFE.throwException(ex);
229 >    private void setDoneExceptionally(Throwable rex) {
230 >        exceptionMap.put(this, rex);
231 >        setCompletion(EXCEPTIONAL);
232      }
233  
191    // Setting completion status
192
234      /**
235 <     * Marks completion and wakes up threads waiting to join this task.
235 >     * Main internal execution method: Unless done, calls exec and
236 >     * records completion.
237       *
238 <     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
238 >     * @return true if ran and completed normally
239       */
240 <    final void setCompletion(int completion) {
241 <        ForkJoinPool pool = getPool();
242 <        if (pool != null) {
243 <            int s; // Clear signal bits while setting completion status
244 <            do {} while ((s = status) >= 0 && !casStatus(s, completion));
245 <
246 <            if ((s & SIGNAL_MASK) != 0) {
205 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
206 <                    pool.updateRunningCount(s);
207 <                synchronized (this) { notifyAll(); }
208 <            }
240 >    final boolean tryExec() {
241 >        try {
242 >            if (status < 0 || !exec())
243 >                return false;
244 >        } catch (Throwable rex) {
245 >            setDoneExceptionally(rex);
246 >            return false;
247          }
248 <        else
249 <            externallySetCompletion(completion);
248 >        setCompletion(NORMAL); // must be outside try block
249 >        return true;
250      }
251  
252      /**
253 <     * Version of setCompletion for non-FJ threads.  Leaves signal
254 <     * bits for unblocked threads to adjust, and always notifies.
253 >     * Increments internal signal count (thus requesting signal upon
254 >     * completion) unless already done.  Call only once per join.
255 >     * Used by ForkJoinPool.preJoin.
256 >     *
257 >     * @return status
258       */
259 <    private void externallySetCompletion(int completion) {
259 >    final int requestSignal() {
260          int s;
261 <        do {} while ((s = status) >= 0 &&
262 <                     !casStatus(s, (s & SIGNAL_MASK) | completion));
263 <        synchronized (this) { notifyAll(); }
261 >        do {} while ((s = status) >= 0 &&
262 >                     !UNSAFE.compareAndSwapInt(this, statusOffset, s, s + 1));
263 >        return s;
264      }
265 <
265 >    
266      /**
267 <     * Sets status to indicate normal completion.
267 >     * Sets external signal request unless already done.
268 >     *
269 >     * @return status
270       */
271 <    final void setNormalCompletion() {
272 <        // Try typical fast case -- single CAS, no signal, not already done.
273 <        // Manually expand casStatus to improve chances of inlining it
274 <        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
275 <            setCompletion(NORMAL);
271 >    private int requestExternalSignal() {
272 >        int s;
273 >        do {} while ((s = status) >= 0 &&
274 >                     !UNSAFE.compareAndSwapInt(this, statusOffset,
275 >                                               s, s | EXTERNAL_SIGNAL));
276 >        return s;
277      }
278  
279 <    // internal waiting and notification
280 <
281 <    /**
282 <     * Performs the actual monitor wait for awaitDone.
279 >    /*
280 >     * Awaiting completion. The four versions, internal vs external X
281 >     * untimed vs timed, have the same overall structure but differ
282 >     * from each other enough to defy simple integration.
283       */
240    private void doAwaitDone() {
241        // Minimize lock bias and in/de-flation effects by maximizing
242        // chances of waiting inside sync
243        try {
244            while (status >= 0)
245                synchronized (this) { if (status >= 0) wait(); }
246        } catch (InterruptedException ie) {
247            onInterruptedWait();
248        }
249    }
284  
285      /**
286 <     * Performs the actual timed monitor wait for awaitDone.
286 >     * Blocks a worker until this task is done, also maintaining pool
287 >     * and signal counts
288       */
289 <    private void doAwaitDone(long startTime, long nanos) {
290 <        synchronized (this) {
291 <            try {
292 <                while (status >= 0) {
293 <                    long nt = nanos - (System.nanoTime() - startTime);
294 <                    if (nt <= 0)
295 <                        break;
296 <                    wait(nt / 1000000, (int) (nt % 1000000));
289 >    private void awaitDone(ForkJoinWorkerThread w) {
290 >        if (status >= 0) {
291 >            w.pool.preJoin(this);
292 >            while (status >= 0) {
293 >                try { // minimize lock scope
294 >                    synchronized(this) {
295 >                        if (status >= 0)
296 >                            wait();
297 >                        else { // help release; also helps avoid lock-biasing
298 >                            notifyAll();
299 >                            break;
300 >                        }
301 >                    }
302 >                } catch (InterruptedException ie) {
303 >                    cancelIfTerminating();
304                  }
263            } catch (InterruptedException ie) {
264                onInterruptedWait();
305              }
306          }
307      }
308  
269    // Awaiting completion
270
309      /**
310 <     * Sets status to indicate there is joiner, then waits for join,
273 <     * surrounded with pool notifications.
274 <     *
275 <     * @return status upon exit
310 >     * Blocks a non-ForkJoin thread until this task is done.
311       */
312 <    private int awaitDone(ForkJoinWorkerThread w,
313 <                          boolean maintainParallelism) {
314 <        ForkJoinPool pool = (w == null) ? null : w.pool;
315 <        int s;
316 <        while ((s = status) >= 0) {
317 <            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
318 <                if (pool == null || !pool.preJoin(this, maintainParallelism))
319 <                    doAwaitDone();
320 <                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
321 <                    adjustPoolCountsOnUnblock(pool);
322 <                break;
312 >    private void externalAwaitDone() {
313 >        if (requestExternalSignal() >= 0) {
314 >            boolean interrupted = false;
315 >            while (status >= 0) {
316 >                try {
317 >                    synchronized(this) {
318 >                        if (status >= 0)
319 >                            wait();
320 >                        else {
321 >                            notifyAll();
322 >                            break;
323 >                        }
324 >                    }
325 >                } catch (InterruptedException ie) {
326 >                    interrupted = true;
327 >                }
328              }
329 +            if (interrupted)
330 +                Thread.currentThread().interrupt();
331          }
290        return s;
332      }
333  
334      /**
335 <     * Timed version of awaitDone
295 <     *
296 <     * @return status upon exit
335 >     * Blocks a worker until this task is done or timeout elapses
336       */
337 <    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
338 <        ForkJoinPool pool = (w == null) ? null : w.pool;
339 <        int s;
340 <        while ((s = status) >= 0) {
341 <            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
342 <                long startTime = System.nanoTime();
343 <                if (pool == null || !pool.preJoin(this, false))
344 <                    doAwaitDone(startTime, nanos);
345 <                if ((s = status) >= 0) {
346 <                    adjustPoolCountsOnCancelledWait(pool);
347 <                    s = status;
337 >    private void timedAwaitDone(ForkJoinWorkerThread w, long nanos) {
338 >        if (status >= 0) {
339 >            long startTime = System.nanoTime();
340 >            ForkJoinPool pool = w.pool;
341 >            pool.preJoin(this);
342 >            while (status >= 0) {
343 >                long nt = nanos - (System.nanoTime() - startTime);
344 >                if (nt > 0) {
345 >                    long ms = nt / 1000000;
346 >                    int ns = (int) (nt % 1000000);
347 >                    try {
348 >                        synchronized(this) { if (status >= 0) wait(ms, ns); }
349 >                    } catch (InterruptedException ie) {
350 >                        cancelIfTerminating();
351 >                    }
352 >                }
353 >                else {
354 >                    int s; // adjust running count on timeout
355 >                    while ((s = status) >= 0 &&
356 >                           (s & INTERNAL_SIGNAL_MASK) != 0) {
357 >                        if (UNSAFE.compareAndSwapInt(this, statusOffset,
358 >                                                     s, s - 1)) {
359 >                            pool.updateRunningCount(1);
360 >                            break;
361 >                        }
362 >                    }
363 >                    break;
364                  }
310                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
311                    adjustPoolCountsOnUnblock(pool);
312                break;
365              }
366          }
315        return s;
367      }
368  
369      /**
370 <     * Notifies pool that thread is unblocked. Called by signalled
320 <     * threads when woken by non-FJ threads (which is atypical).
370 >     * Blocks a non-ForkJoin thread until this task is done or timeout elapses
371       */
372 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
373 <        int s;
374 <        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
375 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
376 <            pool.updateRunningCount(s);
377 <    }
378 <
329 <    /**
330 <     * Notifies pool to adjust counts on cancelled or timed out wait.
331 <     */
332 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
333 <        if (pool != null) {
334 <            int s;
335 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
336 <                if (casStatus(s, s - 1)) {
337 <                    pool.updateRunningCount(1);
372 >    private void externalTimedAwaitDone(long nanos) {
373 >        if (requestExternalSignal() >= 0) {
374 >            long startTime = System.nanoTime();
375 >            boolean interrupted = false;
376 >            while (status >= 0) {
377 >                long nt = nanos - (System.nanoTime() - startTime);
378 >                if (nt <= 0)
379                      break;
380 +                long ms = nt / 1000000;
381 +                int ns = (int) (nt % 1000000);
382 +                try {
383 +                    synchronized(this) { if (status >= 0) wait(ms, ns); }
384 +                } catch (InterruptedException ie) {
385 +                    interrupted = true;
386                  }
387              }
388 +            if (interrupted)
389 +                Thread.currentThread().interrupt();
390          }
391      }
392  
393 <    /**
345 <     * Handles interruptions during waits.
346 <     */
347 <    private void onInterruptedWait() {
348 <        ForkJoinWorkerThread w = getWorker();
349 <        if (w == null)
350 <            Thread.currentThread().interrupt(); // re-interrupt
351 <        else if (w.isTerminating())
352 <            cancelIgnoringExceptions();
353 <        // else if FJworker, ignore interrupt
354 <    }
355 <
356 <    // Recording and reporting exceptions
357 <
358 <    private void setDoneExceptionally(Throwable rex) {
359 <        exceptionMap.put(this, rex);
360 <        setCompletion(EXCEPTIONAL);
361 <    }
393 >    // reporting results
394  
395      /**
396 <     * Throws the exception associated with status s.
397 <     *
398 <     * @throws the exception
396 >     * Returns result or throws the exception associated with status.
397 >     * Uses Unsafe as a workaround for javac not allowing rethrow of
398 >     * unchecked exceptions.
399       */
400 <    private void reportException(int s) {
401 <        if ((s &= COMPLETION_MASK) < NORMAL) {
402 <            if (s == CANCELLED)
403 <                throw new CancellationException();
404 <            else
373 <                rethrowException(exceptionMap.get(this));
400 >    private V reportResult() {
401 >        if ((status & COMPLETION_MASK) < NORMAL) {
402 >            Throwable ex = getException();
403 >            if (ex != null)
404 >                UNSAFE.throwException(ex);
405          }
406 +        return getRawResult();
407      }
408  
409      /**
410       * Returns result or throws exception using j.u.c.Future conventions.
411 <     * Only call when {@code isDone} known to be true.
411 >     * Only call when {@code isDone} known to be true or thread known
412 >     * to be interrupted.
413       */
414      private V reportFutureResult()
415 <        throws ExecutionException, InterruptedException {
415 >        throws InterruptedException, ExecutionException {
416 >        if (Thread.interrupted())
417 >            throw new InterruptedException();
418          int s = status & COMPLETION_MASK;
419          if (s < NORMAL) {
420              Throwable ex;
# Line 387 | Line 422 | public abstract class ForkJoinTask<V> im
422                  throw new CancellationException();
423              if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
424                  throw new ExecutionException(ex);
390            if (Thread.interrupted())
391                throw new InterruptedException();
425          }
426          return getRawResult();
427      }
# Line 399 | Line 432 | public abstract class ForkJoinTask<V> im
432       */
433      private V reportTimedFutureResult()
434          throws InterruptedException, ExecutionException, TimeoutException {
435 +        if (Thread.interrupted())
436 +            throw new InterruptedException();
437          Throwable ex;
438          int s = status & COMPLETION_MASK;
439          if (s == NORMAL)
440              return getRawResult();
441 <        if (s == CANCELLED)
441 >        else if (s == CANCELLED)
442              throw new CancellationException();
443 <        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
443 >        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
444              throw new ExecutionException(ex);
445 <        if (Thread.interrupted())
446 <            throw new InterruptedException();
412 <        throw new TimeoutException();
413 <    }
414 <
415 <    // internal execution methods
416 <
417 <    /**
418 <     * Calls exec, recording completion, and rethrowing exception if
419 <     * encountered. Caller should normally check status before calling.
420 <     *
421 <     * @return true if completed normally
422 <     */
423 <    private boolean tryExec() {
424 <        try { // try block must contain only call to exec
425 <            if (!exec())
426 <                return false;
427 <        } catch (Throwable rex) {
428 <            setDoneExceptionally(rex);
429 <            rethrowException(rex);
430 <            return false; // not reached
431 <        }
432 <        setNormalCompletion();
433 <        return true;
434 <    }
435 <
436 <    /**
437 <     * Main execution method used by worker threads. Invokes
438 <     * base computation unless already complete.
439 <     */
440 <    final void quietlyExec() {
441 <        if (status >= 0) {
442 <            try {
443 <                if (!exec())
444 <                    return;
445 <            } catch (Throwable rex) {
446 <                setDoneExceptionally(rex);
447 <                return;
448 <            }
449 <            setNormalCompletion();
450 <        }
451 <    }
452 <
453 <    /**
454 <     * Calls exec(), recording but not rethrowing exception.
455 <     * Caller should normally check status before calling.
456 <     *
457 <     * @return true if completed normally
458 <     */
459 <    private boolean tryQuietlyInvoke() {
460 <        try {
461 <            if (!exec())
462 <                return false;
463 <        } catch (Throwable rex) {
464 <            setDoneExceptionally(rex);
465 <            return false;
466 <        }
467 <        setNormalCompletion();
468 <        return true;
469 <    }
470 <
471 <    /**
472 <     * Cancels, ignoring any exceptions it throws.
473 <     */
474 <    final void cancelIgnoringExceptions() {
475 <        try {
476 <            cancel(false);
477 <        } catch (Throwable ignore) {
478 <        }
479 <    }
480 <
481 <    /**
482 <     * Main implementation of helpJoin
483 <     */
484 <    private int busyJoin(ForkJoinWorkerThread w) {
485 <        int s;
486 <        ForkJoinTask<?> t;
487 <        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
488 <            t.quietlyExec();
489 <        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
445 >        else
446 >            throw new TimeoutException();
447      }
448  
449      // public methods
# Line 494 | Line 451 | public abstract class ForkJoinTask<V> im
451      /**
452       * Arranges to asynchronously execute this task.  While it is not
453       * necessarily enforced, it is a usage error to fork a task more
454 <     * than once unless it has completed and been reinitialized.  This
455 <     * method may be invoked only from within ForkJoinTask
456 <     * computations (as may be determined using method {@link
457 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
458 <     * in exceptions or errors, possibly including ClassCastException.
454 >     * than once unless it has completed and been reinitialized.
455 >     * Subsequent modifications to the state of this task or any data
456 >     * it operates on are not necessarily consistently observable by
457 >     * any thread other than the one executing it unless preceded by a
458 >     * call to {@link #join} or related methods, or a call to {@link
459 >     * #isDone} returning {@code true}.
460 >     *
461 >     * <p>This method may be invoked only from within {@code
462 >     * ForkJoinTask} computations (as may be determined using method
463 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
464 >     * result in exceptions or errors, possibly including {@code
465 >     * ClassCastException}.
466       *
467 <     * @return {@code this}, to simplify usage.
467 >     * @return {@code this}, to simplify usage
468       */
469      public final ForkJoinTask<V> fork() {
470          ((ForkJoinWorkerThread) Thread.currentThread())
# Line 509 | Line 473 | public abstract class ForkJoinTask<V> im
473      }
474  
475      /**
476 <     * Returns the result of the computation when it is ready.
477 <     * This method differs from {@code get} in that abnormal
478 <     * completion results in RuntimeExceptions or Errors, not
479 <     * ExecutionExceptions.
476 >     * Returns the result of the computation when it {@link #isDone is done}.
477 >     * This method differs from {@link #get()} in that
478 >     * abnormal completion results in {@code RuntimeException} or
479 >     * {@code Error}, not {@code ExecutionException}.
480       *
481       * @return the computed result
482       */
483      public final V join() {
484 <        ForkJoinWorkerThread w = getWorker();
485 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
522 <            reportException(awaitDone(w, true));
523 <        return getRawResult();
484 >        quietlyJoin();
485 >        return reportResult();
486      }
487  
488      /**
489       * Commences performing this task, awaits its completion if
490 <     * necessary, and return its result.
490 >     * necessary, and return its result, or throws an (unchecked)
491 >     * exception if the underlying computation did so.
492       *
530     * @throws Throwable (a RuntimeException, Error, or unchecked
531     * exception) if the underlying computation did so
493       * @return the computed result
494       */
495      public final V invoke() {
496 <        if (status >= 0 && tryExec())
497 <            return getRawResult();
498 <        else
538 <            return join();
496 >        if (!tryExec())
497 >            quietlyJoin();
498 >        return reportResult();
499      }
500  
501      /**
502       * Forks the given tasks, returning when {@code isDone} holds for
503 <     * each task or an exception is encountered. This method may be
504 <     * invoked only from within ForkJoinTask computations (as may be
505 <     * determined using method {@link #inForkJoinPool}). Attempts to
506 <     * invoke in other contexts result in exceptions or errors,
507 <     * possibly including ClassCastException.
503 >     * each task or an (unchecked) exception is encountered, in which
504 >     * case the exception is rethrown.  If either task encounters an
505 >     * exception, the other one may be, but is not guaranteed to be,
506 >     * cancelled.  If both tasks throw an exception, then this method
507 >     * throws one of them.  The individual status of each task may be
508 >     * checked using {@link #getException()} and related methods.
509 >     *
510 >     * <p>This method may be invoked only from within {@code
511 >     * ForkJoinTask} computations (as may be determined using method
512 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
513 >     * result in exceptions or errors, possibly including {@code
514 >     * ClassCastException}.
515       *
516       * @param t1 the first task
517       * @param t2 the second task
518       * @throws NullPointerException if any task is null
552     * @throws RuntimeException or Error if a task did so
519       */
520 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
520 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
521          t2.fork();
522          t1.invoke();
523          t2.join();
# Line 559 | Line 525 | public abstract class ForkJoinTask<V> im
525  
526      /**
527       * Forks the given tasks, returning when {@code isDone} holds for
528 <     * each task or an exception is encountered. If any task
529 <     * encounters an exception, others may be, but are not guaranteed
530 <     * to be, cancelled.  This method may be invoked only from within
531 <     * ForkJoinTask computations (as may be determined using method
532 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
533 <     * result in exceptions or errors, possibly including
534 <     * ClassCastException.
535 <     *
536 <     * Overloadings of this method exist for the special cases
537 <     * of one to four arguments.
528 >     * each task or an (unchecked) exception is encountered, in which
529 >     * case the exception is rethrown. If any task encounters an
530 >     * exception, others may be, but are not guaranteed to be,
531 >     * cancelled.  If more than one task encounters an exception, then
532 >     * this method throws any one of these exceptions.  The individual
533 >     * status of each task may be checked using {@link #getException()}
534 >     * and related methods.
535 >     *
536 >     * <p>This method may be invoked only from within {@code
537 >     * ForkJoinTask} computations (as may be determined using method
538 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
539 >     * result in exceptions or errors, possibly including {@code
540 >     * ClassCastException}.
541       *
542       * @param tasks the tasks
543 <     * @throws NullPointerException if tasks or any element are null
575 <     * @throws RuntimeException or Error if any task did so
543 >     * @throws NullPointerException if any task is null
544       */
545      public static void invokeAll(ForkJoinTask<?>... tasks) {
546          Throwable ex = null;
# Line 604 | Line 572 | public abstract class ForkJoinTask<V> im
572              }
573          }
574          if (ex != null)
575 <            rethrowException(ex);
575 >            UNSAFE.throwException(ex);
576      }
577  
578      /**
579 <     * Forks all tasks in the collection, returning when {@code
580 <     * isDone} holds for each task or an exception is encountered. If
581 <     * any task encounters an exception, others may be, but are not
582 <     * guaranteed to be, cancelled.  This method may be invoked only
583 <     * from within ForkJoinTask computations (as may be determined
584 <     * using method {@link #inForkJoinPool}). Attempts to invoke in
585 <     * other contexts result in exceptions or errors, possibly
586 <     * including ClassCastException.
579 >     * Forks all tasks in the specified collection, returning when
580 >     * {@code isDone} holds for each task or an (unchecked) exception
581 >     * is encountered.  If any task encounters an exception, others
582 >     * may be, but are not guaranteed to be, cancelled.  If more than
583 >     * one task encounters an exception, then this method throws any
584 >     * one of these exceptions.  The individual status of each task
585 >     * may be checked using {@link #getException()} and related
586 >     * methods.  The behavior of this operation is undefined if the
587 >     * specified collection is modified while the operation is in
588 >     * progress.
589 >     *
590 >     * <p>This method may be invoked only from within {@code
591 >     * ForkJoinTask} computations (as may be determined using method
592 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
593 >     * result in exceptions or errors, possibly including {@code
594 >     * ClassCastException}.
595       *
596       * @param tasks the collection of tasks
597       * @return the tasks argument, to simplify usage
598       * @throws NullPointerException if tasks or any element are null
623     * @throws RuntimeException or Error if any task did so
599       */
600      public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
601 <        if (!(tasks instanceof List<?>)) {
601 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
602              invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
603              return tasks;
604          }
# Line 659 | Line 634 | public abstract class ForkJoinTask<V> im
634              }
635          }
636          if (ex != null)
637 <            rethrowException(ex);
637 >            UNSAFE.throwException(ex);
638          return tasks;
639      }
640  
641      /**
642 <     * Returns {@code true} if the computation performed by this task
643 <     * has completed (or has been cancelled).
644 <     *
645 <     * @return {@code true} if this computation has completed
646 <     */
647 <    public final boolean isDone() {
648 <        return status < 0;
674 <    }
675 <
676 <    /**
677 <     * Returns {@code true} if this task was cancelled.
678 <     *
679 <     * @return {@code true} if this task was cancelled
680 <     */
681 <    public final boolean isCancelled() {
682 <        return (status & COMPLETION_MASK) == CANCELLED;
683 <    }
684 <
685 <    /**
686 <     * Asserts that the results of this task's computation will not be
687 <     * used. If a cancellation occurs before attempting to execute this
688 <     * task, execution will be suppressed, {@link #isCancelled}
689 <     * will report true, and {@link #join} will result in a
690 <     * {@code CancellationException} being thrown. Otherwise, when
691 <     * cancellation races with completion, there are no guarantees
692 <     * about whether {@code isCancelled} will report {@code true},
693 <     * whether {@code join} will return normally or via an exception,
694 <     * or whether these behaviors will remain consistent upon repeated
695 <     * invocation.
642 >     * Attempts to cancel execution of this task. This attempt will
643 >     * fail if the task has already completed, has already been
644 >     * cancelled, or could not be cancelled for some other reason. If
645 >     * successful, and this task has not started when cancel is
646 >     * called, execution of this task is suppressed, {@link
647 >     * #isCancelled} will report true, and {@link #join} will result
648 >     * in a {@code CancellationException} being thrown.
649       *
650       * <p>This method may be overridden in subclasses, but if so, must
651       * still ensure that these minimal properties hold. In particular,
652 <     * the cancel method itself must not throw exceptions.
652 >     * the {@code cancel} method itself must not throw exceptions.
653       *
654 <     * <p> This method is designed to be invoked by <em>other</em>
654 >     * <p>This method is designed to be invoked by <em>other</em>
655       * tasks. To terminate the current task, you can just return or
656       * throw an unchecked exception from its computation method, or
657       * invoke {@link #completeExceptionally}.
658       *
659       * @param mayInterruptIfRunning this value is ignored in the
660 <     * default implementation because tasks are not in general
660 >     * default implementation because tasks are not
661       * cancelled via interruption
662       *
663       * @return {@code true} if this task is now cancelled
# Line 715 | Line 668 | public abstract class ForkJoinTask<V> im
668      }
669  
670      /**
671 +     * Cancels, ignoring any exceptions it throws. Used during worker
672 +     * and pool shutdown.
673 +     */
674 +    final void cancelIgnoringExceptions() {
675 +        try {
676 +            cancel(false);
677 +        } catch (Throwable ignore) {
678 +        }
679 +    }
680 +
681 +    /**
682 +     * Cancels ignoring exceptions if worker is terminating
683 +     */
684 +    private void cancelIfTerminating() {
685 +        Thread t = Thread.currentThread();
686 +        if ((t instanceof ForkJoinWorkerThread) &&
687 +            ((ForkJoinWorkerThread) t).isTerminating()) {
688 +            try {
689 +                cancel(false);
690 +            } catch (Throwable ignore) {
691 +            }
692 +        }
693 +    }
694 +
695 +    public final boolean isDone() {
696 +        return status < 0;
697 +    }
698 +
699 +    public final boolean isCancelled() {
700 +        return (status & COMPLETION_MASK) == CANCELLED;
701 +    }
702 +
703 +    /**
704       * Returns {@code true} if this task threw an exception or was cancelled.
705       *
706       * @return {@code true} if this task threw an exception or was cancelled
# Line 724 | Line 710 | public abstract class ForkJoinTask<V> im
710      }
711  
712      /**
713 +     * Returns {@code true} if this task completed without throwing an
714 +     * exception and was not cancelled.
715 +     *
716 +     * @return {@code true} if this task completed without throwing an
717 +     * exception and was not cancelled
718 +     */
719 +    public final boolean isCompletedNormally() {
720 +        return (status & COMPLETION_MASK) == NORMAL;
721 +    }
722 +
723 +    /**
724       * Returns the exception thrown by the base computation, or a
725 <     * CancellationException if cancelled, or null if none or if the
726 <     * method has not yet completed.
725 >     * {@code CancellationException} if cancelled, or {@code null} if
726 >     * none or if the method has not yet completed.
727       *
728       * @return the exception, or {@code null} if none
729       */
730      public final Throwable getException() {
731          int s = status & COMPLETION_MASK;
732 <        if (s >= NORMAL)
733 <            return null;
734 <        if (s == CANCELLED)
738 <            return new CancellationException();
739 <        return exceptionMap.get(this);
732 >        return ((s >= NORMAL)    ? null :
733 >                (s == CANCELLED) ? new CancellationException() :
734 >                exceptionMap.get(this));
735      }
736  
737      /**
# Line 749 | Line 744 | public abstract class ForkJoinTask<V> im
744       * overridable, but overridden versions must invoke {@code super}
745       * implementation to maintain guarantees.
746       *
747 <     * @param ex the exception to throw. If this exception is
748 <     * not a RuntimeException or Error, the actual exception thrown
749 <     * will be a RuntimeException with cause ex.
747 >     * @param ex the exception to throw. If this exception is not a
748 >     * {@code RuntimeException} or {@code Error}, the actual exception
749 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
750       */
751      public void completeExceptionally(Throwable ex) {
752          setDoneExceptionally((ex instanceof RuntimeException) ||
# Line 778 | Line 773 | public abstract class ForkJoinTask<V> im
773              setDoneExceptionally(rex);
774              return;
775          }
776 <        setNormalCompletion();
776 >        setCompletion(NORMAL);
777      }
778  
779      public final V get() throws InterruptedException, ExecutionException {
780 <        ForkJoinWorkerThread w = getWorker();
786 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
787 <            awaitDone(w, true);
780 >        quietlyJoin();
781          return reportFutureResult();
782      }
783 <
783 >    
784      public final V get(long timeout, TimeUnit unit)
785          throws InterruptedException, ExecutionException, TimeoutException {
786          long nanos = unit.toNanos(timeout);
787 <        ForkJoinWorkerThread w = getWorker();
788 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
789 <            awaitDone(w, nanos);
787 >        Thread t = Thread.currentThread();
788 >        if (t instanceof ForkJoinWorkerThread) {
789 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
790 >            if (!w.unpushTask(this) || !tryExec())
791 >                timedAwaitDone(w, nanos);
792 >        }
793 >        else
794 >            externalTimedAwaitDone(nanos);
795          return reportTimedFutureResult();
796      }
797  
798      /**
799 <     * Possibly executes other tasks until this task is ready, then
800 <     * returns the result of the computation.  This method may be more
801 <     * efficient than {@code join}, but is only applicable when
802 <     * there are no potential dependencies between continuation of the
803 <     * current task and that of any other task that might be executed
804 <     * while helping. (This usually holds for pure divide-and-conquer
805 <     * tasks). This method may be invoked only from within
806 <     * ForkJoinTask computations (as may be determined using method
807 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
808 <     * result in exceptions or errors, possibly including
809 <     * ClassCastException.
799 >     * Possibly executes other tasks until this task {@link #isDone is
800 >     * done}, then returns the result of the computation.  This method
801 >     * may be more efficient than {@code join}, but is only applicable
802 >     * when there are no potential dependencies between continuation
803 >     * of the current task and that of any other task that might be
804 >     * executed while helping. (This usually holds for pure
805 >     * divide-and-conquer tasks).
806 >     *
807 >     * <p>This method may be invoked only from within {@code
808 >     * ForkJoinTask} computations (as may be determined using method
809 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
810 >     * result in exceptions or errors, possibly including {@code
811 >     * ClassCastException}.
812       *
813       * @return the computed result
814       */
815      public final V helpJoin() {
816 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
817 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
818 <            reportException(busyJoin(w));
819 <        return getRawResult();
816 >        quietlyHelpJoin();
817 >        return reportResult();
818      }
819  
820      /**
821 <     * Possibly executes other tasks until this task is ready.  This
822 <     * method may be invoked only from within ForkJoinTask
823 <     * computations (as may be determined using method {@link
824 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
825 <     * in exceptions or errors, possibly including ClassCastException.
821 >     * Possibly executes other tasks until this task {@link #isDone is
822 >     * done}.  This method may be useful when processing collections
823 >     * of tasks when some have been cancelled or otherwise known to
824 >     * have aborted.
825 >     *
826 >     * <p>This method may be invoked only from within {@code
827 >     * ForkJoinTask} computations (as may be determined using method
828 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
829 >     * result in exceptions or errors, possibly including {@code
830 >     * ClassCastException}.
831       */
832      public final void quietlyHelpJoin() {
833 <        if (status >= 0) {
834 <            ForkJoinWorkerThread w =
835 <                (ForkJoinWorkerThread) Thread.currentThread();
836 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
837 <                busyJoin(w);
833 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
834 >        if (!w.unpushTask(this) || !tryExec()) {
835 >            while (status >= 0) {
836 >                ForkJoinTask<?> t = w.scanWhileJoining(this);
837 >                if (t == null) {
838 >                    if (status >= 0)
839 >                        awaitDone(w);
840 >                    break;
841 >                }
842 >                t.tryExec();
843 >            }
844          }
845      }
846  
# Line 842 | Line 851 | public abstract class ForkJoinTask<V> im
851       * known to have aborted.
852       */
853      public final void quietlyJoin() {
854 <        if (status >= 0) {
855 <            ForkJoinWorkerThread w = getWorker();
856 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
857 <                awaitDone(w, true);
854 >        Thread t = Thread.currentThread();
855 >        if (t instanceof ForkJoinWorkerThread) {
856 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
857 >            if (!w.unpushTask(this) || !tryExec())
858 >                awaitDone(w);
859          }
860 +        else
861 +            externalAwaitDone();
862      }
863  
864      /**
# Line 857 | Line 869 | public abstract class ForkJoinTask<V> im
869       * known to have aborted.
870       */
871      public final void quietlyInvoke() {
872 <        if (status >= 0 && !tryQuietlyInvoke())
872 >        if (!tryExec())
873              quietlyJoin();
874      }
875  
876      /**
877       * Possibly executes tasks until the pool hosting the current task
878 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
879 <     * designs in which many tasks are forked, but none are explicitly
880 <     * joined, instead executing them until all are processed.  This
881 <     * method may be invoked only from within ForkJoinTask
882 <     * computations (as may be determined using method {@link
883 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
884 <     * in exceptions or errors, possibly including ClassCastException.
878 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
879 >     * be of use in designs in which many tasks are forked, but none
880 >     * are explicitly joined, instead executing them until all are
881 >     * processed.
882 >     *
883 >     * <p>This method may be invoked only from within {@code
884 >     * ForkJoinTask} computations (as may be determined using method
885 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
886 >     * result in exceptions or errors, possibly including {@code
887 >     * ClassCastException}.
888       */
889      public static void helpQuiesce() {
890          ((ForkJoinWorkerThread) Thread.currentThread())
# Line 882 | Line 897 | public abstract class ForkJoinTask<V> im
897       * this task, but only if reuse occurs when this task has either
898       * never been forked, or has been forked, then completed and all
899       * outstanding joins of this task have also completed. Effects
900 <     * under any other usage conditions are not guaranteed, and are
901 <     * discouraged. This method may be useful when executing
900 >     * under any other usage conditions are not guaranteed.
901 >     * This method may be useful when executing
902       * pre-constructed trees of subtasks in loops.
903       */
904      public void reinitialize() {
# Line 922 | Line 937 | public abstract class ForkJoinTask<V> im
937       * by the current thread, and has not commenced executing in
938       * another thread.  This method may be useful when arranging
939       * alternative local processing of tasks that could have been, but
940 <     * were not, stolen. This method may be invoked only from within
941 <     * ForkJoinTask computations (as may be determined using method
942 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
943 <     * result in exceptions or errors, possibly including
944 <     * ClassCastException.
940 >     * were not, stolen.
941 >     *
942 >     * <p>This method may be invoked only from within {@code
943 >     * ForkJoinTask} computations (as may be determined using method
944 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
945 >     * result in exceptions or errors, possibly including {@code
946 >     * ClassCastException}.
947       *
948       * @return {@code true} if unforked
949       */
# Line 939 | Line 956 | public abstract class ForkJoinTask<V> im
956       * Returns an estimate of the number of tasks that have been
957       * forked by the current worker thread but not yet executed. This
958       * value may be useful for heuristic decisions about whether to
959 <     * fork other tasks.  This method may be invoked only from within
960 <     * ForkJoinTask computations (as may be determined using method
961 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
962 <     * result in exceptions or errors, possibly including
963 <     * ClassCastException.
959 >     * fork other tasks.
960 >     *
961 >     * <p>This method may be invoked only from within {@code
962 >     * ForkJoinTask} computations (as may be determined using method
963 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
964 >     * result in exceptions or errors, possibly including {@code
965 >     * ClassCastException}.
966 >     *
967       * @return the number of tasks
968       */
969      public static int getQueuedTaskCount() {
# Line 959 | Line 979 | public abstract class ForkJoinTask<V> im
979       * usages of ForkJoinTasks, at steady state, each worker should
980       * aim to maintain a small constant surplus (for example, 3) of
981       * tasks, and to process computations locally if this threshold is
982 <     * exceeded.  This method may be invoked only from within
983 <     * ForkJoinTask computations (as may be determined using method
984 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
985 <     * result in exceptions or errors, possibly including
986 <     * ClassCastException.  *
982 >     * exceeded.
983 >     *
984 >     * <p>This method may be invoked only from within {@code
985 >     * ForkJoinTask} computations (as may be determined using method
986 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
987 >     * result in exceptions or errors, possibly including {@code
988 >     * ClassCastException}.
989 >     *
990       * @return the surplus number of tasks, which may be negative
991       */
992      public static int getSurplusQueuedTaskCount() {
# Line 999 | Line 1022 | public abstract class ForkJoinTask<V> im
1022       * called otherwise. The return value controls whether this task
1023       * is considered to be done normally. It may return false in
1024       * asynchronous actions that require explicit invocations of
1025 <     * {@link #complete} to become joinable. It may throw exceptions
1026 <     * to indicate abnormal exit.
1025 >     * {@link #complete} to become joinable. It may also throw an
1026 >     * (unchecked) exception to indicate abnormal exit.
1027       *
1028       * @return {@code true} if completed normally
1006     * @throws Error or RuntimeException if encountered during computation
1029       */
1030      protected abstract boolean exec();
1031  
# Line 1015 | Line 1037 | public abstract class ForkJoinTask<V> im
1037       * null even if a task exists but cannot be accessed without
1038       * contention with other threads.  This method is designed
1039       * primarily to support extensions, and is unlikely to be useful
1040 <     * otherwise.  This method may be invoked only from within
1041 <     * ForkJoinTask computations (as may be determined using method
1042 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1043 <     * result in exceptions or errors, possibly including
1044 <     * ClassCastException.
1040 >     * otherwise.
1041 >     *
1042 >     * <p>This method may be invoked only from within {@code
1043 >     * ForkJoinTask} computations (as may be determined using method
1044 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1045 >     * result in exceptions or errors, possibly including {@code
1046 >     * ClassCastException}.
1047       *
1048       * @return the next task, or {@code null} if none are available
1049       */
# Line 1032 | Line 1056 | public abstract class ForkJoinTask<V> im
1056       * Unschedules and returns, without executing, the next task
1057       * queued by the current thread but not yet executed.  This method
1058       * is designed primarily to support extensions, and is unlikely to
1059 <     * be useful otherwise.  This method may be invoked only from
1060 <     * within ForkJoinTask computations (as may be determined using
1061 <     * method {@link #inForkJoinPool}). Attempts to invoke in other
1062 <     * contexts result in exceptions or errors, possibly including
1063 <     * ClassCastException.
1059 >     * be useful otherwise.
1060 >     *
1061 >     * <p>This method may be invoked only from within {@code
1062 >     * ForkJoinTask} computations (as may be determined using method
1063 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1064 >     * result in exceptions or errors, possibly including {@code
1065 >     * ClassCastException}.
1066       *
1067       * @return the next task, or {@code null} if none are available
1068       */
# Line 1053 | Line 1079 | public abstract class ForkJoinTask<V> im
1079       * {@code null} result does not necessarily imply quiescence
1080       * of the pool this task is operating in.  This method is designed
1081       * primarily to support extensions, and is unlikely to be useful
1082 <     * otherwise.  This method may be invoked only from within
1083 <     * ForkJoinTask computations (as may be determined using method
1084 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1085 <     * result in exceptions or errors, possibly including
1086 <     * ClassCastException.
1082 >     * otherwise.
1083 >     *
1084 >     * <p>This method may be invoked only from within {@code
1085 >     * ForkJoinTask} computations (as may be determined using method
1086 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1087 >     * result in exceptions or errors, possibly including {@code
1088 >     * ClassCastException}.
1089       *
1090       * @return a task, or {@code null} if none are available
1091       */
# Line 1122 | Line 1150 | public abstract class ForkJoinTask<V> im
1150      }
1151  
1152      /**
1153 <     * Returns a new ForkJoinTask that performs the {@code run}
1154 <     * method of the given Runnable as its action, and returns a null
1155 <     * result upon {@code join}.
1153 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1154 >     * method of the given {@code Runnable} as its action, and returns
1155 >     * a null result upon {@link #join}.
1156       *
1157       * @param runnable the runnable action
1158       * @return the task
# Line 1134 | Line 1162 | public abstract class ForkJoinTask<V> im
1162      }
1163  
1164      /**
1165 <     * Returns a new ForkJoinTask that performs the {@code run}
1166 <     * method of the given Runnable as its action, and returns the
1167 <     * given result upon {@code join}.
1165 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1166 >     * method of the given {@code Runnable} as its action, and returns
1167 >     * the given result upon {@link #join}.
1168       *
1169       * @param runnable the runnable action
1170       * @param result the result upon completion
# Line 1147 | Line 1175 | public abstract class ForkJoinTask<V> im
1175      }
1176  
1177      /**
1178 <     * Returns a new ForkJoinTask that performs the {@code call}
1179 <     * method of the given Callable as its action, and returns its
1180 <     * result upon {@code join}, translating any checked
1181 <     * exceptions encountered into {@code RuntimeException}.
1178 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1179 >     * method of the given {@code Callable} as its action, and returns
1180 >     * its result upon {@link #join}, translating any checked exceptions
1181 >     * encountered into {@code RuntimeException}.
1182       *
1183       * @param callable the callable action
1184       * @return the task
# Line 1164 | Line 1192 | public abstract class ForkJoinTask<V> im
1192      private static final long serialVersionUID = -7721805057305804111L;
1193  
1194      /**
1195 <     * Save the state to a stream.
1195 >     * Saves the state to a stream.
1196       *
1197       * @serialData the current run status and the exception thrown
1198       * during execution, or {@code null} if none
# Line 1177 | Line 1205 | public abstract class ForkJoinTask<V> im
1205      }
1206  
1207      /**
1208 <     * Reconstitute the instance from a stream.
1208 >     * Reconstitutes the instance from a stream.
1209       *
1210       * @param s the stream
1211       */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines