ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.151
Committed: Sat Feb 6 17:33:47 2021 UTC (3 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.150: +82 -36 lines
Log Message:
More async and parallelism-0 improvements

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