ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.120
Committed: Sun Mar 11 18:00:06 2018 UTC (6 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.119: +1 -1 lines
Log Message:
prefer throwing ExceptionInInitializerError from <clinit> to throwing Error

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