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