ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.142
Committed: Wed Aug 12 15:52:08 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.141: +1 -1 lines
Log Message:
fix errorprone [UnusedVariable]

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