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