ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.110
Committed: Thu Jun 30 14:17:04 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.109: +1 -1 lines
Log Message:
fix typo reported by Ivan Gerasimov

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