ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.131
Committed: Tue Feb 4 12:38:06 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.130: +14 -9 lines
Log Message:
touchups

File Contents

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