ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.156
Committed: Fri Mar 25 12:29:55 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.155: +4 -1 lines
Log Message:
Compatibility; @since tags

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