ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.158
Committed: Fri May 6 16:03:05 2022 UTC (2 years ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.157: +4 -2 lines
Log Message:
sync with openjdk

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