ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.155
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.154: +185 -149 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

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