ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.147
Committed: Fri Dec 4 20:29:22 2020 UTC (3 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.146: +4 -18 lines
Log Message:
JDK-8246587: adaptInterruptible deferred to its own independent change

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