ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.17
Committed: Wed Aug 11 18:45:45 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.16: +113 -126 lines
Log Message:
Sync with jsr166y

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