ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.139
Committed: Fri Jul 24 20:54:37 2020 UTC (3 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.138: +5 -0 lines
Log Message:
8250240: Address use of default constructors in the java.util.concurrent

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/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.io.Serializable;
10 import java.lang.invoke.MethodHandles;
11 import java.lang.invoke.VarHandle;
12 import java.lang.ref.ReferenceQueue;
13 import java.lang.ref.WeakReference;
14 import java.lang.reflect.Constructor;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.RandomAccess;
18 import java.util.concurrent.locks.LockSupport;
19
20 /**
21 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
22 * A {@code ForkJoinTask} is a thread-like entity that is much
23 * lighter weight than a normal thread. Huge numbers of tasks and
24 * subtasks may be hosted by a small number of actual threads in a
25 * ForkJoinPool, at the price of some usage limitations.
26 *
27 * <p>A "main" {@code ForkJoinTask} begins execution when it is
28 * explicitly submitted to a {@link ForkJoinPool}, or, if not already
29 * engaged in a ForkJoin computation, commenced in the {@link
30 * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or
31 * related methods. Once started, it will usually in turn start other
32 * subtasks. As indicated by the name of this class, many programs
33 * using {@code ForkJoinTask} employ only methods {@link #fork} and
34 * {@link #join}, or derivatives such as {@link
35 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
36 * provides a number of other methods that can come into play in
37 * advanced usages, as well as extension mechanics that allow support
38 * of new forms of fork/join processing.
39 *
40 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
41 * The efficiency of {@code ForkJoinTask}s stems from a set of
42 * restrictions (that are only partially statically enforceable)
43 * reflecting their main use as computational tasks calculating pure
44 * functions or operating on purely isolated objects. The primary
45 * coordination mechanisms are {@link #fork}, that arranges
46 * asynchronous execution, and {@link #join}, that doesn't proceed
47 * until the task's result has been computed. Computations should
48 * ideally avoid {@code synchronized} methods or blocks, and should
49 * minimize other blocking synchronization apart from joining other
50 * tasks or using synchronizers such as Phasers that are advertised to
51 * cooperate with fork/join scheduling. Subdividable tasks should also
52 * not perform blocking I/O, and should ideally access variables that
53 * are completely independent of those accessed by other running
54 * tasks. These guidelines are loosely enforced by not permitting
55 * checked exceptions such as {@code IOExceptions} to be
56 * thrown. However, computations may still encounter unchecked
57 * exceptions, that are rethrown to callers attempting to join
58 * them. These exceptions may additionally include {@link
59 * RejectedExecutionException} stemming from internal resource
60 * exhaustion, such as failure to allocate internal task
61 * queues. Rethrown exceptions behave in the same way as regular
62 * exceptions, but, when possible, contain stack traces (as displayed
63 * for example using {@code ex.printStackTrace()}) of both the thread
64 * that initiated the computation as well as the thread actually
65 * encountering the exception; minimally only the latter.
66 *
67 * <p>It is possible to define and use ForkJoinTasks that may block,
68 * but doing so requires three further considerations: (1) Completion
69 * of few if any <em>other</em> tasks should be dependent on a task
70 * that blocks on external synchronization or I/O. Event-style async
71 * tasks that are never joined (for example, those subclassing {@link
72 * CountedCompleter}) often fall into this category. (2) To minimize
73 * resource impact, tasks should be small; ideally performing only the
74 * (possibly) blocking action. (3) Unless the {@link
75 * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
76 * blocked tasks is known to be less than the pool's {@link
77 * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
78 * enough threads will be available to ensure progress or good
79 * performance.
80 *
81 * <p>The primary method for awaiting completion and extracting
82 * results of a task is {@link #join}, but there are several variants:
83 * The {@link Future#get} methods support interruptible and/or timed
84 * waits for completion and report results using {@code Future}
85 * conventions. Method {@link #invoke} is semantically
86 * equivalent to {@code fork(); join()} but always attempts to begin
87 * execution in the current thread. The "<em>quiet</em>" forms of
88 * these methods do not extract results or report exceptions. These
89 * may be useful when a set of tasks are being executed, and you need
90 * to delay processing of results or exceptions until all complete.
91 * Method {@code invokeAll} (available in multiple versions)
92 * performs the most common form of parallel invocation: forking a set
93 * of tasks and joining them all.
94 *
95 * <p>In the most typical usages, a fork-join pair act like a call
96 * (fork) and return (join) from a parallel recursive function. As is
97 * the case with other forms of recursive calls, returns (joins)
98 * should be performed innermost-first. For example, {@code a.fork();
99 * b.fork(); b.join(); a.join();} is likely to be substantially more
100 * efficient than joining {@code a} before {@code b}.
101 *
102 * <p>The execution status of tasks may be queried at several levels
103 * of detail: {@link #isDone} is true if a task completed in any way
104 * (including the case where a task was cancelled without executing);
105 * {@link #isCompletedNormally} is true if a task completed without
106 * cancellation or encountering an exception; {@link #isCancelled} is
107 * true if the task was cancelled (in which case {@link #getException}
108 * returns a {@link CancellationException}); and
109 * {@link #isCompletedAbnormally} is true if a task was either
110 * cancelled or encountered an exception, in which case {@link
111 * #getException} will return either the encountered exception or
112 * {@link CancellationException}.
113 *
114 * <p>By default, method {@link #cancel} ignores its {@code
115 * mayInterruptIfRunning} argument, separating task cancellation from
116 * the interruption status of threads running tasks. However, the
117 * method is overridable to accommodate cases in which running tasks
118 * must be cancelled using interrupts. This may arise when adapting
119 * Callables that cannot check {@code isCancelled()} task status.
120 * Tasks constructed with the {@link #adaptInterruptible} adaptor
121 * track and interrupt the running thread upon {@code
122 * cancel(true)}. Reliable usage requires awareness of potential
123 * consequences: Method bodies should ignore stray interrupts to cope
124 * with the inherent possibility that a late interrupt issued by
125 * another thread after a given task has completed may (inadvertently)
126 * interrupt some future task. Further, interruptible tasks should not
127 * in general create subtasks, because an interrupt intended for a
128 * given task may be consumed by one of its subtasks, or vice versa.
129 *
130 * <p>The ForkJoinTask class is not usually directly subclassed.
131 * Instead, you subclass one of the abstract classes that support a
132 * particular style of fork/join processing, typically {@link
133 * RecursiveAction} for most computations that do not return results,
134 * {@link RecursiveTask} for those that do, and {@link
135 * CountedCompleter} for those in which completed actions trigger
136 * other actions. Normally, a concrete ForkJoinTask subclass declares
137 * fields comprising its parameters, established in a constructor, and
138 * then defines a {@code compute} method that somehow uses the control
139 * methods supplied by this base class.
140 *
141 * <p>Method {@link #join} and its variants are appropriate for use
142 * only when completion dependencies are acyclic; that is, the
143 * parallel computation can be described as a directed acyclic graph
144 * (DAG). Otherwise, executions may encounter a form of deadlock as
145 * tasks cyclically wait for each other. However, this framework
146 * supports other methods and techniques (for example the use of
147 * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
148 * may be of use in constructing custom subclasses for problems that
149 * are not statically structured as DAGs. To support such usages, a
150 * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
151 * value using {@link #setForkJoinTaskTag} or {@link
152 * #compareAndSetForkJoinTaskTag} and checked using {@link
153 * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use
154 * these {@code protected} methods or tags for any purpose, but they
155 * may be of use in the construction of specialized subclasses. For
156 * example, parallel graph traversals can use the supplied methods to
157 * avoid revisiting nodes/tasks that have already been processed.
158 * (Method names for tagging are bulky in part to encourage definition
159 * of methods that reflect their usage patterns.)
160 *
161 * <p>Most base support methods are {@code final}, to prevent
162 * overriding of implementations that are intrinsically tied to the
163 * underlying lightweight task scheduling framework. Developers
164 * creating new basic styles of fork/join processing should minimally
165 * implement {@code protected} methods {@link #exec}, {@link
166 * #setRawResult}, and {@link #getRawResult}, while also introducing
167 * an abstract computational method that can be implemented in its
168 * subclasses, possibly relying on other {@code protected} methods
169 * provided by this class.
170 *
171 * <p>ForkJoinTasks should perform relatively small amounts of
172 * computation. Large tasks should be split into smaller subtasks,
173 * usually via recursive decomposition. As a very rough rule of thumb,
174 * a task should perform more than 100 and less than 10000 basic
175 * computational steps, and should avoid indefinite looping. If tasks
176 * are too big, then parallelism cannot improve throughput. If too
177 * small, then memory and internal task maintenance overhead may
178 * overwhelm processing.
179 *
180 * <p>This class provides {@code adapt} methods for {@link Runnable}
181 * and {@link Callable}, that may be of use when mixing execution of
182 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
183 * of this form, consider using a pool constructed in <em>asyncMode</em>.
184 *
185 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
186 * used in extensions such as remote execution frameworks. It is
187 * sensible to serialize tasks only before or after, but not during,
188 * execution. Serialization is not relied on during execution itself.
189 *
190 * @since 1.7
191 * @author Doug Lea
192 */
193 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
194
195 /*
196 * See the internal documentation of class ForkJoinPool for a
197 * general implementation overview. ForkJoinTasks are mainly
198 * responsible for maintaining their "status" field amidst relays
199 * to methods in ForkJoinWorkerThread and ForkJoinPool.
200 *
201 * The methods of this class are more-or-less layered into
202 * (1) basic status maintenance
203 * (2) execution and awaiting completion
204 * (3) user-level methods that additionally report results.
205 * This is sometimes hard to see because this file orders exported
206 * methods in a way that flows well in javadocs.
207 *
208 * Revision notes: The use of "Aux" field replaces previous
209 * reliance on a table to hold exceptions and synchronized blocks
210 * and monitors to wait for completion.
211 */
212
213 /**
214 * Nodes for threads waiting for completion, or holding a thrown
215 * exception (never both). Waiting threads prepend nodes
216 * Treiber-stack-style. Signallers detach and unpark
217 * waiters. Cancelled waiters try to unsplice.
218 */
219 static final class Aux {
220 final Thread thread;
221 final Throwable ex; // null if a waiter
222 Aux next; // accessed only via memory-acquire chains
223 Aux(Thread thread, Throwable ex) {
224 this.thread = thread;
225 this.ex = ex;
226 }
227 final boolean casNext(Aux c, Aux v) { // used only in cancellation
228 return NEXT.compareAndSet(this, c, v);
229 }
230 private static final VarHandle NEXT;
231 static {
232 try {
233 NEXT = MethodHandles.lookup()
234 .findVarHandle(Aux.class, "next", Aux.class);
235 } catch (ReflectiveOperationException e) {
236 throw new ExceptionInInitializerError(e);
237 }
238 }
239 }
240
241 /*
242 * The status field holds bits packed into a single int to ensure
243 * atomicity. Status is initially zero, and takes on nonnegative
244 * values until completed, upon which it holds (sign bit) DONE,
245 * possibly with ABNORMAL (cancelled or exceptional) and THROWN
246 * (in which case an exception has been stored). A value of
247 * ABNORMAL without DONE signifies an interrupted wait. These
248 * control bits occupy only (some of) the upper half (16 bits) of
249 * status field. The lower bits are used for user-defined tags.
250 */
251 private static final int DONE = 1 << 31; // must be negative
252 private static final int ABNORMAL = 1 << 16;
253 private static final int THROWN = 1 << 17;
254 private static final int SMASK = 0xffff; // short bits for tags
255 private static final int UNCOMPENSATE = 1 << 16; // helpJoin return sentinel
256
257 // Fields
258 volatile int status; // accessed directly by pool and workers
259 private transient volatile Aux aux; // either waiters or thrown Exception
260
261 // Support for atomic operations
262 private static final VarHandle STATUS;
263 private static final VarHandle AUX;
264 private int getAndBitwiseOrStatus(int v) {
265 return (int)STATUS.getAndBitwiseOr(this, v);
266 }
267 private boolean casStatus(int c, int v) {
268 return STATUS.weakCompareAndSet(this, c, v);
269 }
270 private boolean casAux(Aux c, Aux v) {
271 return AUX.compareAndSet(this, c, v);
272 }
273
274 /** Removes and unparks waiters */
275 private void signalWaiters() {
276 for (Aux a; (a = aux) != null && a.ex == null; ) {
277 if (casAux(a, null)) { // detach entire list
278 for (Thread t; a != null; a = a.next) {
279 if ((t = a.thread) != Thread.currentThread() && t != null)
280 LockSupport.unpark(t); // don't self-signal
281 }
282 break;
283 }
284 }
285 }
286
287 /**
288 * Possibly blocks until task is done or interrupted or timed out.
289 *
290 * @param interruptible true if wait can be cancelled by interrupt
291 * @param deadline if non-zero use timed waits and possibly timeout
292 * @param pool if nonnull pool to uncompensate after unblocking
293 * @return status on exit, or ABNORMAL if interrupted while waiting
294 */
295 private int awaitDone(boolean interruptible, long deadline,
296 ForkJoinPool pool) {
297 int s;
298 boolean interrupted = false, queued = false, parked = false;
299 Aux node = null;
300 while ((s = status) >= 0) {
301 Aux a; long ns;
302 if (parked && Thread.interrupted()) {
303 if (interruptible) {
304 s = ABNORMAL;
305 break;
306 }
307 interrupted = true;
308 }
309 else if (queued) {
310 if (deadline != 0L) {
311 if ((ns = deadline - System.nanoTime()) <= 0L)
312 break;
313 LockSupport.parkNanos(ns);
314 }
315 else
316 LockSupport.park();
317 parked = true;
318 }
319 else if (node != null) {
320 if ((a = aux) != null && a.ex != null)
321 Thread.onSpinWait(); // exception in progress
322 else if (queued = casAux(node.next = a, node))
323 LockSupport.setCurrentBlocker(this);
324 }
325 else {
326 try {
327 node = new Aux(Thread.currentThread(), null);
328 } catch (Throwable ex) { // try to cancel if cannot create
329 casStatus(s, s | (DONE | ABNORMAL));
330 }
331 }
332 }
333 if (pool != null)
334 pool.uncompensate();
335
336 if (queued) {
337 LockSupport.setCurrentBlocker(null);
338 if (s >= 0) { // cancellation similar to AbstractQueuedSynchronizer
339 outer: for (Aux a; (a = aux) != null && a.ex == null; ) {
340 for (Aux trail = null;;) {
341 Aux next = a.next;
342 if (a == node) {
343 if (trail != null)
344 trail.casNext(trail, next);
345 else if (casAux(a, next))
346 break outer; // cannot be re-encountered
347 break; // restart
348 } else {
349 trail = a;
350 if ((a = next) == null)
351 break outer;
352 }
353 }
354 }
355 }
356 else {
357 signalWaiters(); // help clean or signal
358 if (interrupted)
359 Thread.currentThread().interrupt();
360 }
361 }
362 return s;
363 }
364
365 /**
366 * Sets DONE status and wakes up threads waiting to join this task.
367 * @return status on exit
368 */
369 private int setDone() {
370 int s = getAndBitwiseOrStatus(DONE) | DONE;
371 signalWaiters();
372 return s;
373 }
374
375 /**
376 * Sets ABNORMAL DONE status unless already done, and wakes up threads
377 * waiting to join this task.
378 * @return status on exit
379 */
380 private int trySetCancelled() {
381 int s;
382 do {} while ((s = status) >= 0 && !casStatus(s, s |= (DONE | ABNORMAL)));
383 signalWaiters();
384 return s;
385 }
386
387 /**
388 * Records exception and sets ABNORMAL THROWN DONE status unless
389 * already done, and wakes up threads waiting to join this task.
390 * If losing a race with setDone or trySetCancelled, the exception
391 * may be recorded but not reported.
392 *
393 * @return status on exit
394 */
395 final int trySetThrown(Throwable ex) {
396 Aux h = new Aux(Thread.currentThread(), ex), p = null;
397 boolean installed = false;
398 int s;
399 while ((s = status) >= 0) {
400 Aux a;
401 if (!installed && ((a = aux) == null || a.ex == null) &&
402 (installed = casAux(a, h)))
403 p = a; // list of waiters replaced by h
404 if (installed && casStatus(s, s |= (DONE | ABNORMAL | THROWN)))
405 break;
406 }
407 for (; p != null; p = p.next)
408 LockSupport.unpark(p.thread);
409 return s;
410 }
411
412 /**
413 * Records exception unless already done. Overridable in subclasses.
414 *
415 * @return status on exit
416 */
417 int trySetException(Throwable ex) {
418 return trySetThrown(ex);
419 }
420
421 /**
422 * Constructor for subclasses to call.
423 */
424 public ForkJoinTask() {}
425
426 static boolean isExceptionalStatus(int s) { // needed by subclasses
427 return (s & THROWN) != 0;
428 }
429
430 /**
431 * Unless done, calls exec and records status if completed, but
432 * doesn't wait for completion otherwise.
433 *
434 * @return status on exit from this method
435 */
436 final int doExec() {
437 int s; boolean completed;
438 if ((s = status) >= 0) {
439 try {
440 completed = exec();
441 } catch (Throwable rex) {
442 s = trySetException(rex);
443 completed = false;
444 }
445 if (completed)
446 s = setDone();
447 }
448 return s;
449 }
450
451 /**
452 * Helps and/or waits for completion from join, get, or invoke;
453 * called from either internal or external threads.
454 *
455 * @param ran true if task known to have been exec'd
456 * @param interruptible true if park interruptibly when external
457 * @param timed true if use timed wait
458 * @param nanos if timed, timeout value
459 * @return ABNORMAL if interrupted, else status on exit
460 */
461 private int awaitJoin(boolean ran, boolean interruptible, boolean timed,
462 long nanos) {
463 boolean internal; ForkJoinPool p; ForkJoinPool.WorkQueue q; int s;
464 Thread t; ForkJoinWorkerThread wt;
465 if (internal = ((t = Thread.currentThread())
466 instanceof ForkJoinWorkerThread)) {
467 p = (wt = (ForkJoinWorkerThread)t).pool;
468 q = wt.workQueue;
469 }
470 else {
471 p = ForkJoinPool.common;
472 q = ForkJoinPool.commonQueue();
473 if (interruptible && Thread.interrupted())
474 return ABNORMAL;
475 }
476 if ((s = status) < 0)
477 return s;
478 long deadline = 0L;
479 if (timed) {
480 if (nanos <= 0L)
481 return 0;
482 else if ((deadline = nanos + System.nanoTime()) == 0L)
483 deadline = 1L;
484 }
485 ForkJoinPool uncompensate = null;
486 if (q != null && p != null) { // try helping
487 if ((!timed || p.isSaturated()) &&
488 ((this instanceof CountedCompleter) ?
489 (s = p.helpComplete(this, q, internal)) < 0 :
490 (q.tryRemove(this, internal) && (s = doExec()) < 0)))
491 return s;
492 if (internal) {
493 if ((s = p.helpJoin(this, q)) < 0)
494 return s;
495 if (s == UNCOMPENSATE)
496 uncompensate = p;
497 interruptible = false;
498 }
499 }
500 return awaitDone(interruptible, deadline, uncompensate);
501 }
502
503 /**
504 * Cancels, ignoring any exceptions thrown by cancel. Cancel is
505 * spec'ed not to throw any exceptions, but if it does anyway, we
506 * have no recourse, so guard against this case.
507 */
508 static final void cancelIgnoringExceptions(Future<?> t) {
509 if (t != null) {
510 try {
511 t.cancel(true);
512 } catch (Throwable ignore) {
513 }
514 }
515 }
516
517 /**
518 * Returns a rethrowable exception for this task, if available.
519 * To provide accurate stack traces, if the exception was not
520 * thrown by the current thread, we try to create a new exception
521 * of the same type as the one thrown, but with the recorded
522 * exception as its cause. If there is no such constructor, we
523 * instead try to use a no-arg constructor, followed by initCause,
524 * to the same effect. If none of these apply, or any fail due to
525 * other exceptions, we return the recorded exception, which is
526 * still correct, although it may contain a misleading stack
527 * trace.
528 *
529 * @return the exception, or null if none
530 */
531 private Throwable getThrowableException() {
532 Throwable ex; Aux a;
533 if ((a = aux) == null)
534 ex = null;
535 else if ((ex = a.ex) != null && a.thread != Thread.currentThread()) {
536 try {
537 Constructor<?> noArgCtor = null, oneArgCtor = null;
538 for (Constructor<?> c : ex.getClass().getConstructors()) {
539 Class<?>[] ps = c.getParameterTypes();
540 if (ps.length == 0)
541 noArgCtor = c;
542 else if (ps.length == 1 && ps[0] == Throwable.class) {
543 oneArgCtor = c;
544 break;
545 }
546 }
547 if (oneArgCtor != null)
548 ex = (Throwable)oneArgCtor.newInstance(ex);
549 else if (noArgCtor != null) {
550 Throwable rx = (Throwable)noArgCtor.newInstance();
551 rx.initCause(ex);
552 ex = rx;
553 }
554 } catch (Exception ignore) {
555 }
556 }
557 return ex;
558 }
559
560 /**
561 * Returns exception associated with the given status, or null if none.
562 */
563 private Throwable getException(int s) {
564 Throwable ex = null;
565 if ((s & ABNORMAL) != 0 &&
566 ((s & THROWN) == 0 || (ex = getThrowableException()) == null))
567 ex = new CancellationException();
568 return ex;
569 }
570
571 /**
572 * Throws exception associated with the given status, or
573 * CancellationException if none recorded.
574 */
575 private void reportException(int s) {
576 ForkJoinTask.<RuntimeException>uncheckedThrow(
577 (s & THROWN) != 0 ? getThrowableException() : null);
578 }
579
580 /**
581 * Throws exception for (timed or untimed) get, wrapping if
582 * necessary in an ExecutionException.
583 */
584 private void reportExecutionException(int s) {
585 Throwable ex = null;
586 if (s == ABNORMAL)
587 ex = new InterruptedException();
588 else if (s >= 0)
589 ex = new TimeoutException();
590 else if ((s & THROWN) != 0 && (ex = getThrowableException()) != null)
591 ex = new ExecutionException(ex);
592 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
593 }
594
595 /**
596 * A version of "sneaky throw" to relay exceptions in other
597 * contexts.
598 */
599 static void rethrow(Throwable ex) {
600 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
601 }
602
603 /**
604 * The sneaky part of sneaky throw, relying on generics
605 * limitations to evade compiler complaints about rethrowing
606 * unchecked exceptions. If argument null, throws
607 * CancellationException.
608 */
609 @SuppressWarnings("unchecked") static <T extends Throwable>
610 void uncheckedThrow(Throwable t) throws T {
611 if (t == null)
612 t = new CancellationException();
613 throw (T)t; // rely on vacuous cast
614 }
615
616 // public methods
617
618 /**
619 * Arranges to asynchronously execute this task in the pool the
620 * current task is running in, if applicable, or using the {@link
621 * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While
622 * it is not necessarily enforced, it is a usage error to fork a
623 * task more than once unless it has completed and been
624 * reinitialized. Subsequent modifications to the state of this
625 * task or any data it operates on are not necessarily
626 * consistently observable by any thread other than the one
627 * executing it unless preceded by a call to {@link #join} or
628 * related methods, or a call to {@link #isDone} returning {@code
629 * true}.
630 *
631 * @return {@code this}, to simplify usage
632 */
633 public final ForkJoinTask<V> fork() {
634 Thread t; ForkJoinWorkerThread w;
635 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
636 (w = (ForkJoinWorkerThread)t).workQueue.push(this, w.pool);
637 else
638 ForkJoinPool.common.externalPush(this);
639 return this;
640 }
641
642 /**
643 * Returns the result of the computation when it
644 * {@linkplain #isDone is done}.
645 * This method differs from {@link #get()} in that abnormal
646 * completion results in {@code RuntimeException} or {@code Error},
647 * not {@code ExecutionException}, and that interrupts of the
648 * calling thread do <em>not</em> cause the method to abruptly
649 * return by throwing {@code InterruptedException}.
650 *
651 * @return the computed result
652 */
653 public final V join() {
654 int s;
655 if ((s = status) >= 0)
656 s = awaitJoin(false, false, false, 0L);
657 if ((s & ABNORMAL) != 0)
658 reportException(s);
659 return getRawResult();
660 }
661
662 /**
663 * Commences performing this task, awaits its completion if
664 * necessary, and returns its result, or throws an (unchecked)
665 * {@code RuntimeException} or {@code Error} if the underlying
666 * computation did so.
667 *
668 * @return the computed result
669 */
670 public final V invoke() {
671 int s;
672 if ((s = doExec()) >= 0)
673 s = awaitJoin(true, false, false, 0L);
674 if ((s & ABNORMAL) != 0)
675 reportException(s);
676 return getRawResult();
677 }
678
679 /**
680 * Forks the given tasks, returning when {@code isDone} holds for
681 * each task or an (unchecked) exception is encountered, in which
682 * case the exception is rethrown. If more than one task
683 * encounters an exception, then this method throws any one of
684 * these exceptions. If any task encounters an exception, the
685 * other may be cancelled. However, the execution status of
686 * individual tasks is not guaranteed upon exceptional return. The
687 * status of each task may be obtained using {@link
688 * #getException()} and related methods to check if they have been
689 * cancelled, completed normally or exceptionally, or left
690 * unprocessed.
691 *
692 * @param t1 the first task
693 * @param t2 the second task
694 * @throws NullPointerException if any task is null
695 */
696 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
697 int s1, s2;
698 if (t1 == null || t2 == null)
699 throw new NullPointerException();
700 t2.fork();
701 if ((s1 = t1.doExec()) >= 0)
702 s1 = t1.awaitJoin(true, false, false, 0L);
703 if ((s1 & ABNORMAL) != 0) {
704 cancelIgnoringExceptions(t2);
705 t1.reportException(s1);
706 }
707 else if (((s2 = t2.awaitJoin(false, false, false, 0L)) & ABNORMAL) != 0)
708 t2.reportException(s2);
709 }
710
711 /**
712 * Forks the given tasks, returning when {@code isDone} holds for
713 * each task or an (unchecked) exception is encountered, in which
714 * case the exception is rethrown. If more than one task
715 * encounters an exception, then this method throws any one of
716 * these exceptions. If any task encounters an exception, others
717 * may be cancelled. However, the execution status of individual
718 * tasks is not guaranteed upon exceptional return. The status of
719 * each task may be obtained using {@link #getException()} and
720 * related methods to check if they have been cancelled, completed
721 * normally or exceptionally, or left unprocessed.
722 *
723 * @param tasks the tasks
724 * @throws NullPointerException if any task is null
725 */
726 public static void invokeAll(ForkJoinTask<?>... tasks) {
727 Throwable ex = null;
728 int last = tasks.length - 1;
729 for (int i = last, s; i >= 0; --i) {
730 ForkJoinTask<?> t;
731 if ((t = tasks[i]) == null) {
732 ex = new NullPointerException();
733 break;
734 }
735 if (i == 0) {
736 if ((s = t.doExec()) >= 0)
737 s = t.awaitJoin(true, false, false, 0L);
738 if ((s & ABNORMAL) != 0)
739 ex = t.getException(s);
740 break;
741 }
742 t.fork();
743 }
744 if (ex == null) {
745 for (int i = 1, s; i <= last; ++i) {
746 ForkJoinTask<?> t;
747 if ((t = tasks[i]) != null) {
748 if ((s = t.status) >= 0)
749 s = t.awaitJoin(false, false, false, 0L);
750 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
751 break;
752 }
753 }
754 }
755 if (ex != null) {
756 for (int i = 1, s; i <= last; ++i)
757 cancelIgnoringExceptions(tasks[i]);
758 rethrow(ex);
759 }
760 }
761
762 /**
763 * Forks all tasks in the specified collection, returning when
764 * {@code isDone} holds for each task or an (unchecked) exception
765 * is encountered, in which case the exception is rethrown. If
766 * more than one task encounters an exception, then this method
767 * throws any one of these exceptions. If any task encounters an
768 * exception, others may be cancelled. However, the execution
769 * status of individual tasks is not guaranteed upon exceptional
770 * return. The status of each task may be obtained using {@link
771 * #getException()} and related methods to check if they have been
772 * cancelled, completed normally or exceptionally, or left
773 * unprocessed.
774 *
775 * @param tasks the collection of tasks
776 * @param <T> the type of the values returned from the tasks
777 * @return the tasks argument, to simplify usage
778 * @throws NullPointerException if tasks or any element are null
779 */
780 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
781 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
782 invokeAll(tasks.toArray(new ForkJoinTask<?>[0]));
783 return tasks;
784 }
785 @SuppressWarnings("unchecked")
786 List<? extends ForkJoinTask<?>> ts =
787 (List<? extends ForkJoinTask<?>>) tasks;
788 Throwable ex = null;
789 int last = ts.size() - 1; // nearly same as array version
790 for (int i = last, s; i >= 0; --i) {
791 ForkJoinTask<?> t;
792 if ((t = ts.get(i)) == null) {
793 ex = new NullPointerException();
794 break;
795 }
796 if (i == 0) {
797 if ((s = t.doExec()) >= 0)
798 s = t.awaitJoin(true, false, false, 0L);
799 if ((s & ABNORMAL) != 0)
800 ex = t.getException(s);
801 break;
802 }
803 t.fork();
804 }
805 if (ex == null) {
806 for (int i = 1, s; i <= last; ++i) {
807 ForkJoinTask<?> t;
808 if ((t = ts.get(i)) != null) {
809 if ((s = t.status) >= 0)
810 s = t.awaitJoin(false, false, false, 0L);
811 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
812 break;
813 }
814 }
815 }
816 if (ex != null) {
817 for (int i = 1, s; i <= last; ++i)
818 cancelIgnoringExceptions(ts.get(i));
819 rethrow(ex);
820 }
821 return tasks;
822 }
823
824 /**
825 * Attempts to cancel execution of this task. This attempt will
826 * fail if the task has already completed or could not be
827 * cancelled for some other reason. If successful, and this task
828 * has not started when {@code cancel} is called, execution of
829 * this task is suppressed. After this method returns
830 * successfully, unless there is an intervening call to {@link
831 * #reinitialize}, subsequent calls to {@link #isCancelled},
832 * {@link #isDone}, and {@code cancel} will return {@code true}
833 * and calls to {@link #join} and related methods will result in
834 * {@code CancellationException}.
835 *
836 * <p>This method may be overridden in subclasses, but if so, must
837 * still ensure that these properties hold. In particular, the
838 * {@code cancel} method itself must not throw exceptions.
839 *
840 * <p>This method is designed to be invoked by <em>other</em>
841 * tasks. To terminate the current task, you can just return or
842 * throw an unchecked exception from its computation method, or
843 * invoke {@link #completeExceptionally(Throwable)}.
844 *
845 * @param mayInterruptIfRunning this value has no effect in the
846 * default implementation because interrupts are not used to
847 * control cancellation.
848 *
849 * @return {@code true} if this task is now cancelled
850 */
851 public boolean cancel(boolean mayInterruptIfRunning) {
852 return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL;
853 }
854
855 public final boolean isDone() {
856 return status < 0;
857 }
858
859 public final boolean isCancelled() {
860 return (status & (ABNORMAL | THROWN)) == ABNORMAL;
861 }
862
863 /**
864 * Returns {@code true} if this task threw an exception or was cancelled.
865 *
866 * @return {@code true} if this task threw an exception or was cancelled
867 */
868 public final boolean isCompletedAbnormally() {
869 return (status & ABNORMAL) != 0;
870 }
871
872 /**
873 * Returns {@code true} if this task completed without throwing an
874 * exception and was not cancelled.
875 *
876 * @return {@code true} if this task completed without throwing an
877 * exception and was not cancelled
878 */
879 public final boolean isCompletedNormally() {
880 return (status & (DONE | ABNORMAL)) == DONE;
881 }
882
883 /**
884 * Returns the exception thrown by the base computation, or a
885 * {@code CancellationException} if cancelled, or {@code null} if
886 * none or if the method has not yet completed.
887 *
888 * @return the exception, or {@code null} if none
889 */
890 public final Throwable getException() {
891 return getException(status);
892 }
893
894 /**
895 * Completes this task abnormally, and if not already aborted or
896 * cancelled, causes it to throw the given exception upon
897 * {@code join} and related operations. This method may be used
898 * to induce exceptions in asynchronous tasks, or to force
899 * completion of tasks that would not otherwise complete. Its use
900 * in other situations is discouraged. This method is
901 * overridable, but overridden versions must invoke {@code super}
902 * implementation to maintain guarantees.
903 *
904 * @param ex the exception to throw. If this exception is not a
905 * {@code RuntimeException} or {@code Error}, the actual exception
906 * thrown will be a {@code RuntimeException} with cause {@code ex}.
907 */
908 public void completeExceptionally(Throwable ex) {
909 trySetException((ex instanceof RuntimeException) ||
910 (ex instanceof Error) ? ex :
911 new RuntimeException(ex));
912 }
913
914 /**
915 * Completes this task, and if not already aborted or cancelled,
916 * returning the given value as the result of subsequent
917 * invocations of {@code join} and related operations. This method
918 * may be used to provide results for asynchronous tasks, or to
919 * provide alternative handling for tasks that would not otherwise
920 * complete normally. Its use in other situations is
921 * discouraged. This method is overridable, but overridden
922 * versions must invoke {@code super} implementation to maintain
923 * guarantees.
924 *
925 * @param value the result value for this task
926 */
927 public void complete(V value) {
928 try {
929 setRawResult(value);
930 } catch (Throwable rex) {
931 trySetException(rex);
932 return;
933 }
934 setDone();
935 }
936
937 /**
938 * Completes this task normally without setting a value. The most
939 * recent value established by {@link #setRawResult} (or {@code
940 * null} by default) will be returned as the result of subsequent
941 * invocations of {@code join} and related operations.
942 *
943 * @since 1.8
944 */
945 public final void quietlyComplete() {
946 setDone();
947 }
948
949 /**
950 * Waits if necessary for the computation to complete, and then
951 * retrieves its result.
952 *
953 * @return the computed result
954 * @throws CancellationException if the computation was cancelled
955 * @throws ExecutionException if the computation threw an
956 * exception
957 * @throws InterruptedException if the current thread is not a
958 * member of a ForkJoinPool and was interrupted while waiting
959 */
960 public final V get() throws InterruptedException, ExecutionException {
961 int s;
962 if (((s = awaitJoin(false, true, false, 0L)) & ABNORMAL) != 0)
963 reportExecutionException(s);
964 return getRawResult();
965 }
966
967 /**
968 * Waits if necessary for at most the given time for the computation
969 * to complete, and then retrieves its result, if available.
970 *
971 * @param timeout the maximum time to wait
972 * @param unit the time unit of the timeout argument
973 * @return the computed result
974 * @throws CancellationException if the computation was cancelled
975 * @throws ExecutionException if the computation threw an
976 * exception
977 * @throws InterruptedException if the current thread is not a
978 * member of a ForkJoinPool and was interrupted while waiting
979 * @throws TimeoutException if the wait timed out
980 */
981 public final V get(long timeout, TimeUnit unit)
982 throws InterruptedException, ExecutionException, TimeoutException {
983 int s;
984 if ((s = awaitJoin(false, true, true, unit.toNanos(timeout))) >= 0 ||
985 (s & ABNORMAL) != 0)
986 reportExecutionException(s);
987 return getRawResult();
988 }
989
990 /**
991 * Joins this task, without returning its result or throwing its
992 * exception. This method may be useful when processing
993 * collections of tasks when some have been cancelled or otherwise
994 * known to have aborted.
995 */
996 public final void quietlyJoin() {
997 if (status >= 0)
998 awaitJoin(false, false, false, 0L);
999 }
1000
1001 /**
1002 * Commences performing this task and awaits its completion if
1003 * necessary, without returning its result or throwing its
1004 * exception.
1005 */
1006 public final void quietlyInvoke() {
1007 if (doExec() >= 0)
1008 awaitJoin(true, false, false, 0L);
1009 }
1010
1011 /**
1012 * Possibly executes tasks until the pool hosting the current task
1013 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This
1014 * method may be of use in designs in which many tasks are forked,
1015 * but none are explicitly joined, instead executing them until
1016 * all are processed.
1017 */
1018 public static void helpQuiesce() {
1019 Thread t; ForkJoinWorkerThread w; ForkJoinPool p;
1020 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
1021 (p = (w = (ForkJoinWorkerThread)t).pool) != null)
1022 p.helpQuiescePool(w.workQueue, Long.MAX_VALUE, false);
1023 else
1024 ForkJoinPool.common.externalHelpQuiescePool(Long.MAX_VALUE, false);
1025 }
1026
1027 /**
1028 * Resets the internal bookkeeping state of this task, allowing a
1029 * subsequent {@code fork}. This method allows repeated reuse of
1030 * this task, but only if reuse occurs when this task has either
1031 * never been forked, or has been forked, then completed and all
1032 * outstanding joins of this task have also completed. Effects
1033 * under any other usage conditions are not guaranteed.
1034 * This method may be useful when executing
1035 * pre-constructed trees of subtasks in loops.
1036 *
1037 * <p>Upon completion of this method, {@code isDone()} reports
1038 * {@code false}, and {@code getException()} reports {@code
1039 * null}. However, the value returned by {@code getRawResult} is
1040 * unaffected. To clear this value, you can invoke {@code
1041 * setRawResult(null)}.
1042 */
1043 public void reinitialize() {
1044 aux = null;
1045 status = 0;
1046 }
1047
1048 /**
1049 * Returns the pool hosting the current thread, or {@code null}
1050 * if the current thread is executing outside of any ForkJoinPool.
1051 *
1052 * <p>This method returns {@code null} if and only if {@link
1053 * #inForkJoinPool} returns {@code false}.
1054 *
1055 * @return the pool, or {@code null} if none
1056 */
1057 public static ForkJoinPool getPool() {
1058 Thread t;
1059 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1060 ((ForkJoinWorkerThread) t).pool : null);
1061 }
1062
1063 /**
1064 * Returns {@code true} if the current thread is a {@link
1065 * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1066 *
1067 * @return {@code true} if the current thread is a {@link
1068 * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1069 * or {@code false} otherwise
1070 */
1071 public static boolean inForkJoinPool() {
1072 return Thread.currentThread() instanceof ForkJoinWorkerThread;
1073 }
1074
1075 /**
1076 * Tries to unschedule this task for execution. This method will
1077 * typically (but is not guaranteed to) succeed if this task is
1078 * the most recently forked task by the current thread, and has
1079 * not commenced executing in another thread. This method may be
1080 * useful when arranging alternative local processing of tasks
1081 * that could have been, but were not, stolen.
1082 *
1083 * @return {@code true} if unforked
1084 */
1085 public boolean tryUnfork() {
1086 Thread t; ForkJoinPool.WorkQueue q;
1087 return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1088 ? (q = ((ForkJoinWorkerThread)t).workQueue) != null
1089 && q.tryUnpush(this)
1090 : (q = ForkJoinPool.commonQueue()) != null
1091 && q.externalTryUnpush(this);
1092 }
1093
1094 /**
1095 * Returns an estimate of the number of tasks that have been
1096 * forked by the current worker thread but not yet executed. This
1097 * value may be useful for heuristic decisions about whether to
1098 * fork other tasks.
1099 *
1100 * @return the number of tasks
1101 */
1102 public static int getQueuedTaskCount() {
1103 Thread t; ForkJoinPool.WorkQueue q;
1104 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1105 q = ((ForkJoinWorkerThread)t).workQueue;
1106 else
1107 q = ForkJoinPool.commonQueue();
1108 return (q == null) ? 0 : q.queueSize();
1109 }
1110
1111 /**
1112 * Returns an estimate of how many more locally queued tasks are
1113 * held by the current worker thread than there are other worker
1114 * threads that might steal them, or zero if this thread is not
1115 * operating in a ForkJoinPool. This value may be useful for
1116 * heuristic decisions about whether to fork other tasks. In many
1117 * usages of ForkJoinTasks, at steady state, each worker should
1118 * aim to maintain a small constant surplus (for example, 3) of
1119 * tasks, and to process computations locally if this threshold is
1120 * exceeded.
1121 *
1122 * @return the surplus number of tasks, which may be negative
1123 */
1124 public static int getSurplusQueuedTaskCount() {
1125 return ForkJoinPool.getSurplusQueuedTaskCount();
1126 }
1127
1128 // Extension methods
1129
1130 /**
1131 * Returns the result that would be returned by {@link #join}, even
1132 * if this task completed abnormally, or {@code null} if this task
1133 * is not known to have been completed. This method is designed
1134 * to aid debugging, as well as to support extensions. Its use in
1135 * any other context is discouraged.
1136 *
1137 * @return the result, or {@code null} if not completed
1138 */
1139 public abstract V getRawResult();
1140
1141 /**
1142 * Forces the given value to be returned as a result. This method
1143 * is designed to support extensions, and should not in general be
1144 * called otherwise.
1145 *
1146 * @param value the value
1147 */
1148 protected abstract void setRawResult(V value);
1149
1150 /**
1151 * Immediately performs the base action of this task and returns
1152 * true if, upon return from this method, this task is guaranteed
1153 * to have completed. This method may return false otherwise, to
1154 * indicate that this task is not necessarily complete (or is not
1155 * known to be complete), for example in asynchronous actions that
1156 * require explicit invocations of completion methods. This method
1157 * may also throw an (unchecked) exception to indicate abnormal
1158 * exit. This method is designed to support extensions, and should
1159 * not in general be called otherwise.
1160 *
1161 * @return {@code true} if this task is known to have completed normally
1162 */
1163 protected abstract boolean exec();
1164
1165 /**
1166 * Returns, but does not unschedule or execute, a task queued by
1167 * the current thread but not yet executed, if one is immediately
1168 * available. There is no guarantee that this task will actually
1169 * be polled or executed next. Conversely, this method may return
1170 * null even if a task exists but cannot be accessed without
1171 * contention with other threads. This method is designed
1172 * primarily to support extensions, and is unlikely to be useful
1173 * otherwise.
1174 *
1175 * @return the next task, or {@code null} if none are available
1176 */
1177 protected static ForkJoinTask<?> peekNextLocalTask() {
1178 Thread t; ForkJoinPool.WorkQueue q;
1179 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1180 q = ((ForkJoinWorkerThread)t).workQueue;
1181 else
1182 q = ForkJoinPool.commonQueue();
1183 return (q == null) ? null : q.peek();
1184 }
1185
1186 /**
1187 * Unschedules and returns, without executing, the next task
1188 * queued by the current thread but not yet executed, if the
1189 * current thread is operating in a ForkJoinPool. This method is
1190 * designed primarily to support extensions, and is unlikely to be
1191 * useful otherwise.
1192 *
1193 * @return the next task, or {@code null} if none are available
1194 */
1195 protected static ForkJoinTask<?> pollNextLocalTask() {
1196 Thread t;
1197 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1198 ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null);
1199 }
1200
1201 /**
1202 * If the current thread is operating in a ForkJoinPool,
1203 * unschedules and returns, without executing, the next task
1204 * queued by the current thread but not yet executed, if one is
1205 * available, or if not available, a task that was forked by some
1206 * other thread, if available. Availability may be transient, so a
1207 * {@code null} result does not necessarily imply quiescence of
1208 * the pool this task is operating in. This method is designed
1209 * primarily to support extensions, and is unlikely to be useful
1210 * otherwise.
1211 *
1212 * @return a task, or {@code null} if none are available
1213 */
1214 protected static ForkJoinTask<?> pollTask() {
1215 Thread t; ForkJoinWorkerThread w;
1216 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1217 (w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) :
1218 null);
1219 }
1220
1221 /**
1222 * If the current thread is operating in a ForkJoinPool,
1223 * unschedules and returns, without executing, a task externally
1224 * submitted to the pool, if one is available. Availability may be
1225 * transient, so a {@code null} result does not necessarily imply
1226 * quiescence of the pool. This method is designed primarily to
1227 * support extensions, and is unlikely to be useful otherwise.
1228 *
1229 * @return a task, or {@code null} if none are available
1230 * @since 9
1231 */
1232 protected static ForkJoinTask<?> pollSubmission() {
1233 Thread t;
1234 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1235 ((ForkJoinWorkerThread)t).pool.pollSubmission() : null);
1236 }
1237
1238 // tag operations
1239
1240 /**
1241 * Returns the tag for this task.
1242 *
1243 * @return the tag for this task
1244 * @since 1.8
1245 */
1246 public final short getForkJoinTaskTag() {
1247 return (short)status;
1248 }
1249
1250 /**
1251 * Atomically sets the tag value for this task and returns the old value.
1252 *
1253 * @param newValue the new tag value
1254 * @return the previous value of the tag
1255 * @since 1.8
1256 */
1257 public final short setForkJoinTaskTag(short newValue) {
1258 for (int s;;) {
1259 if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK)))
1260 return (short)s;
1261 }
1262 }
1263
1264 /**
1265 * Atomically conditionally sets the tag value for this task.
1266 * Among other applications, tags can be used as visit markers
1267 * in tasks operating on graphs, as in methods that check: {@code
1268 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1269 * before processing, otherwise exiting because the node has
1270 * already been visited.
1271 *
1272 * @param expect the expected tag value
1273 * @param update the new tag value
1274 * @return {@code true} if successful; i.e., the current value was
1275 * equal to {@code expect} and was changed to {@code update}.
1276 * @since 1.8
1277 */
1278 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) {
1279 for (int s;;) {
1280 if ((short)(s = status) != expect)
1281 return false;
1282 if (casStatus(s, (s & ~SMASK) | (update & SMASK)))
1283 return true;
1284 }
1285 }
1286
1287 /**
1288 * Adapter for Runnables. This implements RunnableFuture
1289 * to be compliant with AbstractExecutorService constraints
1290 * when used in ForkJoinPool.
1291 */
1292 static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1293 implements RunnableFuture<T> {
1294 @SuppressWarnings("serial") // Conditionally serializable
1295 final Runnable runnable;
1296 @SuppressWarnings("serial") // Conditionally serializable
1297 T result;
1298 AdaptedRunnable(Runnable runnable, T result) {
1299 if (runnable == null) throw new NullPointerException();
1300 this.runnable = runnable;
1301 this.result = result; // OK to set this even before completion
1302 }
1303 public final T getRawResult() { return result; }
1304 public final void setRawResult(T v) { result = v; }
1305 public final boolean exec() { runnable.run(); return true; }
1306 public final void run() { invoke(); }
1307 public String toString() {
1308 return super.toString() + "[Wrapped task = " + runnable + "]";
1309 }
1310 private static final long serialVersionUID = 5232453952276885070L;
1311 }
1312
1313 /**
1314 * Adapter for Runnables without results.
1315 */
1316 static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1317 implements RunnableFuture<Void> {
1318 @SuppressWarnings("serial") // Conditionally serializable
1319 final Runnable runnable;
1320 AdaptedRunnableAction(Runnable runnable) {
1321 if (runnable == null) throw new NullPointerException();
1322 this.runnable = runnable;
1323 }
1324 public final Void getRawResult() { return null; }
1325 public final void setRawResult(Void v) { }
1326 public final boolean exec() { runnable.run(); return true; }
1327 public final void run() { invoke(); }
1328 public String toString() {
1329 return super.toString() + "[Wrapped task = " + runnable + "]";
1330 }
1331 private static final long serialVersionUID = 5232453952276885070L;
1332 }
1333
1334 /**
1335 * Adapter for Runnables in which failure forces worker exception.
1336 */
1337 static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1338 @SuppressWarnings("serial") // Conditionally serializable
1339 final Runnable runnable;
1340 RunnableExecuteAction(Runnable runnable) {
1341 if (runnable == null) throw new NullPointerException();
1342 this.runnable = runnable;
1343 }
1344 public final Void getRawResult() { return null; }
1345 public final void setRawResult(Void v) { }
1346 public final boolean exec() { runnable.run(); return true; }
1347 int trySetException(Throwable ex) {
1348 int s; // if runnable has a handler, invoke it
1349 if (isExceptionalStatus(s = trySetThrown(ex)) &&
1350 runnable instanceof java.lang.Thread.UncaughtExceptionHandler) {
1351 try {
1352 ((java.lang.Thread.UncaughtExceptionHandler)runnable).
1353 uncaughtException(Thread.currentThread(), ex);
1354 } catch (Throwable ignore) {
1355 }
1356 }
1357 return s;
1358 }
1359 private static final long serialVersionUID = 5232453952276885070L;
1360 }
1361
1362 /**
1363 * Adapter for Callables.
1364 */
1365 static final class AdaptedCallable<T> extends ForkJoinTask<T>
1366 implements RunnableFuture<T> {
1367 @SuppressWarnings("serial") // Conditionally serializable
1368 final Callable<? extends T> callable;
1369 @SuppressWarnings("serial") // Conditionally serializable
1370 T result;
1371 AdaptedCallable(Callable<? extends T> callable) {
1372 if (callable == null) throw new NullPointerException();
1373 this.callable = callable;
1374 }
1375 public final T getRawResult() { return result; }
1376 public final void setRawResult(T v) { result = v; }
1377 public final boolean exec() {
1378 try {
1379 result = callable.call();
1380 return true;
1381 } catch (RuntimeException rex) {
1382 throw rex;
1383 } catch (Exception ex) {
1384 throw new RuntimeException(ex);
1385 }
1386 }
1387 public final void run() { invoke(); }
1388 public String toString() {
1389 return super.toString() + "[Wrapped task = " + callable + "]";
1390 }
1391 private static final long serialVersionUID = 2838392045355241008L;
1392 }
1393
1394 static final class AdaptedInterruptibleCallable<T> extends ForkJoinTask<T>
1395 implements RunnableFuture<T> {
1396 @SuppressWarnings("serial") // Conditionally serializable
1397 final Callable<? extends T> callable;
1398 @SuppressWarnings("serial") // Conditionally serializable
1399 transient volatile Thread runner;
1400 T result;
1401 AdaptedInterruptibleCallable(Callable<? extends T> callable) {
1402 if (callable == null) throw new NullPointerException();
1403 this.callable = callable;
1404 }
1405 public final T getRawResult() { return result; }
1406 public final void setRawResult(T v) { result = v; }
1407 public final boolean exec() {
1408 Thread.interrupted();
1409 runner = Thread.currentThread();
1410 try {
1411 if (!isDone()) // recheck
1412 result = callable.call();
1413 return true;
1414 } catch (RuntimeException rex) {
1415 throw rex;
1416 } catch (Exception ex) {
1417 throw new RuntimeException(ex);
1418 } finally {
1419 runner = null;
1420 Thread.interrupted();
1421 }
1422 }
1423 public final void run() { invoke(); }
1424 public final boolean cancel(boolean mayInterruptIfRunning) {
1425 Thread t;
1426 boolean stat = super.cancel(false);
1427 if (mayInterruptIfRunning && (t = runner) != null) {
1428 try {
1429 t.interrupt();
1430 } catch (Throwable ignore) {
1431 }
1432 }
1433 return stat;
1434 }
1435 public String toString() {
1436 return super.toString() + "[Wrapped task = " + callable + "]";
1437 }
1438 private static final long serialVersionUID = 2838392045355241008L;
1439 }
1440
1441 /**
1442 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1443 * method of the given {@code Runnable} as its action, and returns
1444 * a null result upon {@link #join}.
1445 *
1446 * @param runnable the runnable action
1447 * @return the task
1448 */
1449 public static ForkJoinTask<?> adapt(Runnable runnable) {
1450 return new AdaptedRunnableAction(runnable);
1451 }
1452
1453 /**
1454 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1455 * method of the given {@code Runnable} as its action, and returns
1456 * the given result upon {@link #join}.
1457 *
1458 * @param runnable the runnable action
1459 * @param result the result upon completion
1460 * @param <T> the type of the result
1461 * @return the task
1462 */
1463 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1464 return new AdaptedRunnable<T>(runnable, result);
1465 }
1466
1467 /**
1468 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1469 * method of the given {@code Callable} as its action, and returns
1470 * its result upon {@link #join}, translating any checked exceptions
1471 * encountered into {@code RuntimeException}.
1472 *
1473 * @param callable the callable action
1474 * @param <T> the type of the callable's result
1475 * @return the task
1476 */
1477 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1478 return new AdaptedCallable<T>(callable);
1479 }
1480
1481 /**
1482 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1483 * method of the given {@code Callable} as its action, and returns
1484 * its result upon {@link #join}, translating any checked exceptions
1485 * encountered into {@code RuntimeException}. Additionally,
1486 * invocations of {@code cancel} with {@code mayInterruptIfRunning
1487 * true} will attempt to interrupt the thread performing the task.
1488 *
1489 * @param callable the callable action
1490 * @param <T> the type of the callable's result
1491 * @return the task
1492 *
1493 * @since 15
1494 */
1495 public static <T> ForkJoinTask<T> adaptInterruptible(Callable<? extends T> callable) {
1496 return new AdaptedInterruptibleCallable<T>(callable);
1497 }
1498
1499 // Serialization support
1500
1501 private static final long serialVersionUID = -7721805057305804111L;
1502
1503 /**
1504 * Saves this task to a stream (that is, serializes it).
1505 *
1506 * @param s the stream
1507 * @throws java.io.IOException if an I/O error occurs
1508 * @serialData the current run status and the exception thrown
1509 * during execution, or {@code null} if none
1510 */
1511 private void writeObject(java.io.ObjectOutputStream s)
1512 throws java.io.IOException {
1513 Aux a;
1514 s.defaultWriteObject();
1515 s.writeObject((a = aux) == null ? null : a.ex);
1516 }
1517
1518 /**
1519 * Reconstitutes this task from a stream (that is, deserializes it).
1520 * @param s the stream
1521 * @throws ClassNotFoundException if the class of a serialized object
1522 * could not be found
1523 * @throws java.io.IOException if an I/O error occurs
1524 */
1525 private void readObject(java.io.ObjectInputStream s)
1526 throws java.io.IOException, ClassNotFoundException {
1527 s.defaultReadObject();
1528 Object ex = s.readObject();
1529 if (ex != null)
1530 trySetThrown((Throwable)ex);
1531 }
1532
1533 static {
1534 try {
1535 MethodHandles.Lookup l = MethodHandles.lookup();
1536 STATUS = l.findVarHandle(ForkJoinTask.class, "status", int.class);
1537 AUX = l.findVarHandle(ForkJoinTask.class, "aux", Aux.class);
1538 } catch (ReflectiveOperationException e) {
1539 throw new ExceptionInInitializerError(e);
1540 }
1541 }
1542
1543 }