ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.21
Committed: Sat Sep 4 00:21:31 2010 UTC (13 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +7 -5 lines
Log Message:
coding style

File Contents

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