ForkJoinTask.java revision edf43d27e240d82106f39ae91404963c23987234
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
7package java.util.concurrent;
8
9import java.io.Serializable;
10import java.util.Collection;
11import java.util.List;
12import java.util.RandomAccess;
13import java.lang.ref.WeakReference;
14import java.lang.ref.ReferenceQueue;
15import java.util.concurrent.locks.ReentrantLock;
16import java.lang.reflect.Constructor;
17
18/**
19 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
20 * A {@code ForkJoinTask} is a thread-like entity that is much
21 * lighter weight than a normal thread.  Huge numbers of tasks and
22 * subtasks may be hosted by a small number of actual threads in a
23 * ForkJoinPool, at the price of some usage limitations.
24 *
25 * <p>A "main" {@code ForkJoinTask} begins execution when it is
26 * explicitly submitted to a {@link ForkJoinPool}, or, if not already
27 * engaged in a ForkJoin computation, commenced in the {@code
28 * ForkJoinPool.commonPool()} via {@link #fork}, {@link #invoke}, or
29 * related methods.  Once started, it will usually in turn start other
30 * subtasks.  As indicated by the name of this class, many programs
31 * using {@code ForkJoinTask} employ only methods {@link #fork} and
32 * {@link #join}, or derivatives such as {@link
33 * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
34 * provides a number of other methods that can come into play in
35 * advanced usages, as well as extension mechanics that allow support
36 * of new forms of fork/join processing.
37 *
38 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
39 * The efficiency of {@code ForkJoinTask}s stems from a set of
40 * restrictions (that are only partially statically enforceable)
41 * reflecting their main use as computational tasks calculating pure
42 * functions or operating on purely isolated objects.  The primary
43 * coordination mechanisms are {@link #fork}, that arranges
44 * asynchronous execution, and {@link #join}, that doesn't proceed
45 * until the task's result has been computed.  Computations should
46 * ideally avoid {@code synchronized} methods or blocks, and should
47 * minimize other blocking synchronization apart from joining other
48 * tasks or using synchronizers such as Phasers that are advertised to
49 * cooperate with fork/join scheduling. Subdividable tasks should also
50 * not perform blocking I/O, and should ideally access variables that
51 * are completely independent of those accessed by other running
52 * tasks. These guidelines are loosely enforced by not permitting
53 * checked exceptions such as {@code IOExceptions} to be
54 * thrown. However, computations may still encounter unchecked
55 * exceptions, that are rethrown to callers attempting to join
56 * them. These exceptions may additionally include {@link
57 * RejectedExecutionException} stemming from internal resource
58 * exhaustion, such as failure to allocate internal task
59 * queues. Rethrown exceptions behave in the same way as regular
60 * exceptions, but, when possible, contain stack traces (as displayed
61 * for example using {@code ex.printStackTrace()}) of both the thread
62 * that initiated the computation as well as the thread actually
63 * encountering the exception; minimally only the latter.
64 *
65 * <p>It is possible to define and use ForkJoinTasks that may block,
66 * but doing do requires three further considerations: (1) Completion
67 * of few if any <em>other</em> tasks should be dependent on a task
68 * that blocks on external synchronization or I/O. Event-style async
69 * tasks that are never joined often fall into this category.
70 * (2) To minimize resource impact, tasks should be small; ideally
71 * performing only the (possibly) blocking action. (3) Unless the {@link
72 * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
73 * blocked tasks is known to be less than the pool's {@link
74 * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
75 * enough threads will be available to ensure progress or good
76 * performance.
77 *
78 * <p>The primary method for awaiting completion and extracting
79 * results of a task is {@link #join}, but there are several variants:
80 * The {@link Future#get} methods support interruptible and/or timed
81 * waits for completion and report results using {@code Future}
82 * conventions. Method {@link #invoke} is semantically
83 * equivalent to {@code fork(); join()} but always attempts to begin
84 * execution in the current thread. The "<em>quiet</em>" forms of
85 * these methods do not extract results or report exceptions. These
86 * may be useful when a set of tasks are being executed, and you need
87 * to delay processing of results or exceptions until all complete.
88 * Method {@code invokeAll} (available in multiple versions)
89 * performs the most common form of parallel invocation: forking a set
90 * of tasks and joining them all.
91 *
92 * <p>In the most typical usages, a fork-join pair act like a call
93 * (fork) and return (join) from a parallel recursive function. As is
94 * the case with other forms of recursive calls, returns (joins)
95 * should be performed innermost-first. For example, {@code a.fork();
96 * b.fork(); b.join(); a.join();} is likely to be substantially more
97 * efficient than joining {@code a} before {@code b}.
98 *
99 * <p>The execution status of tasks may be queried at several levels
100 * of detail: {@link #isDone} is true if a task completed in any way
101 * (including the case where a task was cancelled without executing);
102 * {@link #isCompletedNormally} is true if a task completed without
103 * cancellation or encountering an exception; {@link #isCancelled} is
104 * true if the task was cancelled (in which case {@link #getException}
105 * returns a {@link java.util.concurrent.CancellationException}); and
106 * {@link #isCompletedAbnormally} is true if a task was either
107 * cancelled or encountered an exception, in which case {@link
108 * #getException} will return either the encountered exception or
109 * {@link java.util.concurrent.CancellationException}.
110 *
111 * <p>The ForkJoinTask class is not usually directly subclassed.
112 * Instead, you subclass one of the abstract classes that support a
113 * particular style of fork/join processing, typically {@link
114 * RecursiveAction} for most computations that do not return results
115 * and {@link RecursiveTask} for those that do. Normally, a concrete
116 * ForkJoinTask subclass declares fields comprising its parameters,
117 * established in a constructor, and then defines a {@code compute}
118 * method that somehow uses the control methods supplied by this base class.
119 *
120 * <p>Method {@link #join} and its variants are appropriate for use
121 * only when completion dependencies are acyclic; that is, the
122 * parallel computation can be described as a directed acyclic graph
123 * (DAG). Otherwise, executions may encounter a form of deadlock as
124 * tasks cyclically wait for each other.  However, this framework
125 * supports other methods and techniques (for example the use of
126 * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
127 * may be of use in constructing custom subclasses for problems that
128 * are not statically structured as DAGs. To support such usages, a
129 * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
130 * value using {@code setForkJoinTaskTag} or {@code
131 * compareAndSetForkJoinTaskTag} and checked using {@code
132 * getForkJoinTaskTag}. The ForkJoinTask implementation does not use
133 * these {@code protected} methods or tags for any purpose, but they
134 * may be of use in the construction of specialized subclasses.  For
135 * example, parallel graph traversals can use the supplied methods to
136 * avoid revisiting nodes/tasks that have already been processed.
137 * (Method names for tagging are bulky in part to encourage definition
138 * of methods that reflect their usage patterns.)
139 *
140 * <p>Most base support methods are {@code final}, to prevent
141 * overriding of implementations that are intrinsically tied to the
142 * underlying lightweight task scheduling framework.  Developers
143 * creating new basic styles of fork/join processing should minimally
144 * implement {@code protected} methods {@link #exec}, {@link
145 * #setRawResult}, and {@link #getRawResult}, while also introducing
146 * an abstract computational method that can be implemented in its
147 * subclasses, possibly relying on other {@code protected} methods
148 * provided by this class.
149 *
150 * <p>ForkJoinTasks should perform relatively small amounts of
151 * computation. Large tasks should be split into smaller subtasks,
152 * usually via recursive decomposition. As a very rough rule of thumb,
153 * a task should perform more than 100 and less than 10000 basic
154 * computational steps, and should avoid indefinite looping. If tasks
155 * are too big, then parallelism cannot improve throughput. If too
156 * small, then memory and internal task maintenance overhead may
157 * overwhelm processing.
158 *
159 * <p>This class provides {@code adapt} methods for {@link Runnable}
160 * and {@link Callable}, that may be of use when mixing execution of
161 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
162 * of this form, consider using a pool constructed in <em>asyncMode</em>.
163 *
164 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
165 * used in extensions such as remote execution frameworks. It is
166 * sensible to serialize tasks only before or after, but not during,
167 * execution. Serialization is not relied on during execution itself.
168 *
169 * @since 1.7
170 * @author Doug Lea
171 */
172// android-note: Removed references to hidden apis commonPool, CountedCompleter
173// etc.
174public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
175
176    /*
177     * See the internal documentation of class ForkJoinPool for a
178     * general implementation overview.  ForkJoinTasks are mainly
179     * responsible for maintaining their "status" field amidst relays
180     * to methods in ForkJoinWorkerThread and ForkJoinPool.
181     *
182     * The methods of this class are more-or-less layered into
183     * (1) basic status maintenance
184     * (2) execution and awaiting completion
185     * (3) user-level methods that additionally report results.
186     * This is sometimes hard to see because this file orders exported
187     * methods in a way that flows well in javadocs.
188     */
189
190    /*
191     * The status field holds run control status bits packed into a
192     * single int to minimize footprint and to ensure atomicity (via
193     * CAS).  Status is initially zero, and takes on nonnegative
194     * values until completed, upon which status (anded with
195     * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks
196     * undergoing blocking waits by other threads have the SIGNAL bit
197     * set.  Completion of a stolen task with SIGNAL set awakens any
198     * waiters via notifyAll. Even though suboptimal for some
199     * purposes, we use basic builtin wait/notify to take advantage of
200     * "monitor inflation" in JVMs that we would otherwise need to
201     * emulate to avoid adding further per-task bookkeeping overhead.
202     * We want these monitors to be "fat", i.e., not use biasing or
203     * thin-lock techniques, so use some odd coding idioms that tend
204     * to avoid them, mainly by arranging that every synchronized
205     * block performs a wait, notifyAll or both.
206     *
207     * These control bits occupy only (some of) the upper half (16
208     * bits) of status field. The lower bits are used for user-defined
209     * tags.
210     */
211
212    /** The run status of this task */
213    volatile int status; // accessed directly by pool and workers
214    static final int DONE_MASK   = 0xf0000000;  // mask out non-completion bits
215    static final int NORMAL      = 0xf0000000;  // must be negative
216    static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
217    static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
218    static final int SIGNAL      = 0x00010000;  // must be >= 1 << 16
219    static final int SMASK       = 0x0000ffff;  // short bits for tags
220
221    /**
222     * Marks completion and wakes up threads waiting to join this
223     * task.
224     *
225     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
226     * @return completion status on exit
227     */
228    private int setCompletion(int completion) {
229        for (int s;;) {
230            if ((s = status) < 0)
231                return s;
232            if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
233                if ((s >>> 16) != 0)
234                    synchronized (this) { notifyAll(); }
235                return completion;
236            }
237        }
238    }
239
240    /**
241     * Primary execution method for stolen tasks. Unless done, calls
242     * exec and records status if completed, but doesn't wait for
243     * completion otherwise.
244     *
245     * @return status on exit from this method
246     */
247    final int doExec() {
248        int s; boolean completed;
249        if ((s = status) >= 0) {
250            try {
251                completed = exec();
252            } catch (Throwable rex) {
253                return setExceptionalCompletion(rex);
254            }
255            if (completed)
256                s = setCompletion(NORMAL);
257        }
258        return s;
259    }
260
261    /**
262     * Tries to set SIGNAL status unless already completed. Used by
263     * ForkJoinPool. Other variants are directly incorporated into
264     * externalAwaitDone etc.
265     *
266     * @return true if successful
267     */
268    final boolean trySetSignal() {
269        int s = status;
270        return s >= 0 && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL);
271    }
272
273    /**
274     * Blocks a non-worker-thread until completion.
275     * @return status upon completion
276     */
277    private int externalAwaitDone() {
278        int s;
279        ForkJoinPool cp = ForkJoinPool.common;
280        if ((s = status) >= 0) {
281            if (cp != null) {
282                if (this instanceof CountedCompleter)
283                    s = cp.externalHelpComplete((CountedCompleter<?>)this);
284                else if (cp.tryExternalUnpush(this))
285                    s = doExec();
286            }
287            if (s >= 0 && (s = status) >= 0) {
288                boolean interrupted = false;
289                do {
290                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
291                        synchronized (this) {
292                            if (status >= 0) {
293                                try {
294                                    wait();
295                                } catch (InterruptedException ie) {
296                                    interrupted = true;
297                                }
298                            }
299                            else
300                                notifyAll();
301                        }
302                    }
303                } while ((s = status) >= 0);
304                if (interrupted)
305                    Thread.currentThread().interrupt();
306            }
307        }
308        return s;
309    }
310
311    /**
312     * Blocks a non-worker-thread until completion or interruption.
313     */
314    private int externalInterruptibleAwaitDone() throws InterruptedException {
315        int s;
316        ForkJoinPool cp = ForkJoinPool.common;
317        if (Thread.interrupted())
318            throw new InterruptedException();
319        if ((s = status) >= 0 && cp != null) {
320            if (this instanceof CountedCompleter)
321                cp.externalHelpComplete((CountedCompleter<?>)this);
322            else if (cp.tryExternalUnpush(this))
323                doExec();
324        }
325        while ((s = status) >= 0) {
326            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
327                synchronized (this) {
328                    if (status >= 0)
329                        wait();
330                    else
331                        notifyAll();
332                }
333            }
334        }
335        return s;
336    }
337
338    /**
339     * Implementation for join, get, quietlyJoin. Directly handles
340     * only cases of already-completed, external wait, and
341     * unfork+exec.  Others are relayed to ForkJoinPool.awaitJoin.
342     *
343     * @return status upon completion
344     */
345    private int doJoin() {
346        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
347        return (s = status) < 0 ? s :
348            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
349            (w = (wt = (ForkJoinWorkerThread)t).workQueue).
350            tryUnpush(this) && (s = doExec()) < 0 ? s :
351            wt.pool.awaitJoin(w, this) :
352            externalAwaitDone();
353    }
354
355    /**
356     * Implementation for invoke, quietlyInvoke.
357     *
358     * @return status upon completion
359     */
360    private int doInvoke() {
361        int s; Thread t; ForkJoinWorkerThread wt;
362        return (s = doExec()) < 0 ? s :
363            ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
364            (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, this) :
365            externalAwaitDone();
366    }
367
368    // Exception table support
369
370    /**
371     * Table of exceptions thrown by tasks, to enable reporting by
372     * callers. Because exceptions are rare, we don't directly keep
373     * them with task objects, but instead use a weak ref table.  Note
374     * that cancellation exceptions don't appear in the table, but are
375     * instead recorded as status values.
376     *
377     * Note: These statics are initialized below in static block.
378     */
379    private static final ExceptionNode[] exceptionTable;
380    private static final ReentrantLock exceptionTableLock;
381    private static final ReferenceQueue<Object> exceptionTableRefQueue;
382
383    /**
384     * Fixed capacity for exceptionTable.
385     */
386    private static final int EXCEPTION_MAP_CAPACITY = 32;
387
388    /**
389     * Key-value nodes for exception table.  The chained hash table
390     * uses identity comparisons, full locking, and weak references
391     * for keys. The table has a fixed capacity because it only
392     * maintains task exceptions long enough for joiners to access
393     * them, so should never become very large for sustained
394     * periods. However, since we do not know when the last joiner
395     * completes, we must use weak references and expunge them. We do
396     * so on each operation (hence full locking). Also, some thread in
397     * any ForkJoinPool will call helpExpungeStaleExceptions when its
398     * pool becomes isQuiescent.
399     */
400    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
401        final Throwable ex;
402        ExceptionNode next;
403        final long thrower;  // use id not ref to avoid weak cycles
404        final int hashCode;  // store task hashCode before weak ref disappears
405        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
406            super(task, exceptionTableRefQueue);
407            this.ex = ex;
408            this.next = next;
409            this.thrower = Thread.currentThread().getId();
410            this.hashCode = System.identityHashCode(task);
411        }
412    }
413
414    /**
415     * Records exception and sets status.
416     *
417     * @return status on exit
418     */
419    final int recordExceptionalCompletion(Throwable ex) {
420        int s;
421        if ((s = status) >= 0) {
422            int h = System.identityHashCode(this);
423            final ReentrantLock lock = exceptionTableLock;
424            lock.lock();
425            try {
426                expungeStaleExceptions();
427                ExceptionNode[] t = exceptionTable;
428                int i = h & (t.length - 1);
429                for (ExceptionNode e = t[i]; ; e = e.next) {
430                    if (e == null) {
431                        t[i] = new ExceptionNode(this, ex, t[i]);
432                        break;
433                    }
434                    if (e.get() == this) // already present
435                        break;
436                }
437            } finally {
438                lock.unlock();
439            }
440            s = setCompletion(EXCEPTIONAL);
441        }
442        return s;
443    }
444
445    /**
446     * Records exception and possibly propagates.
447     *
448     * @return status on exit
449     */
450    private int setExceptionalCompletion(Throwable ex) {
451        int s = recordExceptionalCompletion(ex);
452        if ((s & DONE_MASK) == EXCEPTIONAL)
453            internalPropagateException(ex);
454        return s;
455    }
456
457    /**
458     * Hook for exception propagation support for tasks with completers.
459     */
460    void internalPropagateException(Throwable ex) {
461    }
462
463    /**
464     * Cancels, ignoring any exceptions thrown by cancel. Used during
465     * worker and pool shutdown. Cancel is spec'ed not to throw any
466     * exceptions, but if it does anyway, we have no recourse during
467     * shutdown, so guard against this case.
468     */
469    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
470        if (t != null && t.status >= 0) {
471            try {
472                t.cancel(false);
473            } catch (Throwable ignore) {
474            }
475        }
476    }
477
478    /**
479     * Removes exception node and clears status.
480     */
481    private void clearExceptionalCompletion() {
482        int h = System.identityHashCode(this);
483        final ReentrantLock lock = exceptionTableLock;
484        lock.lock();
485        try {
486            ExceptionNode[] t = exceptionTable;
487            int i = h & (t.length - 1);
488            ExceptionNode e = t[i];
489            ExceptionNode pred = null;
490            while (e != null) {
491                ExceptionNode next = e.next;
492                if (e.get() == this) {
493                    if (pred == null)
494                        t[i] = next;
495                    else
496                        pred.next = next;
497                    break;
498                }
499                pred = e;
500                e = next;
501            }
502            expungeStaleExceptions();
503            status = 0;
504        } finally {
505            lock.unlock();
506        }
507    }
508
509    /**
510     * Returns a rethrowable exception for the given task, if
511     * available. To provide accurate stack traces, if the exception
512     * was not thrown by the current thread, we try to create a new
513     * exception of the same type as the one thrown, but with the
514     * recorded exception as its cause. If there is no such
515     * constructor, we instead try to use a no-arg constructor,
516     * followed by initCause, to the same effect. If none of these
517     * apply, or any fail due to other exceptions, we return the
518     * recorded exception, which is still correct, although it may
519     * contain a misleading stack trace.
520     *
521     * @return the exception, or null if none
522     */
523    private Throwable getThrowableException() {
524        if ((status & DONE_MASK) != EXCEPTIONAL)
525            return null;
526        int h = System.identityHashCode(this);
527        ExceptionNode e;
528        final ReentrantLock lock = exceptionTableLock;
529        lock.lock();
530        try {
531            expungeStaleExceptions();
532            ExceptionNode[] t = exceptionTable;
533            e = t[h & (t.length - 1)];
534            while (e != null && e.get() != this)
535                e = e.next;
536        } finally {
537            lock.unlock();
538        }
539        Throwable ex;
540        if (e == null || (ex = e.ex) == null)
541            return null;
542        if (false && e.thrower != Thread.currentThread().getId()) {
543            Class<? extends Throwable> ec = ex.getClass();
544            try {
545                Constructor<?> noArgCtor = null;
546                Constructor<?>[] cs = ec.getConstructors();// public ctors only
547                for (int i = 0; i < cs.length; ++i) {
548                    Constructor<?> c = cs[i];
549                    Class<?>[] ps = c.getParameterTypes();
550                    if (ps.length == 0)
551                        noArgCtor = c;
552                    else if (ps.length == 1 && ps[0] == Throwable.class)
553                        return (Throwable)(c.newInstance(ex));
554                }
555                if (noArgCtor != null) {
556                    Throwable wx = (Throwable)(noArgCtor.newInstance());
557                    wx.initCause(ex);
558                    return wx;
559                }
560            } catch (Exception ignore) {
561            }
562        }
563        return ex;
564    }
565
566    /**
567     * Poll stale refs and remove them. Call only while holding lock.
568     */
569    private static void expungeStaleExceptions() {
570        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
571            if (x instanceof ExceptionNode) {
572                int hashCode = ((ExceptionNode)x).hashCode;
573                ExceptionNode[] t = exceptionTable;
574                int i = hashCode & (t.length - 1);
575                ExceptionNode e = t[i];
576                ExceptionNode pred = null;
577                while (e != null) {
578                    ExceptionNode next = e.next;
579                    if (e == x) {
580                        if (pred == null)
581                            t[i] = next;
582                        else
583                            pred.next = next;
584                        break;
585                    }
586                    pred = e;
587                    e = next;
588                }
589            }
590        }
591    }
592
593    /**
594     * If lock is available, poll stale refs and remove them.
595     * Called from ForkJoinPool when pools become quiescent.
596     */
597    static final void helpExpungeStaleExceptions() {
598        final ReentrantLock lock = exceptionTableLock;
599        if (lock.tryLock()) {
600            try {
601                expungeStaleExceptions();
602            } finally {
603                lock.unlock();
604            }
605        }
606    }
607
608    /**
609     * A version of "sneaky throw" to relay exceptions
610     */
611    static void rethrow(Throwable ex) {
612        if (ex != null)
613            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
614    }
615
616    /**
617     * The sneaky part of sneaky throw, relying on generics
618     * limitations to evade compiler complaints about rethrowing
619     * unchecked exceptions
620     */
621    @SuppressWarnings("unchecked") static <T extends Throwable>
622        void uncheckedThrow(Throwable t) throws T {
623        throw (T)t; // rely on vacuous cast
624    }
625
626    /**
627     * Throws exception, if any, associated with the given status.
628     */
629    private void reportException(int s) {
630        if (s == CANCELLED)
631            throw new CancellationException();
632        if (s == EXCEPTIONAL)
633            rethrow(getThrowableException());
634    }
635
636    // public methods
637
638    /**
639     * Arranges to asynchronously execute this task in the pool the
640     * current task is running in, if applicable, or using the {@code
641     * ForkJoinPool.commonPool()} if not {@link #inForkJoinPool}.  While
642     * it is not necessarily enforced, it is a usage error to fork a
643     * task more than once unless it has completed and been
644     * reinitialized.  Subsequent modifications to the state of this
645     * task or any data it operates on are not necessarily
646     * consistently observable by any thread other than the one
647     * executing it unless preceded by a call to {@link #join} or
648     * related methods, or a call to {@link #isDone} returning {@code
649     * true}.
650     *
651     * @return {@code this}, to simplify usage
652     */
653    public final ForkJoinTask<V> fork() {
654        Thread t;
655        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
656            ((ForkJoinWorkerThread)t).workQueue.push(this);
657        else
658            ForkJoinPool.common.externalPush(this);
659        return this;
660    }
661
662    /**
663     * Returns the result of the computation when it {@link #isDone is
664     * done}.  This method differs from {@link #get()} in that
665     * abnormal completion results in {@code RuntimeException} or
666     * {@code Error}, not {@code ExecutionException}, and that
667     * interrupts of the calling thread do <em>not</em> cause the
668     * method to abruptly return by throwing {@code
669     * InterruptedException}.
670     *
671     * @return the computed result
672     */
673    public final V join() {
674        int s;
675        if ((s = doJoin() & DONE_MASK) != NORMAL)
676            reportException(s);
677        return getRawResult();
678    }
679
680    /**
681     * Commences performing this task, awaits its completion if
682     * necessary, and returns its result, or throws an (unchecked)
683     * {@code RuntimeException} or {@code Error} if the underlying
684     * computation did so.
685     *
686     * @return the computed result
687     */
688    public final V invoke() {
689        int s;
690        if ((s = doInvoke() & DONE_MASK) != NORMAL)
691            reportException(s);
692        return getRawResult();
693    }
694
695    /**
696     * Forks the given tasks, returning when {@code isDone} holds for
697     * each task or an (unchecked) exception is encountered, in which
698     * case the exception is rethrown. If more than one task
699     * encounters an exception, then this method throws any one of
700     * these exceptions. If any task encounters an exception, the
701     * other may be cancelled. However, the execution status of
702     * individual tasks is not guaranteed upon exceptional return. The
703     * status of each task may be obtained using {@link
704     * #getException()} and related methods to check if they have been
705     * cancelled, completed normally or exceptionally, or left
706     * unprocessed.
707     *
708     * @param t1 the first task
709     * @param t2 the second task
710     * @throws NullPointerException if any task is null
711     */
712    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
713        int s1, s2;
714        t2.fork();
715        if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL)
716            t1.reportException(s1);
717        if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL)
718            t2.reportException(s2);
719    }
720
721    /**
722     * Forks the given tasks, returning when {@code isDone} holds for
723     * each task or an (unchecked) exception is encountered, in which
724     * case the exception is rethrown. If more than one task
725     * encounters an exception, then this method throws any one of
726     * these exceptions. If any task encounters an exception, others
727     * may be cancelled. However, the execution status of individual
728     * tasks is not guaranteed upon exceptional return. The status of
729     * each task may be obtained using {@link #getException()} and
730     * related methods to check if they have been cancelled, completed
731     * normally or exceptionally, or left unprocessed.
732     *
733     * @param tasks the tasks
734     * @throws NullPointerException if any task is null
735     */
736    public static void invokeAll(ForkJoinTask<?>... tasks) {
737        Throwable ex = null;
738        int last = tasks.length - 1;
739        for (int i = last; i >= 0; --i) {
740            ForkJoinTask<?> t = tasks[i];
741            if (t == null) {
742                if (ex == null)
743                    ex = new NullPointerException();
744            }
745            else if (i != 0)
746                t.fork();
747            else if (t.doInvoke() < NORMAL && ex == null)
748                ex = t.getException();
749        }
750        for (int i = 1; i <= last; ++i) {
751            ForkJoinTask<?> t = tasks[i];
752            if (t != null) {
753                if (ex != null)
754                    t.cancel(false);
755                else if (t.doJoin() < NORMAL)
756                    ex = t.getException();
757            }
758        }
759        if (ex != null)
760            rethrow(ex);
761    }
762
763    /**
764     * Forks all tasks in the specified collection, returning when
765     * {@code isDone} holds for each task or an (unchecked) exception
766     * is encountered, in which case the exception is rethrown. If
767     * more than one task encounters an exception, then this method
768     * throws any one of these exceptions. If any task encounters an
769     * exception, others may be cancelled. However, the execution
770     * status of individual tasks is not guaranteed upon exceptional
771     * return. The status of each task may be obtained using {@link
772     * #getException()} and related methods to check if they have been
773     * cancelled, completed normally or exceptionally, or left
774     * unprocessed.
775     *
776     * @param tasks the collection of tasks
777     * @return the tasks argument, to simplify usage
778     * @throws NullPointerException if tasks or any element are null
779     */
780    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
781        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
782            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
783            return tasks;
784        }
785        @SuppressWarnings("unchecked")
786        List<? extends ForkJoinTask<?>> ts =
787            (List<? extends ForkJoinTask<?>>) tasks;
788        Throwable ex = null;
789        int last = ts.size() - 1;
790        for (int i = last; i >= 0; --i) {
791            ForkJoinTask<?> t = ts.get(i);
792            if (t == null) {
793                if (ex == null)
794                    ex = new NullPointerException();
795            }
796            else if (i != 0)
797                t.fork();
798            else if (t.doInvoke() < NORMAL && ex == null)
799                ex = t.getException();
800        }
801        for (int i = 1; i <= last; ++i) {
802            ForkJoinTask<?> t = ts.get(i);
803            if (t != null) {
804                if (ex != null)
805                    t.cancel(false);
806                else if (t.doJoin() < NORMAL)
807                    ex = t.getException();
808            }
809        }
810        if (ex != null)
811            rethrow(ex);
812        return tasks;
813    }
814
815    /**
816     * Attempts to cancel execution of this task. This attempt will
817     * fail if the task has already completed or could not be
818     * cancelled for some other reason. If successful, and this task
819     * has not started when {@code cancel} is called, execution of
820     * this task is suppressed. After this method returns
821     * successfully, unless there is an intervening call to {@link
822     * #reinitialize}, subsequent calls to {@link #isCancelled},
823     * {@link #isDone}, and {@code cancel} will return {@code true}
824     * and calls to {@link #join} and related methods will result in
825     * {@code CancellationException}.
826     *
827     * <p>This method may be overridden in subclasses, but if so, must
828     * still ensure that these properties hold. In particular, the
829     * {@code cancel} method itself must not throw exceptions.
830     *
831     * <p>This method is designed to be invoked by <em>other</em>
832     * tasks. To terminate the current task, you can just return or
833     * throw an unchecked exception from its computation method, or
834     * invoke {@link #completeExceptionally(Throwable)}.
835     *
836     * @param mayInterruptIfRunning this value has no effect in the
837     * default implementation because interrupts are not used to
838     * control cancellation.
839     *
840     * @return {@code true} if this task is now cancelled
841     */
842    public boolean cancel(boolean mayInterruptIfRunning) {
843        return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED;
844    }
845
846    public final boolean isDone() {
847        return status < 0;
848    }
849
850    public final boolean isCancelled() {
851        return (status & DONE_MASK) == CANCELLED;
852    }
853
854    /**
855     * Returns {@code true} if this task threw an exception or was cancelled.
856     *
857     * @return {@code true} if this task threw an exception or was cancelled
858     */
859    public final boolean isCompletedAbnormally() {
860        return status < NORMAL;
861    }
862
863    /**
864     * Returns {@code true} if this task completed without throwing an
865     * exception and was not cancelled.
866     *
867     * @return {@code true} if this task completed without throwing an
868     * exception and was not cancelled
869     */
870    public final boolean isCompletedNormally() {
871        return (status & DONE_MASK) == NORMAL;
872    }
873
874    /**
875     * Returns the exception thrown by the base computation, or a
876     * {@code CancellationException} if cancelled, or {@code null} if
877     * none or if the method has not yet completed.
878     *
879     * @return the exception, or {@code null} if none
880     */
881    public final Throwable getException() {
882        int s = status & DONE_MASK;
883        return ((s >= NORMAL)    ? null :
884                (s == CANCELLED) ? new CancellationException() :
885                getThrowableException());
886    }
887
888    /**
889     * Completes this task abnormally, and if not already aborted or
890     * cancelled, causes it to throw the given exception upon
891     * {@code join} and related operations. This method may be used
892     * to induce exceptions in asynchronous tasks, or to force
893     * completion of tasks that would not otherwise complete.  Its use
894     * in other situations is discouraged.  This method is
895     * overridable, but overridden versions must invoke {@code super}
896     * implementation to maintain guarantees.
897     *
898     * @param ex the exception to throw. If this exception is not a
899     * {@code RuntimeException} or {@code Error}, the actual exception
900     * thrown will be a {@code RuntimeException} with cause {@code ex}.
901     */
902    public void completeExceptionally(Throwable ex) {
903        setExceptionalCompletion((ex instanceof RuntimeException) ||
904                                 (ex instanceof Error) ? ex :
905                                 new RuntimeException(ex));
906    }
907
908    /**
909     * Completes this task, and if not already aborted or cancelled,
910     * returning the given value as the result of subsequent
911     * invocations of {@code join} and related operations. This method
912     * may be used to provide results for asynchronous tasks, or to
913     * provide alternative handling for tasks that would not otherwise
914     * complete normally. Its use in other situations is
915     * discouraged. This method is overridable, but overridden
916     * versions must invoke {@code super} implementation to maintain
917     * guarantees.
918     *
919     * @param value the result value for this task
920     */
921    public void complete(V value) {
922        try {
923            setRawResult(value);
924        } catch (Throwable rex) {
925            setExceptionalCompletion(rex);
926            return;
927        }
928        setCompletion(NORMAL);
929    }
930
931    /**
932     * Completes this task normally without setting a value. The most
933     * recent value established by {@link #setRawResult} (or {@code
934     * null} by default) will be returned as the result of subsequent
935     * invocations of {@code join} and related operations.
936     *
937     * @since 1.8
938     * @hide
939     */
940    public final void quietlyComplete() {
941        setCompletion(NORMAL);
942    }
943
944    /**
945     * Waits if necessary for the computation to complete, and then
946     * retrieves its result.
947     *
948     * @return the computed result
949     * @throws CancellationException if the computation was cancelled
950     * @throws ExecutionException if the computation threw an
951     * exception
952     * @throws InterruptedException if the current thread is not a
953     * member of a ForkJoinPool and was interrupted while waiting
954     */
955    public final V get() throws InterruptedException, ExecutionException {
956        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
957            doJoin() : externalInterruptibleAwaitDone();
958        Throwable ex;
959        if ((s &= DONE_MASK) == CANCELLED)
960            throw new CancellationException();
961        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
962            throw new ExecutionException(ex);
963        return getRawResult();
964    }
965
966    /**
967     * Waits if necessary for at most the given time for the computation
968     * to complete, and then retrieves its result, if available.
969     *
970     * @param timeout the maximum time to wait
971     * @param unit the time unit of the timeout argument
972     * @return the computed result
973     * @throws CancellationException if the computation was cancelled
974     * @throws ExecutionException if the computation threw an
975     * exception
976     * @throws InterruptedException if the current thread is not a
977     * member of a ForkJoinPool and was interrupted while waiting
978     * @throws TimeoutException if the wait timed out
979     */
980    public final V get(long timeout, TimeUnit unit)
981        throws InterruptedException, ExecutionException, TimeoutException {
982        if (Thread.interrupted())
983            throw new InterruptedException();
984        // Messy in part because we measure in nanosecs, but wait in millisecs
985        int s; long ms;
986        long ns = unit.toNanos(timeout);
987        ForkJoinPool cp;
988        if ((s = status) >= 0 && ns > 0L) {
989            long deadline = System.nanoTime() + ns;
990            ForkJoinPool p = null;
991            ForkJoinPool.WorkQueue w = null;
992            Thread t = Thread.currentThread();
993            if (t instanceof ForkJoinWorkerThread) {
994                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
995                p = wt.pool;
996                w = wt.workQueue;
997                p.helpJoinOnce(w, this); // no retries on failure
998            }
999            else if ((cp = ForkJoinPool.common) != null) {
1000                if (this instanceof CountedCompleter)
1001                    cp.externalHelpComplete((CountedCompleter<?>)this);
1002                else if (cp.tryExternalUnpush(this))
1003                    doExec();
1004            }
1005            boolean canBlock = false;
1006            boolean interrupted = false;
1007            try {
1008                while ((s = status) >= 0) {
1009                    if (w != null && w.qlock < 0)
1010                        cancelIgnoringExceptions(this);
1011                    else if (!canBlock) {
1012                        if (p == null || p.tryCompensate(p.ctl))
1013                            canBlock = true;
1014                    }
1015                    else {
1016                        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
1017                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
1018                            synchronized (this) {
1019                                if (status >= 0) {
1020                                    try {
1021                                        wait(ms);
1022                                    } catch (InterruptedException ie) {
1023                                        if (p == null)
1024                                            interrupted = true;
1025                                    }
1026                                }
1027                                else
1028                                    notifyAll();
1029                            }
1030                        }
1031                        if ((s = status) < 0 || interrupted ||
1032                            (ns = deadline - System.nanoTime()) <= 0L)
1033                            break;
1034                    }
1035                }
1036            } finally {
1037                if (p != null && canBlock)
1038                    p.incrementActiveCount();
1039            }
1040            if (interrupted)
1041                throw new InterruptedException();
1042        }
1043        if ((s &= DONE_MASK) != NORMAL) {
1044            Throwable ex;
1045            if (s == CANCELLED)
1046                throw new CancellationException();
1047            if (s != EXCEPTIONAL)
1048                throw new TimeoutException();
1049            if ((ex = getThrowableException()) != null)
1050                throw new ExecutionException(ex);
1051        }
1052        return getRawResult();
1053    }
1054
1055    /**
1056     * Joins this task, without returning its result or throwing its
1057     * exception. This method may be useful when processing
1058     * collections of tasks when some have been cancelled or otherwise
1059     * known to have aborted.
1060     */
1061    public final void quietlyJoin() {
1062        doJoin();
1063    }
1064
1065    /**
1066     * Commences performing this task and awaits its completion if
1067     * necessary, without returning its result or throwing its
1068     * exception.
1069     */
1070    public final void quietlyInvoke() {
1071        doInvoke();
1072    }
1073
1074    /**
1075     * Possibly executes tasks until the pool hosting the current task
1076     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
1077     * be of use in designs in which many tasks are forked, but none
1078     * are explicitly joined, instead executing them until all are
1079     * processed.
1080     */
1081    public static void helpQuiesce() {
1082        Thread t;
1083        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
1084            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
1085            wt.pool.helpQuiescePool(wt.workQueue);
1086        }
1087        else
1088            ForkJoinPool.quiesceCommonPool();
1089    }
1090
1091    /**
1092     * Resets the internal bookkeeping state of this task, allowing a
1093     * subsequent {@code fork}. This method allows repeated reuse of
1094     * this task, but only if reuse occurs when this task has either
1095     * never been forked, or has been forked, then completed and all
1096     * outstanding joins of this task have also completed. Effects
1097     * under any other usage conditions are not guaranteed.
1098     * This method may be useful when executing
1099     * pre-constructed trees of subtasks in loops.
1100     *
1101     * <p>Upon completion of this method, {@code isDone()} reports
1102     * {@code false}, and {@code getException()} reports {@code
1103     * null}. However, the value returned by {@code getRawResult} is
1104     * unaffected. To clear this value, you can invoke {@code
1105     * setRawResult(null)}.
1106     */
1107    public void reinitialize() {
1108        if ((status & DONE_MASK) == EXCEPTIONAL)
1109            clearExceptionalCompletion();
1110        else
1111            status = 0;
1112    }
1113
1114    /**
1115     * Returns the pool hosting the current task execution, or null
1116     * if this task is executing outside of any ForkJoinPool.
1117     *
1118     * @see #inForkJoinPool
1119     * @return the pool, or {@code null} if none
1120     */
1121    public static ForkJoinPool getPool() {
1122        Thread t = Thread.currentThread();
1123        return (t instanceof ForkJoinWorkerThread) ?
1124            ((ForkJoinWorkerThread) t).pool : null;
1125    }
1126
1127    /**
1128     * Returns {@code true} if the current thread is a {@link
1129     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1130     *
1131     * @return {@code true} if the current thread is a {@link
1132     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1133     * or {@code false} otherwise
1134     */
1135    public static boolean inForkJoinPool() {
1136        return Thread.currentThread() instanceof ForkJoinWorkerThread;
1137    }
1138
1139    /**
1140     * Tries to unschedule this task for execution. This method will
1141     * typically (but is not guaranteed to) succeed if this task is
1142     * the most recently forked task by the current thread, and has
1143     * not commenced executing in another thread.  This method may be
1144     * useful when arranging alternative local processing of tasks
1145     * that could have been, but were not, stolen.
1146     *
1147     * @return {@code true} if unforked
1148     */
1149    public boolean tryUnfork() {
1150        Thread t;
1151        return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1152                ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
1153                ForkJoinPool.common.tryExternalUnpush(this));
1154    }
1155
1156    /**
1157     * Returns an estimate of the number of tasks that have been
1158     * forked by the current worker thread but not yet executed. This
1159     * value may be useful for heuristic decisions about whether to
1160     * fork other tasks.
1161     *
1162     * @return the number of tasks
1163     */
1164    public static int getQueuedTaskCount() {
1165        Thread t; ForkJoinPool.WorkQueue q;
1166        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1167            q = ((ForkJoinWorkerThread)t).workQueue;
1168        else
1169            q = ForkJoinPool.commonSubmitterQueue();
1170        return (q == null) ? 0 : q.queueSize();
1171    }
1172
1173    /**
1174     * Returns an estimate of how many more locally queued tasks are
1175     * held by the current worker thread than there are other worker
1176     * threads that might steal them, or zero if this thread is not
1177     * operating in a ForkJoinPool. This value may be useful for
1178     * heuristic decisions about whether to fork other tasks. In many
1179     * usages of ForkJoinTasks, at steady state, each worker should
1180     * aim to maintain a small constant surplus (for example, 3) of
1181     * tasks, and to process computations locally if this threshold is
1182     * exceeded.
1183     *
1184     * @return the surplus number of tasks, which may be negative
1185     */
1186    public static int getSurplusQueuedTaskCount() {
1187        return ForkJoinPool.getSurplusQueuedTaskCount();
1188    }
1189
1190    // Extension methods
1191
1192    /**
1193     * Returns the result that would be returned by {@link #join}, even
1194     * if this task completed abnormally, or {@code null} if this task
1195     * is not known to have been completed.  This method is designed
1196     * to aid debugging, as well as to support extensions. Its use in
1197     * any other context is discouraged.
1198     *
1199     * @return the result, or {@code null} if not completed
1200     */
1201    public abstract V getRawResult();
1202
1203    /**
1204     * Forces the given value to be returned as a result.  This method
1205     * is designed to support extensions, and should not in general be
1206     * called otherwise.
1207     *
1208     * @param value the value
1209     */
1210    protected abstract void setRawResult(V value);
1211
1212    /**
1213     * Immediately performs the base action of this task and returns
1214     * true if, upon return from this method, this task is guaranteed
1215     * to have completed normally. This method may return false
1216     * otherwise, to indicate that this task is not necessarily
1217     * complete (or is not known to be complete), for example in
1218     * asynchronous actions that require explicit invocations of
1219     * completion methods. This method may also throw an (unchecked)
1220     * exception to indicate abnormal exit. This method is designed to
1221     * support extensions, and should not in general be called
1222     * otherwise.
1223     *
1224     * @return {@code true} if this task is known to have completed normally
1225     */
1226    protected abstract boolean exec();
1227
1228    /**
1229     * Returns, but does not unschedule or execute, a task queued by
1230     * the current thread but not yet executed, if one is immediately
1231     * available. There is no guarantee that this task will actually
1232     * be polled or executed next. Conversely, this method may return
1233     * null even if a task exists but cannot be accessed without
1234     * contention with other threads.  This method is designed
1235     * primarily to support extensions, and is unlikely to be useful
1236     * otherwise.
1237     *
1238     * @return the next task, or {@code null} if none are available
1239     */
1240    protected static ForkJoinTask<?> peekNextLocalTask() {
1241        Thread t; ForkJoinPool.WorkQueue q;
1242        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1243            q = ((ForkJoinWorkerThread)t).workQueue;
1244        else
1245            q = ForkJoinPool.commonSubmitterQueue();
1246        return (q == null) ? null : q.peek();
1247    }
1248
1249    /**
1250     * Unschedules and returns, without executing, the next task
1251     * queued by the current thread but not yet executed, if the
1252     * current thread is operating in a ForkJoinPool.  This method is
1253     * designed primarily to support extensions, and is unlikely to be
1254     * useful otherwise.
1255     *
1256     * @return the next task, or {@code null} if none are available
1257     */
1258    protected static ForkJoinTask<?> pollNextLocalTask() {
1259        Thread t;
1260        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1261            ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() :
1262            null;
1263    }
1264
1265    /**
1266     * If the current thread is operating in a ForkJoinPool,
1267     * unschedules and returns, without executing, the next task
1268     * queued by the current thread but not yet executed, if one is
1269     * available, or if not available, a task that was forked by some
1270     * other thread, if available. Availability may be transient, so a
1271     * {@code null} result does not necessarily imply quiescence of
1272     * the pool this task is operating in.  This method is designed
1273     * primarily to support extensions, and is unlikely to be useful
1274     * otherwise.
1275     *
1276     * @return a task, or {@code null} if none are available
1277     */
1278    protected static ForkJoinTask<?> pollTask() {
1279        Thread t; ForkJoinWorkerThread wt;
1280        return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1281            (wt = (ForkJoinWorkerThread)t).pool.nextTaskFor(wt.workQueue) :
1282            null;
1283    }
1284
1285    // tag operations
1286
1287    /**
1288     * Returns the tag for this task.
1289     *
1290     * @return the tag for this task
1291     * @since 1.8
1292     * @hide
1293     */
1294    public final short getForkJoinTaskTag() {
1295        return (short)status;
1296    }
1297
1298    /**
1299     * Atomically sets the tag value for this task.
1300     *
1301     * @param tag the tag value
1302     * @return the previous value of the tag
1303     * @since 1.8
1304     * @hide
1305     */
1306    public final short setForkJoinTaskTag(short tag) {
1307        for (int s;;) {
1308            if (U.compareAndSwapInt(this, STATUS, s = status,
1309                                    (s & ~SMASK) | (tag & SMASK)))
1310                return (short)s;
1311        }
1312    }
1313
1314    /**
1315     * Atomically conditionally sets the tag value for this task.
1316     * Among other applications, tags can be used as visit markers
1317     * in tasks operating on graphs, as in methods that check: {@code
1318     * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1319     * before processing, otherwise exiting because the node has
1320     * already been visited.
1321     *
1322     * @param e the expected tag value
1323     * @param tag the new tag value
1324     * @return {@code true} if successful; i.e., the current value was
1325     * equal to e and is now tag.
1326     * @since 1.8
1327     * @hide
1328     */
1329    public final boolean compareAndSetForkJoinTaskTag(short e, short tag) {
1330        for (int s;;) {
1331            if ((short)(s = status) != e)
1332                return false;
1333            if (U.compareAndSwapInt(this, STATUS, s,
1334                                    (s & ~SMASK) | (tag & SMASK)))
1335                return true;
1336        }
1337    }
1338
1339    /**
1340     * Adaptor for Runnables. This implements RunnableFuture
1341     * to be compliant with AbstractExecutorService constraints
1342     * when used in ForkJoinPool.
1343     */
1344    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1345        implements RunnableFuture<T> {
1346        final Runnable runnable;
1347        T result;
1348        AdaptedRunnable(Runnable runnable, T result) {
1349            if (runnable == null) throw new NullPointerException();
1350            this.runnable = runnable;
1351            this.result = result; // OK to set this even before completion
1352        }
1353        public final T getRawResult() { return result; }
1354        public final void setRawResult(T v) { result = v; }
1355        public final boolean exec() { runnable.run(); return true; }
1356        public final void run() { invoke(); }
1357        private static final long serialVersionUID = 5232453952276885070L;
1358    }
1359
1360    /**
1361     * Adaptor for Runnables without results
1362     */
1363    static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1364        implements RunnableFuture<Void> {
1365        final Runnable runnable;
1366        AdaptedRunnableAction(Runnable runnable) {
1367            if (runnable == null) throw new NullPointerException();
1368            this.runnable = runnable;
1369        }
1370        public final Void getRawResult() { return null; }
1371        public final void setRawResult(Void v) { }
1372        public final boolean exec() { runnable.run(); return true; }
1373        public final void run() { invoke(); }
1374        private static final long serialVersionUID = 5232453952276885070L;
1375    }
1376
1377    /**
1378     * Adaptor for Runnables in which failure forces worker exception
1379     */
1380    static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1381        final Runnable runnable;
1382        RunnableExecuteAction(Runnable runnable) {
1383            if (runnable == null) throw new NullPointerException();
1384            this.runnable = runnable;
1385        }
1386        public final Void getRawResult() { return null; }
1387        public final void setRawResult(Void v) { }
1388        public final boolean exec() { runnable.run(); return true; }
1389        void internalPropagateException(Throwable ex) {
1390            rethrow(ex); // rethrow outside exec() catches.
1391        }
1392        private static final long serialVersionUID = 5232453952276885070L;
1393    }
1394
1395    /**
1396     * Adaptor for Callables
1397     */
1398    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1399        implements RunnableFuture<T> {
1400        final Callable<? extends T> callable;
1401        T result;
1402        AdaptedCallable(Callable<? extends T> callable) {
1403            if (callable == null) throw new NullPointerException();
1404            this.callable = callable;
1405        }
1406        public final T getRawResult() { return result; }
1407        public final void setRawResult(T v) { result = v; }
1408        public final boolean exec() {
1409            try {
1410                result = callable.call();
1411                return true;
1412            } catch (RuntimeException rex) {
1413                throw rex;
1414            } catch (Exception ex) {
1415                throw new RuntimeException(ex);
1416            }
1417        }
1418        public final void run() { invoke(); }
1419        private static final long serialVersionUID = 2838392045355241008L;
1420    }
1421
1422    /**
1423     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1424     * method of the given {@code Runnable} as its action, and returns
1425     * a null result upon {@link #join}.
1426     *
1427     * @param runnable the runnable action
1428     * @return the task
1429     */
1430    public static ForkJoinTask<?> adapt(Runnable runnable) {
1431        return new AdaptedRunnableAction(runnable);
1432    }
1433
1434    /**
1435     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1436     * method of the given {@code Runnable} as its action, and returns
1437     * the given result upon {@link #join}.
1438     *
1439     * @param runnable the runnable action
1440     * @param result the result upon completion
1441     * @return the task
1442     */
1443    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1444        return new AdaptedRunnable<T>(runnable, result);
1445    }
1446
1447    /**
1448     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1449     * method of the given {@code Callable} as its action, and returns
1450     * its result upon {@link #join}, translating any checked exceptions
1451     * encountered into {@code RuntimeException}.
1452     *
1453     * @param callable the callable action
1454     * @return the task
1455     */
1456    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1457        return new AdaptedCallable<T>(callable);
1458    }
1459
1460    // Serialization support
1461
1462    private static final long serialVersionUID = -7721805057305804111L;
1463
1464    /**
1465     * Saves this task to a stream (that is, serializes it).
1466     *
1467     * @serialData the current run status and the exception thrown
1468     * during execution, or {@code null} if none
1469     */
1470    private void writeObject(java.io.ObjectOutputStream s)
1471        throws java.io.IOException {
1472        s.defaultWriteObject();
1473        s.writeObject(getException());
1474    }
1475
1476    /**
1477     * Reconstitutes this task from a stream (that is, deserializes it).
1478     */
1479    private void readObject(java.io.ObjectInputStream s)
1480        throws java.io.IOException, ClassNotFoundException {
1481        s.defaultReadObject();
1482        Object ex = s.readObject();
1483        if (ex != null)
1484            setExceptionalCompletion((Throwable)ex);
1485    }
1486
1487    // Unsafe mechanics
1488    private static final sun.misc.Unsafe U;
1489    private static final long STATUS;
1490
1491    static {
1492        exceptionTableLock = new ReentrantLock();
1493        exceptionTableRefQueue = new ReferenceQueue<Object>();
1494        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1495        try {
1496            U = sun.misc.Unsafe.getUnsafe();
1497            Class<?> k = ForkJoinTask.class;
1498            STATUS = U.objectFieldOffset
1499                (k.getDeclaredField("status"));
1500        } catch (Exception e) {
1501            throw new Error(e);
1502        }
1503    }
1504}
1505