ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.36
Committed: Sun Nov 21 20:26:59 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.35: +11 -6 lines
Log Message:
cancel() spec improvements

File Contents

# User Rev Content
1 jsr166 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
5     */
6    
7     package java.util.concurrent;
8    
9     import java.io.Serializable;
10     import java.util.Collection;
11     import java.util.Collections;
12     import java.util.List;
13 jsr166 1.7 import java.util.RandomAccess;
14 jsr166 1.1 import java.util.Map;
15     import java.util.WeakHashMap;
16 dl 1.32 import java.util.concurrent.Callable;
17     import java.util.concurrent.CancellationException;
18     import java.util.concurrent.ExecutionException;
19     import java.util.concurrent.Executor;
20     import java.util.concurrent.ExecutorService;
21     import java.util.concurrent.Future;
22     import java.util.concurrent.RejectedExecutionException;
23     import java.util.concurrent.RunnableFuture;
24     import java.util.concurrent.TimeUnit;
25     import java.util.concurrent.TimeoutException;
26 jsr166 1.1
27     /**
28 jsr166 1.6 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
29     * A {@code ForkJoinTask} is a thread-like entity that is much
30 jsr166 1.1 * lighter weight than a normal thread. Huge numbers of tasks and
31     * subtasks may be hosted by a small number of actual threads in a
32     * ForkJoinPool, at the price of some usage limitations.
33     *
34 jsr166 1.6 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
35     * to a {@link ForkJoinPool}. Once started, it will usually in turn
36     * start other subtasks. As indicated by the name of this class,
37     * many programs using {@code ForkJoinTask} employ only methods
38     * {@link #fork} and {@link #join}, or derivatives such as {@link
39 jsr166 1.27 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
40     * provides a number of other methods that can come into play in
41     * advanced usages, as well as extension mechanics that allow
42     * support of new forms of fork/join processing.
43 jsr166 1.1 *
44 jsr166 1.6 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
45     * The efficiency of {@code ForkJoinTask}s stems from a set of
46     * restrictions (that are only partially statically enforceable)
47     * reflecting their intended use as computational tasks calculating
48     * pure functions or operating on purely isolated objects. The
49     * primary coordination mechanisms are {@link #fork}, that arranges
50     * asynchronous execution, and {@link #join}, that doesn't proceed
51     * until the task's result has been computed. Computations should
52     * avoid {@code synchronized} methods or blocks, and should minimize
53     * other blocking synchronization apart from joining other tasks or
54     * using synchronizers such as Phasers that are advertised to
55     * cooperate with fork/join scheduling. Tasks should also not perform
56     * blocking IO, and should ideally access variables that are
57     * completely independent of those accessed by other running
58     * tasks. Minor breaches of these restrictions, for example using
59     * shared output streams, may be tolerable in practice, but frequent
60     * use may result in poor performance, and the potential to
61     * indefinitely stall if the number of threads not waiting for IO or
62     * other external synchronization becomes exhausted. This usage
63     * restriction is in part enforced by not permitting checked
64     * exceptions such as {@code IOExceptions} to be thrown. However,
65     * computations may still encounter unchecked exceptions, that are
66 jsr166 1.7 * rethrown to callers attempting to join them. These exceptions may
67 jsr166 1.11 * additionally include {@link RejectedExecutionException} stemming
68     * from internal resource exhaustion, such as failure to allocate
69     * internal task queues.
70 jsr166 1.1 *
71     * <p>The primary method for awaiting completion and extracting
72     * results of a task is {@link #join}, but there are several variants:
73     * The {@link Future#get} methods support interruptible and/or timed
74     * waits for completion and report results using {@code Future}
75 dl 1.16 * conventions. Method {@link #invoke} is semantically
76 jsr166 1.8 * equivalent to {@code fork(); join()} but always attempts to begin
77     * execution in the current thread. The "<em>quiet</em>" forms of
78     * these methods do not extract results or report exceptions. These
79 jsr166 1.1 * may be useful when a set of tasks are being executed, and you need
80     * to delay processing of results or exceptions until all complete.
81     * Method {@code invokeAll} (available in multiple versions)
82     * performs the most common form of parallel invocation: forking a set
83     * of tasks and joining them all.
84     *
85 jsr166 1.8 * <p>The execution status of tasks may be queried at several levels
86     * of detail: {@link #isDone} is true if a task completed in any way
87     * (including the case where a task was cancelled without executing);
88     * {@link #isCompletedNormally} is true if a task completed without
89 jsr166 1.10 * cancellation or encountering an exception; {@link #isCancelled} is
90     * true if the task was cancelled (in which case {@link #getException}
91     * returns a {@link java.util.concurrent.CancellationException}); and
92     * {@link #isCompletedAbnormally} is true if a task was either
93     * cancelled or encountered an exception, in which case {@link
94     * #getException} will return either the encountered exception or
95     * {@link java.util.concurrent.CancellationException}.
96 jsr166 1.8 *
97 jsr166 1.6 * <p>The ForkJoinTask class is not usually directly subclassed.
98 jsr166 1.1 * Instead, you subclass one of the abstract classes that support a
99 jsr166 1.6 * particular style of fork/join processing, typically {@link
100     * RecursiveAction} for computations that do not return results, or
101     * {@link RecursiveTask} for those that do. Normally, a concrete
102 jsr166 1.1 * ForkJoinTask subclass declares fields comprising its parameters,
103     * established in a constructor, and then defines a {@code compute}
104     * method that somehow uses the control methods supplied by this base
105     * class. While these methods have {@code public} access (to allow
106 jsr166 1.7 * instances of different task subclasses to call each other's
107 jsr166 1.1 * methods), some of them may only be called from within other
108     * ForkJoinTasks (as may be determined using method {@link
109     * #inForkJoinPool}). Attempts to invoke them in other contexts
110     * result in exceptions or errors, possibly including
111 dl 1.20 * {@code ClassCastException}.
112 jsr166 1.1 *
113 jsr166 1.7 * <p>Most base support methods are {@code final}, to prevent
114     * overriding of implementations that are intrinsically tied to the
115     * underlying lightweight task scheduling framework. Developers
116     * creating new basic styles of fork/join processing should minimally
117     * implement {@code protected} methods {@link #exec}, {@link
118     * #setRawResult}, and {@link #getRawResult}, while also introducing
119     * an abstract computational method that can be implemented in its
120     * subclasses, possibly relying on other {@code protected} methods
121     * provided by this class.
122 jsr166 1.1 *
123     * <p>ForkJoinTasks should perform relatively small amounts of
124 jsr166 1.7 * computation. Large tasks should be split into smaller subtasks,
125     * usually via recursive decomposition. As a very rough rule of thumb,
126     * a task should perform more than 100 and less than 10000 basic
127     * computational steps. If tasks are too big, then parallelism cannot
128     * improve throughput. If too small, then memory and internal task
129     * maintenance overhead may overwhelm processing.
130 jsr166 1.1 *
131 jsr166 1.8 * <p>This class provides {@code adapt} methods for {@link Runnable}
132     * and {@link Callable}, that may be of use when mixing execution of
133 dl 1.16 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
134     * of this form, consider using a pool constructed in <em>asyncMode</em>.
135 jsr166 1.6 *
136 jsr166 1.7 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
137     * used in extensions such as remote execution frameworks. It is
138     * sensible to serialize tasks only before or after, but not during,
139     * execution. Serialization is not relied on during execution itself.
140 jsr166 1.1 *
141     * @since 1.7
142     * @author Doug Lea
143     */
144     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
145    
146 dl 1.13 /*
147     * See the internal documentation of class ForkJoinPool for a
148     * general implementation overview. ForkJoinTasks are mainly
149     * responsible for maintaining their "status" field amidst relays
150     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
151     * methods of this class are more-or-less layered into (1) basic
152     * status maintenance (2) execution and awaiting completion (3)
153     * user-level methods that additionally report results. This is
154     * sometimes hard to see because this file orders exported methods
155 dl 1.17 * in a way that flows well in javadocs. In particular, most
156     * join mechanics are in method quietlyJoin, below.
157 dl 1.13 */
158    
159 dl 1.17 /*
160     * The status field holds run control status bits packed into a
161     * single int to minimize footprint and to ensure atomicity (via
162     * CAS). Status is initially zero, and takes on nonnegative
163     * values until completed, upon which status holds value
164 jsr166 1.23 * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
165 dl 1.17 * waits by other threads have the SIGNAL bit set. Completion of
166     * a stolen task with SIGNAL set awakens any waiters via
167     * notifyAll. Even though suboptimal for some purposes, we use
168     * basic builtin wait/notify to take advantage of "monitor
169     * inflation" in JVMs that we would otherwise need to emulate to
170     * avoid adding further per-task bookkeeping overhead. We want
171     * these monitors to be "fat", i.e., not use biasing or thin-lock
172     * techniques, so use some odd coding idioms that tend to avoid
173     * them.
174 jsr166 1.1 */
175 dl 1.17
176     /** The run status of this task */
177 jsr166 1.1 volatile int status; // accessed directly by pool and workers
178    
179 dl 1.16 private static final int NORMAL = -1;
180     private static final int CANCELLED = -2;
181     private static final int EXCEPTIONAL = -3;
182     private static final int SIGNAL = 1;
183 jsr166 1.1
184     /**
185     * Table of exceptions thrown by tasks, to enable reporting by
186     * callers. Because exceptions are rare, we don't directly keep
187     * them with task objects, but instead use a weak ref table. Note
188     * that cancellation exceptions don't appear in the table, but are
189     * instead recorded as status values.
190     * TODO: Use ConcurrentReferenceHashMap
191     */
192     static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
193     Collections.synchronizedMap
194     (new WeakHashMap<ForkJoinTask<?>, Throwable>());
195    
196 dl 1.13 // Maintaining completion status
197 jsr166 1.1
198     /**
199 dl 1.13 * Marks completion and wakes up threads waiting to join this task,
200     * also clearing signal request bits.
201     *
202     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
203 jsr166 1.1 */
204 dl 1.17 private void setCompletion(int completion) {
205 dl 1.13 int s;
206     while ((s = status) >= 0) {
207     if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
208 dl 1.17 if (s != 0)
209 dl 1.13 synchronized (this) { notifyAll(); }
210 dl 1.17 break;
211 dl 1.13 }
212     }
213 jsr166 1.1 }
214    
215     /**
216 jsr166 1.21 * Records exception and sets exceptional completion.
217 jsr166 1.24 *
218 dl 1.15 * @return status on exit
219 jsr166 1.1 */
220 dl 1.17 private void setExceptionalCompletion(Throwable rex) {
221 dl 1.13 exceptionMap.put(this, rex);
222 dl 1.17 setCompletion(EXCEPTIONAL);
223 jsr166 1.1 }
224    
225     /**
226 dl 1.19 * Blocks a worker thread until completion. Called only by
227     * pool. Currently unused -- pool-based waits use timeout
228     * version below.
229 jsr166 1.1 */
230 dl 1.17 final void internalAwaitDone() {
231     int s; // the odd construction reduces lock bias effects
232 dl 1.15 while ((s = status) >= 0) {
233 dl 1.17 try {
234 jsr166 1.26 synchronized (this) {
235 dl 1.17 if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
236     wait();
237 jsr166 1.1 }
238 dl 1.17 } catch (InterruptedException ie) {
239     cancelIfTerminating();
240 jsr166 1.1 }
241     }
242     }
243    
244     /**
245 dl 1.19 * Blocks a worker thread until completed or timed out. Called
246     * only by pool.
247     *
248     * @return status on exit
249     */
250 dl 1.32 final int internalAwaitDone(long millis, int nanos) {
251 dl 1.19 int s;
252     if ((s = status) >= 0) {
253     try {
254 jsr166 1.26 synchronized (this) {
255 dl 1.19 if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
256 dl 1.32 wait(millis, nanos);
257 dl 1.19 }
258     } catch (InterruptedException ie) {
259     cancelIfTerminating();
260     }
261     s = status;
262     }
263     return s;
264     }
265    
266     /**
267 dl 1.15 * Blocks a non-worker-thread until completion.
268 jsr166 1.1 */
269 dl 1.17 private void externalAwaitDone() {
270 dl 1.15 int s;
271     while ((s = status) >= 0) {
272 jsr166 1.26 synchronized (this) {
273 jsr166 1.31 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
274 dl 1.15 boolean interrupted = false;
275 dl 1.17 while (status >= 0) {
276 dl 1.15 try {
277 dl 1.14 wait();
278 dl 1.15 } catch (InterruptedException ie) {
279     interrupted = true;
280 dl 1.13 }
281 dl 1.17 }
282 dl 1.15 if (interrupted)
283     Thread.currentThread().interrupt();
284     break;
285 dl 1.13 }
286 jsr166 1.1 }
287     }
288     }
289    
290     /**
291 dl 1.15 * Unless done, calls exec and records status if completed, but
292 dl 1.16 * doesn't wait for completion otherwise. Primary execution method
293     * for ForkJoinWorkerThread.
294 jsr166 1.1 */
295 dl 1.17 final void quietlyExec() {
296 dl 1.15 try {
297     if (status < 0 || !exec())
298     return;
299     } catch (Throwable rex) {
300     setExceptionalCompletion(rex);
301     return;
302 jsr166 1.1 }
303 dl 1.15 setCompletion(NORMAL); // must be outside try block
304 jsr166 1.1 }
305    
306     // public methods
307    
308     /**
309     * Arranges to asynchronously execute this task. While it is not
310     * necessarily enforced, it is a usage error to fork a task more
311 jsr166 1.6 * than once unless it has completed and been reinitialized.
312 jsr166 1.11 * Subsequent modifications to the state of this task or any data
313     * it operates on are not necessarily consistently observable by
314     * any thread other than the one executing it unless preceded by a
315     * call to {@link #join} or related methods, or a call to {@link
316     * #isDone} returning {@code true}.
317 jsr166 1.6 *
318     * <p>This method may be invoked only from within {@code
319     * ForkJoinTask} computations (as may be determined using method
320     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
321     * result in exceptions or errors, possibly including {@code
322     * ClassCastException}.
323 jsr166 1.2 *
324 jsr166 1.6 * @return {@code this}, to simplify usage
325 jsr166 1.1 */
326 jsr166 1.2 public final ForkJoinTask<V> fork() {
327 jsr166 1.1 ((ForkJoinWorkerThread) Thread.currentThread())
328     .pushTask(this);
329 jsr166 1.2 return this;
330 jsr166 1.1 }
331    
332     /**
333 jsr166 1.10 * Returns the result of the computation when it {@link #isDone is done}.
334 jsr166 1.6 * This method differs from {@link #get()} in that
335     * abnormal completion results in {@code RuntimeException} or
336     * {@code Error}, not {@code ExecutionException}.
337 jsr166 1.1 *
338     * @return the computed result
339     */
340     public final V join() {
341 dl 1.17 quietlyJoin();
342     Throwable ex;
343     if (status < NORMAL && (ex = getException()) != null)
344     UNSAFE.throwException(ex);
345     return getRawResult();
346 jsr166 1.1 }
347    
348     /**
349     * Commences performing this task, awaits its completion if
350 jsr166 1.21 * necessary, and returns its result, or throws an (unchecked)
351 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
352     * computation did so.
353 jsr166 1.1 *
354     * @return the computed result
355     */
356     public final V invoke() {
357 dl 1.17 quietlyInvoke();
358     Throwable ex;
359     if (status < NORMAL && (ex = getException()) != null)
360     UNSAFE.throwException(ex);
361     return getRawResult();
362 jsr166 1.1 }
363    
364     /**
365 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
366     * each task or an (unchecked) exception is encountered, in which
367 dl 1.20 * case the exception is rethrown. If more than one task
368     * encounters an exception, then this method throws any one of
369     * these exceptions. If any task encounters an exception, the
370     * other may be cancelled. However, the execution status of
371     * individual tasks is not guaranteed upon exceptional return. The
372     * status of each task may be obtained using {@link
373     * #getException()} and related methods to check if they have been
374     * cancelled, completed normally or exceptionally, or left
375     * unprocessed.
376 jsr166 1.6 *
377     * <p>This method may be invoked only from within {@code
378     * ForkJoinTask} computations (as may be determined using method
379     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
380     * result in exceptions or errors, possibly including {@code
381     * ClassCastException}.
382     *
383     * @param t1 the first task
384     * @param t2 the second task
385     * @throws NullPointerException if any task is null
386 jsr166 1.1 */
387 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
388 jsr166 1.1 t2.fork();
389     t1.invoke();
390     t2.join();
391     }
392    
393     /**
394 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
395 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
396 dl 1.20 * case the exception is rethrown. If more than one task
397     * encounters an exception, then this method throws any one of
398     * these exceptions. If any task encounters an exception, others
399     * may be cancelled. However, the execution status of individual
400     * tasks is not guaranteed upon exceptional return. The status of
401     * each task may be obtained using {@link #getException()} and
402     * related methods to check if they have been cancelled, completed
403     * normally or exceptionally, or left unprocessed.
404 jsr166 1.6 *
405     * <p>This method may be invoked only from within {@code
406     * ForkJoinTask} computations (as may be determined using method
407     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
408     * result in exceptions or errors, possibly including {@code
409     * ClassCastException}.
410     *
411     * @param tasks the tasks
412 jsr166 1.8 * @throws NullPointerException if any task is null
413 jsr166 1.1 */
414     public static void invokeAll(ForkJoinTask<?>... tasks) {
415     Throwable ex = null;
416     int last = tasks.length - 1;
417     for (int i = last; i >= 0; --i) {
418     ForkJoinTask<?> t = tasks[i];
419     if (t == null) {
420     if (ex == null)
421     ex = new NullPointerException();
422     }
423     else if (i != 0)
424     t.fork();
425 dl 1.17 else {
426     t.quietlyInvoke();
427     if (ex == null && t.status < NORMAL)
428     ex = t.getException();
429     }
430 jsr166 1.1 }
431     for (int i = 1; i <= last; ++i) {
432     ForkJoinTask<?> t = tasks[i];
433     if (t != null) {
434     if (ex != null)
435     t.cancel(false);
436 dl 1.17 else {
437     t.quietlyJoin();
438     if (ex == null && t.status < NORMAL)
439     ex = t.getException();
440     }
441 jsr166 1.1 }
442     }
443     if (ex != null)
444 dl 1.13 UNSAFE.throwException(ex);
445 jsr166 1.1 }
446    
447     /**
448 jsr166 1.7 * Forks all tasks in the specified collection, returning when
449 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
450 dl 1.20 * is encountered, in which case the exception is rethrown. If
451     * more than one task encounters an exception, then this method
452     * throws any one of these exceptions. If any task encounters an
453     * exception, others may be cancelled. However, the execution
454     * status of individual tasks is not guaranteed upon exceptional
455     * return. The status of each task may be obtained using {@link
456     * #getException()} and related methods to check if they have been
457     * cancelled, completed normally or exceptionally, or left
458     * unprocessed.
459 jsr166 1.6 *
460     * <p>This method may be invoked only from within {@code
461     * ForkJoinTask} computations (as may be determined using method
462     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
463     * result in exceptions or errors, possibly including {@code
464     * ClassCastException}.
465 jsr166 1.1 *
466     * @param tasks the collection of tasks
467 jsr166 1.2 * @return the tasks argument, to simplify usage
468 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
469     */
470 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
471 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
472 jsr166 1.1 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
473 jsr166 1.2 return tasks;
474 jsr166 1.1 }
475     @SuppressWarnings("unchecked")
476     List<? extends ForkJoinTask<?>> ts =
477     (List<? extends ForkJoinTask<?>>) tasks;
478     Throwable ex = null;
479     int last = ts.size() - 1;
480     for (int i = last; i >= 0; --i) {
481     ForkJoinTask<?> t = ts.get(i);
482     if (t == null) {
483     if (ex == null)
484     ex = new NullPointerException();
485     }
486     else if (i != 0)
487     t.fork();
488 dl 1.17 else {
489     t.quietlyInvoke();
490     if (ex == null && t.status < NORMAL)
491     ex = t.getException();
492     }
493 jsr166 1.1 }
494     for (int i = 1; i <= last; ++i) {
495     ForkJoinTask<?> t = ts.get(i);
496     if (t != null) {
497     if (ex != null)
498     t.cancel(false);
499 dl 1.17 else {
500     t.quietlyJoin();
501     if (ex == null && t.status < NORMAL)
502     ex = t.getException();
503     }
504 jsr166 1.1 }
505     }
506     if (ex != null)
507 dl 1.13 UNSAFE.throwException(ex);
508 jsr166 1.2 return tasks;
509 jsr166 1.1 }
510    
511     /**
512 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
513 jsr166 1.36 * fail if the task has already completed or could not be
514     * cancelled for some other reason. If successful, and this task
515     * has not started when {@code cancel} is called, execution of
516     * this task is suppressed, {@link #isCancelled} will report true,
517     * and {@link #join} will result in a {@code CancellationException}
518     * being thrown.
519     *
520     * <p>After this method returns, subsequent calls to {@link
521     * #isDone} will always return {@code true}. Subsequent calls to
522     * {@link #isCancelled} will always return {@code true} if this
523     * method returned {@code true}.
524 jsr166 1.1 *
525     * <p>This method may be overridden in subclasses, but if so, must
526     * still ensure that these minimal properties hold. In particular,
527 jsr166 1.6 * the {@code cancel} method itself must not throw exceptions.
528 jsr166 1.1 *
529 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
530 jsr166 1.1 * tasks. To terminate the current task, you can just return or
531     * throw an unchecked exception from its computation method, or
532 jsr166 1.4 * invoke {@link #completeExceptionally}.
533 jsr166 1.1 *
534     * @param mayInterruptIfRunning this value is ignored in the
535 jsr166 1.35 * default implementation because tasks are not cancelled via
536     * interruption
537 jsr166 1.1 *
538 jsr166 1.4 * @return {@code true} if this task is now cancelled
539 jsr166 1.1 */
540     public boolean cancel(boolean mayInterruptIfRunning) {
541     setCompletion(CANCELLED);
542 dl 1.16 return status == CANCELLED;
543 jsr166 1.1 }
544    
545 dl 1.13 /**
546 dl 1.17 * Cancels, ignoring any exceptions thrown by cancel. Used during
547     * worker and pool shutdown. Cancel is spec'ed not to throw any
548     * exceptions, but if it does anyway, we have no recourse during
549     * shutdown, so guard against this case.
550 dl 1.13 */
551     final void cancelIgnoringExceptions() {
552     try {
553     cancel(false);
554     } catch (Throwable ignore) {
555     }
556     }
557    
558     /**
559 jsr166 1.21 * Cancels if current thread is a terminating worker thread,
560     * ignoring any exceptions thrown by cancel.
561 dl 1.13 */
562 dl 1.17 final void cancelIfTerminating() {
563 dl 1.13 Thread t = Thread.currentThread();
564     if ((t instanceof ForkJoinWorkerThread) &&
565 dl 1.14 ((ForkJoinWorkerThread) t).isTerminating()) {
566 dl 1.13 try {
567     cancel(false);
568     } catch (Throwable ignore) {
569     }
570     }
571     }
572    
573 jsr166 1.8 public final boolean isDone() {
574     return status < 0;
575     }
576    
577     public final boolean isCancelled() {
578 dl 1.16 return status == CANCELLED;
579 jsr166 1.8 }
580    
581     /**
582 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
583 jsr166 1.1 *
584 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
585 jsr166 1.1 */
586     public final boolean isCompletedAbnormally() {
587 dl 1.16 return status < NORMAL;
588 jsr166 1.1 }
589    
590     /**
591 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
592     * exception and was not cancelled.
593     *
594     * @return {@code true} if this task completed without throwing an
595     * exception and was not cancelled
596     */
597     public final boolean isCompletedNormally() {
598 dl 1.16 return status == NORMAL;
599 jsr166 1.8 }
600    
601     /**
602 jsr166 1.1 * Returns the exception thrown by the base computation, or a
603 jsr166 1.6 * {@code CancellationException} if cancelled, or {@code null} if
604     * none or if the method has not yet completed.
605 jsr166 1.1 *
606 jsr166 1.4 * @return the exception, or {@code null} if none
607 jsr166 1.1 */
608     public final Throwable getException() {
609 dl 1.16 int s = status;
610 jsr166 1.8 return ((s >= NORMAL) ? null :
611     (s == CANCELLED) ? new CancellationException() :
612     exceptionMap.get(this));
613 jsr166 1.1 }
614    
615     /**
616     * Completes this task abnormally, and if not already aborted or
617     * cancelled, causes it to throw the given exception upon
618     * {@code join} and related operations. This method may be used
619     * to induce exceptions in asynchronous tasks, or to force
620     * completion of tasks that would not otherwise complete. Its use
621 jsr166 1.6 * in other situations is discouraged. This method is
622 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
623     * implementation to maintain guarantees.
624     *
625 jsr166 1.11 * @param ex the exception to throw. If this exception is not a
626     * {@code RuntimeException} or {@code Error}, the actual exception
627     * thrown will be a {@code RuntimeException} with cause {@code ex}.
628 jsr166 1.1 */
629     public void completeExceptionally(Throwable ex) {
630 dl 1.15 setExceptionalCompletion((ex instanceof RuntimeException) ||
631     (ex instanceof Error) ? ex :
632     new RuntimeException(ex));
633 jsr166 1.1 }
634    
635     /**
636     * Completes this task, and if not already aborted or cancelled,
637 dl 1.22 * returning the given value as the result of subsequent
638     * invocations of {@code join} and related operations. This method
639     * may be used to provide results for asynchronous tasks, or to
640     * provide alternative handling for tasks that would not otherwise
641     * complete normally. Its use in other situations is
642     * discouraged. This method is overridable, but overridden
643     * versions must invoke {@code super} implementation to maintain
644     * guarantees.
645 jsr166 1.1 *
646     * @param value the result value for this task
647     */
648     public void complete(V value) {
649     try {
650     setRawResult(value);
651     } catch (Throwable rex) {
652 dl 1.15 setExceptionalCompletion(rex);
653 jsr166 1.1 return;
654     }
655 dl 1.13 setCompletion(NORMAL);
656 jsr166 1.1 }
657    
658 jsr166 1.25 /**
659 dl 1.29 * Waits if necessary for the computation to complete, and then
660     * retrieves its result.
661     *
662     * @return the computed result
663     * @throws CancellationException if the computation was cancelled
664     * @throws ExecutionException if the computation threw an
665     * exception
666     * @throws InterruptedException if the current thread is not a
667     * member of a ForkJoinPool and was interrupted while waiting
668 jsr166 1.25 */
669 jsr166 1.1 public final V get() throws InterruptedException, ExecutionException {
670 dl 1.28 int s;
671     if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
672     quietlyJoin();
673     s = status;
674     }
675     else {
676     while ((s = status) >= 0) {
677     synchronized (this) { // interruptible form of awaitDone
678 jsr166 1.30 if (UNSAFE.compareAndSwapInt(this, statusOffset,
679 dl 1.28 s, SIGNAL)) {
680     while (status >= 0)
681     wait();
682     }
683     }
684     }
685     }
686 dl 1.15 if (s < NORMAL) {
687     Throwable ex;
688     if (s == CANCELLED)
689     throw new CancellationException();
690     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
691     throw new ExecutionException(ex);
692     }
693     return getRawResult();
694 jsr166 1.1 }
695 dl 1.14
696 jsr166 1.25 /**
697 dl 1.29 * Waits if necessary for at most the given time for the computation
698     * to complete, and then retrieves its result, if available.
699     *
700     * @param timeout the maximum time to wait
701     * @param unit the time unit of the timeout argument
702     * @return the computed result
703     * @throws CancellationException if the computation was cancelled
704     * @throws ExecutionException if the computation threw an
705     * exception
706     * @throws InterruptedException if the current thread is not a
707     * member of a ForkJoinPool and was interrupted while waiting
708     * @throws TimeoutException if the wait timed out
709 jsr166 1.25 */
710 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
711     throws InterruptedException, ExecutionException, TimeoutException {
712 dl 1.18 long nanos = unit.toNanos(timeout);
713 dl 1.32 if (status >= 0) {
714     Thread t = Thread.currentThread();
715     if (t instanceof ForkJoinWorkerThread) {
716     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
717     boolean completed = false; // timed variant of quietlyJoin
718     if (w.unpushTask(this)) {
719     try {
720     completed = exec();
721     } catch (Throwable rex) {
722     setExceptionalCompletion(rex);
723     }
724     }
725     if (completed)
726     setCompletion(NORMAL);
727     else if (status >= 0)
728     w.joinTask(this, true, nanos);
729 dl 1.15 }
730 dl 1.32 else if (Thread.interrupted())
731     throw new InterruptedException();
732     else {
733 dl 1.15 long startTime = System.nanoTime();
734 dl 1.32 int s; long nt;
735     while ((s = status) >= 0 &&
736 dl 1.15 (nt = nanos - (System.nanoTime() - startTime)) > 0) {
737 dl 1.32 if (UNSAFE.compareAndSwapInt(this, statusOffset, s,
738     SIGNAL)) {
739 dl 1.15 long ms = nt / 1000000;
740     int ns = (int) (nt % 1000000);
741 dl 1.32 synchronized (this) {
742     if (status >= 0)
743     wait(ms, ns); // exit on IE throw
744 dl 1.15 }
745     }
746     }
747     }
748     }
749 dl 1.16 int es = status;
750 dl 1.15 if (es != NORMAL) {
751     Throwable ex;
752     if (es == CANCELLED)
753     throw new CancellationException();
754     if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
755     throw new ExecutionException(ex);
756     throw new TimeoutException();
757     }
758     return getRawResult();
759 jsr166 1.1 }
760    
761     /**
762 dl 1.17 * Joins this task, without returning its result or throwing its
763 jsr166 1.1 * exception. This method may be useful when processing
764     * collections of tasks when some have been cancelled or otherwise
765     * known to have aborted.
766     */
767     public final void quietlyJoin() {
768 dl 1.17 Thread t;
769     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
770     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
771     if (status >= 0) {
772     if (w.unpushTask(this)) {
773     boolean completed;
774     try {
775     completed = exec();
776     } catch (Throwable rex) {
777     setExceptionalCompletion(rex);
778     return;
779     }
780     if (completed) {
781     setCompletion(NORMAL);
782     return;
783     }
784     }
785 dl 1.32 w.joinTask(this, false, 0L);
786 dl 1.17 }
787     }
788     else
789     externalAwaitDone();
790 jsr166 1.1 }
791    
792     /**
793     * Commences performing this task and awaits its completion if
794 dl 1.17 * necessary, without returning its result or throwing its
795 dl 1.22 * exception.
796 jsr166 1.1 */
797     public final void quietlyInvoke() {
798 dl 1.17 if (status >= 0) {
799     boolean completed;
800     try {
801     completed = exec();
802     } catch (Throwable rex) {
803     setExceptionalCompletion(rex);
804     return;
805     }
806     if (completed)
807     setCompletion(NORMAL);
808     else
809     quietlyJoin();
810     }
811 jsr166 1.1 }
812    
813     /**
814     * Possibly executes tasks until the pool hosting the current task
815 jsr166 1.7 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
816     * be of use in designs in which many tasks are forked, but none
817     * are explicitly joined, instead executing them until all are
818     * processed.
819 jsr166 1.6 *
820     * <p>This method may be invoked only from within {@code
821     * ForkJoinTask} computations (as may be determined using method
822     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
823     * result in exceptions or errors, possibly including {@code
824     * ClassCastException}.
825 jsr166 1.1 */
826     public static void helpQuiesce() {
827     ((ForkJoinWorkerThread) Thread.currentThread())
828     .helpQuiescePool();
829     }
830    
831     /**
832     * Resets the internal bookkeeping state of this task, allowing a
833     * subsequent {@code fork}. This method allows repeated reuse of
834     * this task, but only if reuse occurs when this task has either
835     * never been forked, or has been forked, then completed and all
836     * outstanding joins of this task have also completed. Effects
837 jsr166 1.6 * under any other usage conditions are not guaranteed.
838     * This method may be useful when executing
839 jsr166 1.1 * pre-constructed trees of subtasks in loops.
840 jsr166 1.34 *
841 dl 1.33 * <p>Upon completion of this method, {@code isDone()} reports
842     * {@code false}, and {@code getException()} reports {@code
843     * null}. However, the value returned by {@code getRawResult} is
844     * unaffected. To clear this value, you can invoke {@code
845     * setRawResult(null)}.
846 jsr166 1.1 */
847     public void reinitialize() {
848 dl 1.16 if (status == EXCEPTIONAL)
849 jsr166 1.1 exceptionMap.remove(this);
850     status = 0;
851     }
852    
853     /**
854     * Returns the pool hosting the current task execution, or null
855     * if this task is executing outside of any ForkJoinPool.
856     *
857 jsr166 1.6 * @see #inForkJoinPool
858 jsr166 1.4 * @return the pool, or {@code null} if none
859 jsr166 1.1 */
860     public static ForkJoinPool getPool() {
861     Thread t = Thread.currentThread();
862     return (t instanceof ForkJoinWorkerThread) ?
863     ((ForkJoinWorkerThread) t).pool : null;
864     }
865    
866     /**
867     * Returns {@code true} if the current thread is executing as a
868     * ForkJoinPool computation.
869     *
870     * @return {@code true} if the current thread is executing as a
871     * ForkJoinPool computation, or false otherwise
872     */
873     public static boolean inForkJoinPool() {
874     return Thread.currentThread() instanceof ForkJoinWorkerThread;
875     }
876    
877     /**
878     * Tries to unschedule this task for execution. This method will
879     * typically succeed if this task is the most recently forked task
880     * by the current thread, and has not commenced executing in
881     * another thread. This method may be useful when arranging
882     * alternative local processing of tasks that could have been, but
883 jsr166 1.6 * were not, stolen.
884     *
885     * <p>This method may be invoked only from within {@code
886     * ForkJoinTask} computations (as may be determined using method
887     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
888     * result in exceptions or errors, possibly including {@code
889     * ClassCastException}.
890 jsr166 1.1 *
891 jsr166 1.4 * @return {@code true} if unforked
892 jsr166 1.1 */
893     public boolean tryUnfork() {
894     return ((ForkJoinWorkerThread) Thread.currentThread())
895     .unpushTask(this);
896     }
897    
898     /**
899     * Returns an estimate of the number of tasks that have been
900     * forked by the current worker thread but not yet executed. This
901     * value may be useful for heuristic decisions about whether to
902     * fork other tasks.
903     *
904 jsr166 1.6 * <p>This method may be invoked only from within {@code
905     * ForkJoinTask} computations (as may be determined using method
906     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
907     * result in exceptions or errors, possibly including {@code
908     * ClassCastException}.
909     *
910 jsr166 1.1 * @return the number of tasks
911     */
912     public static int getQueuedTaskCount() {
913     return ((ForkJoinWorkerThread) Thread.currentThread())
914     .getQueueSize();
915     }
916    
917     /**
918     * Returns an estimate of how many more locally queued tasks are
919     * held by the current worker thread than there are other worker
920     * threads that might steal them. This value may be useful for
921     * heuristic decisions about whether to fork other tasks. In many
922     * usages of ForkJoinTasks, at steady state, each worker should
923     * aim to maintain a small constant surplus (for example, 3) of
924     * tasks, and to process computations locally if this threshold is
925     * exceeded.
926     *
927 jsr166 1.6 * <p>This method may be invoked only from within {@code
928     * ForkJoinTask} computations (as may be determined using method
929     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
930     * result in exceptions or errors, possibly including {@code
931     * ClassCastException}.
932     *
933 jsr166 1.1 * @return the surplus number of tasks, which may be negative
934     */
935     public static int getSurplusQueuedTaskCount() {
936     return ((ForkJoinWorkerThread) Thread.currentThread())
937     .getEstimatedSurplusTaskCount();
938     }
939    
940     // Extension methods
941    
942     /**
943 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
944     * if this task completed abnormally, or {@code null} if this task
945     * is not known to have been completed. This method is designed
946     * to aid debugging, as well as to support extensions. Its use in
947     * any other context is discouraged.
948 jsr166 1.1 *
949 jsr166 1.4 * @return the result, or {@code null} if not completed
950 jsr166 1.1 */
951     public abstract V getRawResult();
952    
953     /**
954     * Forces the given value to be returned as a result. This method
955     * is designed to support extensions, and should not in general be
956     * called otherwise.
957     *
958     * @param value the value
959     */
960     protected abstract void setRawResult(V value);
961    
962     /**
963     * Immediately performs the base action of this task. This method
964     * is designed to support extensions, and should not in general be
965     * called otherwise. The return value controls whether this task
966     * is considered to be done normally. It may return false in
967     * asynchronous actions that require explicit invocations of
968 jsr166 1.8 * {@link #complete} to become joinable. It may also throw an
969     * (unchecked) exception to indicate abnormal exit.
970 jsr166 1.1 *
971 jsr166 1.4 * @return {@code true} if completed normally
972 jsr166 1.1 */
973     protected abstract boolean exec();
974    
975     /**
976 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
977     * the current thread but not yet executed, if one is immediately
978 jsr166 1.1 * available. There is no guarantee that this task will actually
979 jsr166 1.5 * be polled or executed next. Conversely, this method may return
980     * null even if a task exists but cannot be accessed without
981     * contention with other threads. This method is designed
982     * primarily to support extensions, and is unlikely to be useful
983 jsr166 1.6 * otherwise.
984     *
985     * <p>This method may be invoked only from within {@code
986     * ForkJoinTask} computations (as may be determined using method
987     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
988     * result in exceptions or errors, possibly including {@code
989     * ClassCastException}.
990 jsr166 1.1 *
991 jsr166 1.4 * @return the next task, or {@code null} if none are available
992 jsr166 1.1 */
993     protected static ForkJoinTask<?> peekNextLocalTask() {
994     return ((ForkJoinWorkerThread) Thread.currentThread())
995     .peekTask();
996     }
997    
998     /**
999     * Unschedules and returns, without executing, the next task
1000     * queued by the current thread but not yet executed. This method
1001     * is designed primarily to support extensions, and is unlikely to
1002 jsr166 1.6 * be useful otherwise.
1003     *
1004     * <p>This method may be invoked only from within {@code
1005     * ForkJoinTask} computations (as may be determined using method
1006     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1007     * result in exceptions or errors, possibly including {@code
1008     * ClassCastException}.
1009 jsr166 1.1 *
1010 jsr166 1.4 * @return the next task, or {@code null} if none are available
1011 jsr166 1.1 */
1012     protected static ForkJoinTask<?> pollNextLocalTask() {
1013     return ((ForkJoinWorkerThread) Thread.currentThread())
1014     .pollLocalTask();
1015     }
1016    
1017     /**
1018     * Unschedules and returns, without executing, the next task
1019     * queued by the current thread but not yet executed, if one is
1020     * available, or if not available, a task that was forked by some
1021     * other thread, if available. Availability may be transient, so a
1022     * {@code null} result does not necessarily imply quiescence
1023     * of the pool this task is operating in. This method is designed
1024     * primarily to support extensions, and is unlikely to be useful
1025 jsr166 1.6 * otherwise.
1026     *
1027     * <p>This method may be invoked only from within {@code
1028     * ForkJoinTask} computations (as may be determined using method
1029     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1030     * result in exceptions or errors, possibly including {@code
1031     * ClassCastException}.
1032 jsr166 1.1 *
1033 jsr166 1.4 * @return a task, or {@code null} if none are available
1034 jsr166 1.1 */
1035     protected static ForkJoinTask<?> pollTask() {
1036     return ((ForkJoinWorkerThread) Thread.currentThread())
1037     .pollTask();
1038     }
1039    
1040 jsr166 1.5 /**
1041     * Adaptor for Runnables. This implements RunnableFuture
1042     * to be compliant with AbstractExecutorService constraints
1043     * when used in ForkJoinPool.
1044     */
1045     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1046     implements RunnableFuture<T> {
1047     final Runnable runnable;
1048     final T resultOnCompletion;
1049     T result;
1050     AdaptedRunnable(Runnable runnable, T result) {
1051     if (runnable == null) throw new NullPointerException();
1052     this.runnable = runnable;
1053     this.resultOnCompletion = result;
1054     }
1055     public T getRawResult() { return result; }
1056     public void setRawResult(T v) { result = v; }
1057     public boolean exec() {
1058     runnable.run();
1059     result = resultOnCompletion;
1060     return true;
1061     }
1062     public void run() { invoke(); }
1063     private static final long serialVersionUID = 5232453952276885070L;
1064     }
1065    
1066     /**
1067     * Adaptor for Callables
1068     */
1069     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1070     implements RunnableFuture<T> {
1071 jsr166 1.6 final Callable<? extends T> callable;
1072 jsr166 1.5 T result;
1073 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1074 jsr166 1.5 if (callable == null) throw new NullPointerException();
1075     this.callable = callable;
1076     }
1077     public T getRawResult() { return result; }
1078     public void setRawResult(T v) { result = v; }
1079     public boolean exec() {
1080     try {
1081     result = callable.call();
1082     return true;
1083     } catch (Error err) {
1084     throw err;
1085     } catch (RuntimeException rex) {
1086     throw rex;
1087     } catch (Exception ex) {
1088     throw new RuntimeException(ex);
1089     }
1090     }
1091     public void run() { invoke(); }
1092     private static final long serialVersionUID = 2838392045355241008L;
1093     }
1094 jsr166 1.2
1095     /**
1096 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1097     * method of the given {@code Runnable} as its action, and returns
1098     * a null result upon {@link #join}.
1099 jsr166 1.2 *
1100     * @param runnable the runnable action
1101     * @return the task
1102     */
1103 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1104 jsr166 1.5 return new AdaptedRunnable<Void>(runnable, null);
1105 jsr166 1.2 }
1106    
1107     /**
1108 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1109     * method of the given {@code Runnable} as its action, and returns
1110     * the given result upon {@link #join}.
1111 jsr166 1.2 *
1112     * @param runnable the runnable action
1113     * @param result the result upon completion
1114     * @return the task
1115     */
1116     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1117 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1118 jsr166 1.2 }
1119    
1120     /**
1121 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1122     * method of the given {@code Callable} as its action, and returns
1123     * its result upon {@link #join}, translating any checked exceptions
1124     * encountered into {@code RuntimeException}.
1125 jsr166 1.2 *
1126     * @param callable the callable action
1127     * @return the task
1128     */
1129 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1130 jsr166 1.5 return new AdaptedCallable<T>(callable);
1131 jsr166 1.2 }
1132    
1133 jsr166 1.1 // Serialization support
1134    
1135     private static final long serialVersionUID = -7721805057305804111L;
1136    
1137     /**
1138 jsr166 1.21 * Saves the state to a stream (that is, serializes it).
1139 jsr166 1.1 *
1140     * @serialData the current run status and the exception thrown
1141 jsr166 1.4 * during execution, or {@code null} if none
1142 jsr166 1.1 * @param s the stream
1143     */
1144     private void writeObject(java.io.ObjectOutputStream s)
1145     throws java.io.IOException {
1146     s.defaultWriteObject();
1147     s.writeObject(getException());
1148     }
1149    
1150     /**
1151 jsr166 1.21 * Reconstitutes the instance from a stream (that is, deserializes it).
1152 jsr166 1.1 *
1153     * @param s the stream
1154     */
1155     private void readObject(java.io.ObjectInputStream s)
1156     throws java.io.IOException, ClassNotFoundException {
1157     s.defaultReadObject();
1158     Object ex = s.readObject();
1159     if (ex != null)
1160 dl 1.15 setExceptionalCompletion((Throwable) ex);
1161 jsr166 1.1 }
1162    
1163 jsr166 1.3 // Unsafe mechanics
1164 jsr166 1.1
1165 jsr166 1.3 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1166     private static final long statusOffset =
1167     objectFieldOffset("status", ForkJoinTask.class);
1168    
1169     private static long objectFieldOffset(String field, Class<?> klazz) {
1170 jsr166 1.1 try {
1171 jsr166 1.3 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1172 jsr166 1.1 } catch (NoSuchFieldException e) {
1173 jsr166 1.3 // Convert Exception to corresponding Error
1174     NoSuchFieldError error = new NoSuchFieldError(field);
1175 jsr166 1.1 error.initCause(e);
1176     throw error;
1177     }
1178     }
1179     }