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