ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.12
Committed: Tue Oct 27 23:21:32 2009 UTC (14 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +2 -2 lines
Log Message:
sync with jsr166y package

File Contents

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