ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.149
Committed: Sun Jan 31 13:35:43 2021 UTC (3 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.148: +4 -1 lines
Log Message:
Allow self-steal retries; expanding cases covered with parallelism 0

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 (!ran &&
473 (!internal && q.externalTryUnpush(this)) ||
474 q.tryRemove(this, internal)) &&
475 (s = doExec()) < 0))
476 return s;
477 if (internal) {
478 if ((s = p.helpJoin(this, q)) < 0)
479 return s;
480 if (s == UNCOMPENSATE)
481 uncompensate = p;
482 interruptible = false;
483 }
484 }
485 return awaitDone(interruptible, deadline, uncompensate);
486 }
487
488 /**
489 * Cancels, ignoring any exceptions thrown by cancel. Cancel is
490 * spec'ed not to throw any exceptions, but if it does anyway, we
491 * have no recourse, so guard against this case.
492 */
493 static final void cancelIgnoringExceptions(Future<?> t) {
494 if (t != null) {
495 try {
496 t.cancel(true);
497 } catch (Throwable ignore) {
498 }
499 }
500 }
501
502 /**
503 * Returns a rethrowable exception for this task, if available.
504 * To provide accurate stack traces, if the exception was not
505 * thrown by the current thread, we try to create a new exception
506 * of the same type as the one thrown, but with the recorded
507 * exception as its cause. If there is no such constructor, we
508 * instead try to use a no-arg constructor, followed by initCause,
509 * to the same effect. If none of these apply, or any fail due to
510 * other exceptions, we return the recorded exception, which is
511 * still correct, although it may contain a misleading stack
512 * trace.
513 *
514 * @return the exception, or null if none
515 */
516 private Throwable getThrowableException() {
517 Throwable ex; Aux a;
518 if ((a = aux) == null)
519 ex = null;
520 else if ((ex = a.ex) != null && a.thread != Thread.currentThread()) {
521 try {
522 Constructor<?> noArgCtor = null, oneArgCtor = null;
523 for (Constructor<?> c : ex.getClass().getConstructors()) {
524 Class<?>[] ps = c.getParameterTypes();
525 if (ps.length == 0)
526 noArgCtor = c;
527 else if (ps.length == 1 && ps[0] == Throwable.class) {
528 oneArgCtor = c;
529 break;
530 }
531 }
532 if (oneArgCtor != null)
533 ex = (Throwable)oneArgCtor.newInstance(ex);
534 else if (noArgCtor != null) {
535 Throwable rx = (Throwable)noArgCtor.newInstance();
536 rx.initCause(ex);
537 ex = rx;
538 }
539 } catch (Exception ignore) {
540 }
541 }
542 return ex;
543 }
544
545 /**
546 * Returns exception associated with the given status, or null if none.
547 */
548 private Throwable getException(int s) {
549 Throwable ex = null;
550 if ((s & ABNORMAL) != 0 &&
551 ((s & THROWN) == 0 || (ex = getThrowableException()) == null))
552 ex = new CancellationException();
553 return ex;
554 }
555
556 /**
557 * Throws exception associated with the given status, or
558 * CancellationException if none recorded.
559 */
560 private void reportException(int s) {
561 ForkJoinTask.<RuntimeException>uncheckedThrow(
562 (s & THROWN) != 0 ? getThrowableException() : null);
563 }
564
565 /**
566 * Throws exception for (timed or untimed) get, wrapping if
567 * necessary in an ExecutionException.
568 */
569 private void reportExecutionException(int s) {
570 Throwable ex = null;
571 if (s == ABNORMAL)
572 ex = new InterruptedException();
573 else if (s >= 0)
574 ex = new TimeoutException();
575 else if ((s & THROWN) != 0 && (ex = getThrowableException()) != null)
576 ex = new ExecutionException(ex);
577 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
578 }
579
580 /**
581 * A version of "sneaky throw" to relay exceptions in other
582 * contexts.
583 */
584 static void rethrow(Throwable ex) {
585 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
586 }
587
588 /**
589 * The sneaky part of sneaky throw, relying on generics
590 * limitations to evade compiler complaints about rethrowing
591 * unchecked exceptions. If argument null, throws
592 * CancellationException.
593 */
594 @SuppressWarnings("unchecked") static <T extends Throwable>
595 void uncheckedThrow(Throwable t) throws T {
596 if (t == null)
597 t = new CancellationException();
598 throw (T)t; // rely on vacuous cast
599 }
600
601 // public methods
602
603 /**
604 * Arranges to asynchronously execute this task in the pool the
605 * current task is running in, if applicable, or using the {@link
606 * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While
607 * it is not necessarily enforced, it is a usage error to fork a
608 * task more than once unless it has completed and been
609 * reinitialized. Subsequent modifications to the state of this
610 * task or any data it operates on are not necessarily
611 * consistently observable by any thread other than the one
612 * executing it unless preceded by a call to {@link #join} or
613 * related methods, or a call to {@link #isDone} returning {@code
614 * true}.
615 *
616 * @return {@code this}, to simplify usage
617 */
618 public final ForkJoinTask<V> fork() {
619 Thread t; ForkJoinWorkerThread w;
620 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
621 (w = (ForkJoinWorkerThread)t).workQueue.push(this, w.pool);
622 else
623 ForkJoinPool.common.externalPush(this);
624 return this;
625 }
626
627 /**
628 * Returns the result of the computation when it
629 * {@linkplain #isDone is done}.
630 * This method differs from {@link #get()} in that abnormal
631 * completion results in {@code RuntimeException} or {@code Error},
632 * not {@code ExecutionException}, and that interrupts of the
633 * calling thread do <em>not</em> cause the method to abruptly
634 * return by throwing {@code InterruptedException}.
635 *
636 * @return the computed result
637 */
638 public final V join() {
639 int s;
640 if ((s = status) >= 0)
641 s = awaitJoin(false, false, false, 0L);
642 if ((s & ABNORMAL) != 0)
643 reportException(s);
644 return getRawResult();
645 }
646
647 /**
648 * Commences performing this task, awaits its completion if
649 * necessary, and returns its result, or throws an (unchecked)
650 * {@code RuntimeException} or {@code Error} if the underlying
651 * computation did so.
652 *
653 * @return the computed result
654 */
655 public final V invoke() {
656 int s;
657 if ((s = doExec()) >= 0)
658 s = awaitJoin(true, false, false, 0L);
659 if ((s & ABNORMAL) != 0)
660 reportException(s);
661 return getRawResult();
662 }
663
664 /**
665 * Forks the given tasks, returning when {@code isDone} holds for
666 * each task or an (unchecked) exception is encountered, in which
667 * case the exception is rethrown. If more than one task
668 * encounters an exception, then this method throws any one of
669 * these exceptions. If any task encounters an exception, the
670 * other may be cancelled. However, the execution status of
671 * individual tasks is not guaranteed upon exceptional return. The
672 * status of each task may be obtained using {@link
673 * #getException()} and related methods to check if they have been
674 * cancelled, completed normally or exceptionally, or left
675 * unprocessed.
676 *
677 * @param t1 the first task
678 * @param t2 the second task
679 * @throws NullPointerException if any task is null
680 */
681 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
682 int s1, s2;
683 if (t1 == null || t2 == null)
684 throw new NullPointerException();
685 t2.fork();
686 if ((s1 = t1.doExec()) >= 0)
687 s1 = t1.awaitJoin(true, false, false, 0L);
688 if ((s1 & ABNORMAL) != 0) {
689 cancelIgnoringExceptions(t2);
690 t1.reportException(s1);
691 }
692 else if (((s2 = t2.awaitJoin(false, false, false, 0L)) & ABNORMAL) != 0)
693 t2.reportException(s2);
694 }
695
696 /**
697 * Forks the given tasks, returning when {@code isDone} holds for
698 * each task or an (unchecked) exception is encountered, in which
699 * case the exception is rethrown. If more than one task
700 * encounters an exception, then this method throws any one of
701 * these exceptions. If any task encounters an exception, others
702 * may be cancelled. However, the execution status of individual
703 * tasks is not guaranteed upon exceptional return. The status of
704 * each task may be obtained using {@link #getException()} and
705 * related methods to check if they have been cancelled, completed
706 * normally or exceptionally, or left unprocessed.
707 *
708 * @param tasks the tasks
709 * @throws NullPointerException if any task is null
710 */
711 public static void invokeAll(ForkJoinTask<?>... tasks) {
712 Throwable ex = null;
713 int last = tasks.length - 1;
714 for (int i = last; i >= 0; --i) {
715 ForkJoinTask<?> t;
716 if ((t = tasks[i]) == null) {
717 ex = new NullPointerException();
718 break;
719 }
720 if (i == 0) {
721 int s;
722 if ((s = t.doExec()) >= 0)
723 s = t.awaitJoin(true, false, false, 0L);
724 if ((s & ABNORMAL) != 0)
725 ex = t.getException(s);
726 break;
727 }
728 t.fork();
729 }
730 if (ex == null) {
731 for (int i = 1; i <= last; ++i) {
732 ForkJoinTask<?> t;
733 if ((t = tasks[i]) != null) {
734 int s;
735 if ((s = t.status) >= 0)
736 s = t.awaitJoin(false, false, false, 0L);
737 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
738 break;
739 }
740 }
741 }
742 if (ex != null) {
743 for (int i = 1; i <= last; ++i)
744 cancelIgnoringExceptions(tasks[i]);
745 rethrow(ex);
746 }
747 }
748
749 /**
750 * Forks all tasks in the specified collection, returning when
751 * {@code isDone} holds for each task or an (unchecked) exception
752 * is encountered, in which case the exception is rethrown. If
753 * more than one task encounters an exception, then this method
754 * throws any one of these exceptions. If any task encounters an
755 * exception, others may be cancelled. However, the execution
756 * status of individual tasks is not guaranteed upon exceptional
757 * return. The status of each task may be obtained using {@link
758 * #getException()} and related methods to check if they have been
759 * cancelled, completed normally or exceptionally, or left
760 * unprocessed.
761 *
762 * @param tasks the collection of tasks
763 * @param <T> the type of the values returned from the tasks
764 * @return the tasks argument, to simplify usage
765 * @throws NullPointerException if tasks or any element are null
766 */
767 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
768 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
769 invokeAll(tasks.toArray(new ForkJoinTask<?>[0]));
770 return tasks;
771 }
772 @SuppressWarnings("unchecked")
773 List<? extends ForkJoinTask<?>> ts =
774 (List<? extends ForkJoinTask<?>>) tasks;
775 Throwable ex = null;
776 int last = ts.size() - 1; // nearly same as array version
777 for (int i = last; i >= 0; --i) {
778 ForkJoinTask<?> t;
779 if ((t = ts.get(i)) == null) {
780 ex = new NullPointerException();
781 break;
782 }
783 if (i == 0) {
784 int s;
785 if ((s = t.doExec()) >= 0)
786 s = t.awaitJoin(true, false, false, 0L);
787 if ((s & ABNORMAL) != 0)
788 ex = t.getException(s);
789 break;
790 }
791 t.fork();
792 }
793 if (ex == null) {
794 for (int i = 1; i <= last; ++i) {
795 ForkJoinTask<?> t;
796 if ((t = ts.get(i)) != null) {
797 int s;
798 if ((s = t.status) >= 0)
799 s = t.awaitJoin(false, false, false, 0L);
800 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
801 break;
802 }
803 }
804 }
805 if (ex != null) {
806 for (int i = 1; i <= last; ++i)
807 cancelIgnoringExceptions(ts.get(i));
808 rethrow(ex);
809 }
810 return tasks;
811 }
812
813 /**
814 * Attempts to cancel execution of this task. This attempt will
815 * fail if the task has already completed or could not be
816 * cancelled for some other reason. If successful, and this task
817 * has not started when {@code cancel} is called, execution of
818 * this task is suppressed. After this method returns
819 * successfully, unless there is an intervening call to {@link
820 * #reinitialize}, subsequent calls to {@link #isCancelled},
821 * {@link #isDone}, and {@code cancel} will return {@code true}
822 * and calls to {@link #join} and related methods will result in
823 * {@code CancellationException}.
824 *
825 * <p>This method may be overridden in subclasses, but if so, must
826 * still ensure that these properties hold. In particular, the
827 * {@code cancel} method itself must not throw exceptions.
828 *
829 * <p>This method is designed to be invoked by <em>other</em>
830 * tasks. To terminate the current task, you can just return or
831 * throw an unchecked exception from its computation method, or
832 * invoke {@link #completeExceptionally(Throwable)}.
833 *
834 * @param mayInterruptIfRunning this value has no effect in the
835 * default implementation because interrupts are not used to
836 * control cancellation.
837 *
838 * @return {@code true} if this task is now cancelled
839 */
840 public boolean cancel(boolean mayInterruptIfRunning) {
841 return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL;
842 }
843
844 public final boolean isDone() {
845 return status < 0;
846 }
847
848 public final boolean isCancelled() {
849 return (status & (ABNORMAL | THROWN)) == ABNORMAL;
850 }
851
852 /**
853 * Returns {@code true} if this task threw an exception or was cancelled.
854 *
855 * @return {@code true} if this task threw an exception or was cancelled
856 */
857 public final boolean isCompletedAbnormally() {
858 return (status & ABNORMAL) != 0;
859 }
860
861 /**
862 * Returns {@code true} if this task completed without throwing an
863 * exception and was not cancelled.
864 *
865 * @return {@code true} if this task completed without throwing an
866 * exception and was not cancelled
867 */
868 public final boolean isCompletedNormally() {
869 return (status & (DONE | ABNORMAL)) == DONE;
870 }
871
872 /**
873 * Returns the exception thrown by the base computation, or a
874 * {@code CancellationException} if cancelled, or {@code null} if
875 * none or if the method has not yet completed.
876 *
877 * @return the exception, or {@code null} if none
878 */
879 public final Throwable getException() {
880 return getException(status);
881 }
882
883 /**
884 * Completes this task abnormally, and if not already aborted or
885 * cancelled, causes it to throw the given exception upon
886 * {@code join} and related operations. This method may be used
887 * to induce exceptions in asynchronous tasks, or to force
888 * completion of tasks that would not otherwise complete. Its use
889 * in other situations is discouraged. This method is
890 * overridable, but overridden versions must invoke {@code super}
891 * implementation to maintain guarantees.
892 *
893 * @param ex the exception to throw. If this exception is not a
894 * {@code RuntimeException} or {@code Error}, the actual exception
895 * thrown will be a {@code RuntimeException} with cause {@code ex}.
896 */
897 public void completeExceptionally(Throwable ex) {
898 trySetException((ex instanceof RuntimeException) ||
899 (ex instanceof Error) ? ex :
900 new RuntimeException(ex));
901 }
902
903 /**
904 * Completes this task, and if not already aborted or cancelled,
905 * returning the given value as the result of subsequent
906 * invocations of {@code join} and related operations. This method
907 * may be used to provide results for asynchronous tasks, or to
908 * provide alternative handling for tasks that would not otherwise
909 * complete normally. Its use in other situations is
910 * discouraged. This method is overridable, but overridden
911 * versions must invoke {@code super} implementation to maintain
912 * guarantees.
913 *
914 * @param value the result value for this task
915 */
916 public void complete(V value) {
917 try {
918 setRawResult(value);
919 } catch (Throwable rex) {
920 trySetException(rex);
921 return;
922 }
923 setDone();
924 }
925
926 /**
927 * Completes this task normally without setting a value. The most
928 * recent value established by {@link #setRawResult} (or {@code
929 * null} by default) will be returned as the result of subsequent
930 * invocations of {@code join} and related operations.
931 *
932 * @since 1.8
933 */
934 public final void quietlyComplete() {
935 setDone();
936 }
937
938 /**
939 * Waits if necessary for the computation to complete, and then
940 * retrieves its result.
941 *
942 * @return the computed result
943 * @throws CancellationException if the computation was cancelled
944 * @throws ExecutionException if the computation threw an
945 * exception
946 * @throws InterruptedException if the current thread is not a
947 * member of a ForkJoinPool and was interrupted while waiting
948 */
949 public final V get() throws InterruptedException, ExecutionException {
950 int s;
951 if (((s = awaitJoin(false, true, false, 0L)) & ABNORMAL) != 0)
952 reportExecutionException(s);
953 return getRawResult();
954 }
955
956 /**
957 * Waits if necessary for at most the given time for the computation
958 * to complete, and then retrieves its result, if available.
959 *
960 * @param timeout the maximum time to wait
961 * @param unit the time unit of the timeout argument
962 * @return the computed result
963 * @throws CancellationException if the computation was cancelled
964 * @throws ExecutionException if the computation threw an
965 * exception
966 * @throws InterruptedException if the current thread is not a
967 * member of a ForkJoinPool and was interrupted while waiting
968 * @throws TimeoutException if the wait timed out
969 */
970 public final V get(long timeout, TimeUnit unit)
971 throws InterruptedException, ExecutionException, TimeoutException {
972 int s;
973 if ((s = awaitJoin(false, true, true, unit.toNanos(timeout))) >= 0 ||
974 (s & ABNORMAL) != 0)
975 reportExecutionException(s);
976 return getRawResult();
977 }
978
979 /**
980 * Joins this task, without returning its result or throwing its
981 * exception. This method may be useful when processing
982 * collections of tasks when some have been cancelled or otherwise
983 * known to have aborted.
984 */
985 public final void quietlyJoin() {
986 if (status >= 0)
987 awaitJoin(false, false, false, 0L);
988 }
989
990 /**
991 * Commences performing this task and awaits its completion if
992 * necessary, without returning its result or throwing its
993 * exception.
994 */
995 public final void quietlyInvoke() {
996 if (doExec() >= 0)
997 awaitJoin(true, false, false, 0L);
998 }
999
1000 /**
1001 * Possibly executes tasks until the pool hosting the current task
1002 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This
1003 * method may be of use in designs in which many tasks are forked,
1004 * but none are explicitly joined, instead executing them until
1005 * all are processed.
1006 */
1007 public static void helpQuiesce() {
1008 Thread t; ForkJoinWorkerThread w; ForkJoinPool p;
1009 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
1010 (p = (w = (ForkJoinWorkerThread)t).pool) != null)
1011 p.helpQuiescePool(w.workQueue, Long.MAX_VALUE, false);
1012 else
1013 ForkJoinPool.common.externalHelpQuiescePool(Long.MAX_VALUE, false);
1014 }
1015
1016 /**
1017 * Resets the internal bookkeeping state of this task, allowing a
1018 * subsequent {@code fork}. This method allows repeated reuse of
1019 * this task, but only if reuse occurs when this task has either
1020 * never been forked, or has been forked, then completed and all
1021 * outstanding joins of this task have also completed. Effects
1022 * under any other usage conditions are not guaranteed.
1023 * This method may be useful when executing
1024 * pre-constructed trees of subtasks in loops.
1025 *
1026 * <p>Upon completion of this method, {@code isDone()} reports
1027 * {@code false}, and {@code getException()} reports {@code
1028 * null}. However, the value returned by {@code getRawResult} is
1029 * unaffected. To clear this value, you can invoke {@code
1030 * setRawResult(null)}.
1031 */
1032 public void reinitialize() {
1033 aux = null;
1034 status = 0;
1035 }
1036
1037 /**
1038 * Returns the pool hosting the current thread, or {@code null}
1039 * if the current thread is executing outside of any ForkJoinPool.
1040 *
1041 * <p>This method returns {@code null} if and only if {@link
1042 * #inForkJoinPool} returns {@code false}.
1043 *
1044 * @return the pool, or {@code null} if none
1045 */
1046 public static ForkJoinPool getPool() {
1047 Thread t;
1048 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1049 ((ForkJoinWorkerThread) t).pool : null);
1050 }
1051
1052 /**
1053 * Returns {@code true} if the current thread is a {@link
1054 * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1055 *
1056 * @return {@code true} if the current thread is a {@link
1057 * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1058 * or {@code false} otherwise
1059 */
1060 public static boolean inForkJoinPool() {
1061 return Thread.currentThread() instanceof ForkJoinWorkerThread;
1062 }
1063
1064 /**
1065 * Tries to unschedule this task for execution. This method will
1066 * typically (but is not guaranteed to) succeed if this task is
1067 * the most recently forked task by the current thread, and has
1068 * not commenced executing in another thread. This method may be
1069 * useful when arranging alternative local processing of tasks
1070 * that could have been, but were not, stolen.
1071 *
1072 * @return {@code true} if unforked
1073 */
1074 public boolean tryUnfork() {
1075 Thread t; ForkJoinPool.WorkQueue q;
1076 return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1077 ? (q = ((ForkJoinWorkerThread)t).workQueue) != null
1078 && q.tryUnpush(this)
1079 : (q = ForkJoinPool.commonQueue()) != null
1080 && q.externalTryUnpush(this);
1081 }
1082
1083 /**
1084 * Returns an estimate of the number of tasks that have been
1085 * forked by the current worker thread but not yet executed. This
1086 * value may be useful for heuristic decisions about whether to
1087 * fork other tasks.
1088 *
1089 * @return the number of tasks
1090 */
1091 public static int getQueuedTaskCount() {
1092 Thread t; ForkJoinPool.WorkQueue q;
1093 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1094 q = ((ForkJoinWorkerThread)t).workQueue;
1095 else
1096 q = ForkJoinPool.commonQueue();
1097 return (q == null) ? 0 : q.queueSize();
1098 }
1099
1100 /**
1101 * Returns an estimate of how many more locally queued tasks are
1102 * held by the current worker thread than there are other worker
1103 * threads that might steal them, or zero if this thread is not
1104 * operating in a ForkJoinPool. This value may be useful for
1105 * heuristic decisions about whether to fork other tasks. In many
1106 * usages of ForkJoinTasks, at steady state, each worker should
1107 * aim to maintain a small constant surplus (for example, 3) of
1108 * tasks, and to process computations locally if this threshold is
1109 * exceeded.
1110 *
1111 * @return the surplus number of tasks, which may be negative
1112 */
1113 public static int getSurplusQueuedTaskCount() {
1114 return ForkJoinPool.getSurplusQueuedTaskCount();
1115 }
1116
1117 // Extension methods
1118
1119 /**
1120 * Returns the result that would be returned by {@link #join}, even
1121 * if this task completed abnormally, or {@code null} if this task
1122 * is not known to have been completed. This method is designed
1123 * to aid debugging, as well as to support extensions. Its use in
1124 * any other context is discouraged.
1125 *
1126 * @return the result, or {@code null} if not completed
1127 */
1128 public abstract V getRawResult();
1129
1130 /**
1131 * Forces the given value to be returned as a result. This method
1132 * is designed to support extensions, and should not in general be
1133 * called otherwise.
1134 *
1135 * @param value the value
1136 */
1137 protected abstract void setRawResult(V value);
1138
1139 /**
1140 * Immediately performs the base action of this task and returns
1141 * true if, upon return from this method, this task is guaranteed
1142 * to have completed. This method may return false otherwise, to
1143 * indicate that this task is not necessarily complete (or is not
1144 * known to be complete), for example in asynchronous actions that
1145 * require explicit invocations of completion methods. This method
1146 * may also throw an (unchecked) exception to indicate abnormal
1147 * exit. This method is designed to support extensions, and should
1148 * not in general be called otherwise.
1149 *
1150 * @return {@code true} if this task is known to have completed normally
1151 */
1152 protected abstract boolean exec();
1153
1154 /**
1155 * Returns, but does not unschedule or execute, a task queued by
1156 * the current thread but not yet executed, if one is immediately
1157 * available. There is no guarantee that this task will actually
1158 * be polled or executed next. Conversely, this method may return
1159 * null even if a task exists but cannot be accessed without
1160 * contention with other threads. This method is designed
1161 * primarily to support extensions, and is unlikely to be useful
1162 * otherwise.
1163 *
1164 * @return the next task, or {@code null} if none are available
1165 */
1166 protected static ForkJoinTask<?> peekNextLocalTask() {
1167 Thread t; ForkJoinPool.WorkQueue q;
1168 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1169 q = ((ForkJoinWorkerThread)t).workQueue;
1170 else
1171 q = ForkJoinPool.commonQueue();
1172 return (q == null) ? null : q.peek();
1173 }
1174
1175 /**
1176 * Unschedules and returns, without executing, the next task
1177 * queued by the current thread but not yet executed, if the
1178 * current thread is operating in a ForkJoinPool. This method is
1179 * designed primarily to support extensions, and is unlikely to be
1180 * useful otherwise.
1181 *
1182 * @return the next task, or {@code null} if none are available
1183 */
1184 protected static ForkJoinTask<?> pollNextLocalTask() {
1185 Thread t;
1186 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1187 ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null);
1188 }
1189
1190 /**
1191 * If the current thread is operating in a ForkJoinPool,
1192 * unschedules and returns, without executing, the next task
1193 * queued by the current thread but not yet executed, if one is
1194 * available, or if not available, a task that was forked by some
1195 * other thread, if available. Availability may be transient, so a
1196 * {@code null} result does not necessarily imply quiescence of
1197 * the pool this task is operating in. This method is designed
1198 * primarily to support extensions, and is unlikely to be useful
1199 * otherwise.
1200 *
1201 * @return a task, or {@code null} if none are available
1202 */
1203 protected static ForkJoinTask<?> pollTask() {
1204 Thread t; ForkJoinWorkerThread w;
1205 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1206 (w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) :
1207 null);
1208 }
1209
1210 /**
1211 * If the current thread is operating in a ForkJoinPool,
1212 * unschedules and returns, without executing, a task externally
1213 * submitted to the pool, if one is available. Availability may be
1214 * transient, so a {@code null} result does not necessarily imply
1215 * quiescence of the pool. This method is designed primarily to
1216 * support extensions, and is unlikely to be useful otherwise.
1217 *
1218 * @return a task, or {@code null} if none are available
1219 * @since 9
1220 */
1221 protected static ForkJoinTask<?> pollSubmission() {
1222 Thread t;
1223 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1224 ((ForkJoinWorkerThread)t).pool.pollSubmission() : null);
1225 }
1226
1227 // tag operations
1228
1229 /**
1230 * Returns the tag for this task.
1231 *
1232 * @return the tag for this task
1233 * @since 1.8
1234 */
1235 public final short getForkJoinTaskTag() {
1236 return (short)status;
1237 }
1238
1239 /**
1240 * Atomically sets the tag value for this task and returns the old value.
1241 *
1242 * @param newValue the new tag value
1243 * @return the previous value of the tag
1244 * @since 1.8
1245 */
1246 public final short setForkJoinTaskTag(short newValue) {
1247 for (int s;;) {
1248 if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK)))
1249 return (short)s;
1250 }
1251 }
1252
1253 /**
1254 * Atomically conditionally sets the tag value for this task.
1255 * Among other applications, tags can be used as visit markers
1256 * in tasks operating on graphs, as in methods that check: {@code
1257 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1258 * before processing, otherwise exiting because the node has
1259 * already been visited.
1260 *
1261 * @param expect the expected tag value
1262 * @param update the new tag value
1263 * @return {@code true} if successful; i.e., the current value was
1264 * equal to {@code expect} and was changed to {@code update}.
1265 * @since 1.8
1266 */
1267 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) {
1268 for (int s;;) {
1269 if ((short)(s = status) != expect)
1270 return false;
1271 if (casStatus(s, (s & ~SMASK) | (update & SMASK)))
1272 return true;
1273 }
1274 }
1275
1276 /**
1277 * Adapter for Runnables. This implements RunnableFuture
1278 * to be compliant with AbstractExecutorService constraints
1279 * when used in ForkJoinPool.
1280 */
1281 static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1282 implements RunnableFuture<T> {
1283 @SuppressWarnings("serial") // Conditionally serializable
1284 final Runnable runnable;
1285 @SuppressWarnings("serial") // Conditionally serializable
1286 T result;
1287 AdaptedRunnable(Runnable runnable, T result) {
1288 if (runnable == null) throw new NullPointerException();
1289 this.runnable = runnable;
1290 this.result = result; // OK to set this even before completion
1291 }
1292 public final T getRawResult() { return result; }
1293 public final void setRawResult(T v) { result = v; }
1294 public final boolean exec() { runnable.run(); return true; }
1295 public final void run() { invoke(); }
1296 public String toString() {
1297 return super.toString() + "[Wrapped task = " + runnable + "]";
1298 }
1299 private static final long serialVersionUID = 5232453952276885070L;
1300 }
1301
1302 /**
1303 * Adapter for Runnables without results.
1304 */
1305 static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1306 implements RunnableFuture<Void> {
1307 @SuppressWarnings("serial") // Conditionally serializable
1308 final Runnable runnable;
1309 AdaptedRunnableAction(Runnable runnable) {
1310 if (runnable == null) throw new NullPointerException();
1311 this.runnable = runnable;
1312 }
1313 public final Void getRawResult() { return null; }
1314 public final void setRawResult(Void v) { }
1315 public final boolean exec() { runnable.run(); return true; }
1316 public final void run() { invoke(); }
1317 public String toString() {
1318 return super.toString() + "[Wrapped task = " + runnable + "]";
1319 }
1320 private static final long serialVersionUID = 5232453952276885070L;
1321 }
1322
1323 /**
1324 * Adapter for Runnables in which failure forces worker exception.
1325 */
1326 static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1327 @SuppressWarnings("serial") // Conditionally serializable
1328 final Runnable runnable;
1329 RunnableExecuteAction(Runnable runnable) {
1330 if (runnable == null) throw new NullPointerException();
1331 this.runnable = runnable;
1332 }
1333 public final Void getRawResult() { return null; }
1334 public final void setRawResult(Void v) { }
1335 public final boolean exec() { runnable.run(); return true; }
1336 int trySetException(Throwable ex) { // if a handler, invoke it
1337 int s; Thread t; java.lang.Thread.UncaughtExceptionHandler h;
1338 if (isExceptionalStatus(s = trySetThrown(ex)) &&
1339 (h = ((t = Thread.currentThread()).
1340 getUncaughtExceptionHandler())) != null) {
1341 try {
1342 h.uncaughtException(t, ex);
1343 } catch (Throwable ignore) {
1344 }
1345 }
1346 return s;
1347 }
1348 private static final long serialVersionUID = 5232453952276885070L;
1349 }
1350
1351 /**
1352 * Adapter for Callables.
1353 */
1354 static final class AdaptedCallable<T> extends ForkJoinTask<T>
1355 implements RunnableFuture<T> {
1356 @SuppressWarnings("serial") // Conditionally serializable
1357 final Callable<? extends T> callable;
1358 @SuppressWarnings("serial") // Conditionally serializable
1359 T result;
1360 AdaptedCallable(Callable<? extends T> callable) {
1361 if (callable == null) throw new NullPointerException();
1362 this.callable = callable;
1363 }
1364 public final T getRawResult() { return result; }
1365 public final void setRawResult(T v) { result = v; }
1366 public final boolean exec() {
1367 try {
1368 result = callable.call();
1369 return true;
1370 } catch (RuntimeException rex) {
1371 throw rex;
1372 } catch (Exception ex) {
1373 throw new RuntimeException(ex);
1374 }
1375 }
1376 public final void run() { invoke(); }
1377 public String toString() {
1378 return super.toString() + "[Wrapped task = " + callable + "]";
1379 }
1380 private static final long serialVersionUID = 2838392045355241008L;
1381 }
1382
1383 static final class AdaptedInterruptibleCallable<T> extends ForkJoinTask<T>
1384 implements RunnableFuture<T> {
1385 @SuppressWarnings("serial") // Conditionally serializable
1386 final Callable<? extends T> callable;
1387 @SuppressWarnings("serial") // Conditionally serializable
1388 transient volatile Thread runner;
1389 T result;
1390 AdaptedInterruptibleCallable(Callable<? extends T> callable) {
1391 if (callable == null) throw new NullPointerException();
1392 this.callable = callable;
1393 }
1394 public final T getRawResult() { return result; }
1395 public final void setRawResult(T v) { result = v; }
1396 public final boolean exec() {
1397 Thread.interrupted();
1398 runner = Thread.currentThread();
1399 try {
1400 if (!isDone()) // recheck
1401 result = callable.call();
1402 return true;
1403 } catch (RuntimeException rex) {
1404 throw rex;
1405 } catch (Exception ex) {
1406 throw new RuntimeException(ex);
1407 } finally {
1408 runner = null;
1409 Thread.interrupted();
1410 }
1411 }
1412 public final void run() { invoke(); }
1413 public final boolean cancel(boolean mayInterruptIfRunning) {
1414 Thread t;
1415 boolean stat = super.cancel(false);
1416 if (mayInterruptIfRunning && (t = runner) != null) {
1417 try {
1418 t.interrupt();
1419 } catch (Throwable ignore) {
1420 }
1421 }
1422 return stat;
1423 }
1424 public String toString() {
1425 return super.toString() + "[Wrapped task = " + callable + "]";
1426 }
1427 private static final long serialVersionUID = 2838392045355241008L;
1428 }
1429
1430 /**
1431 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1432 * method of the given {@code Runnable} as its action, and returns
1433 * a null result upon {@link #join}.
1434 *
1435 * @param runnable the runnable action
1436 * @return the task
1437 */
1438 public static ForkJoinTask<?> adapt(Runnable runnable) {
1439 return new AdaptedRunnableAction(runnable);
1440 }
1441
1442 /**
1443 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1444 * method of the given {@code Runnable} as its action, and returns
1445 * the given result upon {@link #join}.
1446 *
1447 * @param runnable the runnable action
1448 * @param result the result upon completion
1449 * @param <T> the type of the result
1450 * @return the task
1451 */
1452 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1453 return new AdaptedRunnable<T>(runnable, result);
1454 }
1455
1456 /**
1457 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1458 * method of the given {@code Callable} as its action, and returns
1459 * its result upon {@link #join}, translating any checked exceptions
1460 * encountered into {@code RuntimeException}.
1461 *
1462 * @param callable the callable action
1463 * @param <T> the type of the callable's result
1464 * @return the task
1465 */
1466 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1467 return new AdaptedCallable<T>(callable);
1468 }
1469
1470 /**
1471 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1472 * method of the given {@code Callable} as its action, and returns
1473 * its result upon {@link #join}, translating any checked exceptions
1474 * encountered into {@code RuntimeException}. Additionally,
1475 * invocations of {@code cancel} with {@code mayInterruptIfRunning
1476 * true} will attempt to interrupt the thread performing the task.
1477 *
1478 * @param callable the callable action
1479 * @param <T> the type of the callable's result
1480 * @return the task
1481 *
1482 * @since 17
1483 */
1484 // adaptInterruptible deferred to its own independent change
1485 // https://bugs.openjdk.java.net/browse/JDK-8246587
1486 /* TODO: public */ private static <T> ForkJoinTask<T> adaptInterruptible(Callable<? extends T> callable) {
1487 return new AdaptedInterruptibleCallable<T>(callable);
1488 }
1489
1490 // Serialization support
1491
1492 private static final long serialVersionUID = -7721805057305804111L;
1493
1494 /**
1495 * Saves this task to a stream (that is, serializes it).
1496 *
1497 * @param s the stream
1498 * @throws java.io.IOException if an I/O error occurs
1499 * @serialData the current run status and the exception thrown
1500 * during execution, or {@code null} if none
1501 */
1502 private void writeObject(java.io.ObjectOutputStream s)
1503 throws java.io.IOException {
1504 Aux a;
1505 s.defaultWriteObject();
1506 s.writeObject((a = aux) == null ? null : a.ex);
1507 }
1508
1509 /**
1510 * Reconstitutes this task from a stream (that is, deserializes it).
1511 * @param s the stream
1512 * @throws ClassNotFoundException if the class of a serialized object
1513 * could not be found
1514 * @throws java.io.IOException if an I/O error occurs
1515 */
1516 private void readObject(java.io.ObjectInputStream s)
1517 throws java.io.IOException, ClassNotFoundException {
1518 s.defaultReadObject();
1519 Object ex = s.readObject();
1520 if (ex != null)
1521 trySetThrown((Throwable)ex);
1522 }
1523
1524 static {
1525 try {
1526 MethodHandles.Lookup l = MethodHandles.lookup();
1527 STATUS = l.findVarHandle(ForkJoinTask.class, "status", int.class);
1528 AUX = l.findVarHandle(ForkJoinTask.class, "aux", Aux.class);
1529 } catch (ReflectiveOperationException e) {
1530 throw new ExceptionInInitializerError(e);
1531 }
1532 }
1533
1534 }