ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.126
Committed: Mon Jan 20 15:51:54 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.125: +106 -118 lines
Log Message:
improve compatibilty for timeouts etc; increase common code paths

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