ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.39
Committed: Wed Aug 5 00:57:41 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.38: +4 -3 lines
Log Message:
Align spec of binary invokeAll with array invokeAll

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