ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.111
Committed: Mon Jul 4 23:53:07 2016 UTC (7 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.110: +1 -2 lines
Log Message:
expungeStaleExceptions: very slightly better code

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