ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.116
Committed: Wed Aug 16 17:18:34 2017 UTC (6 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.115: +9 -0 lines
Log Message:
8186265: Make toString() methods of "task" objects more useful

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