ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.123
Committed: Thu Oct 17 01:51:37 2019 UTC (4 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.122: +6 -0 lines
Log Message:
8232230: Suppress warnings on non-serializable non-transient instance fields in java.util.concurrent

File Contents

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