ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.117
Committed: Tue Sep 26 03:42:11 2017 UTC (6 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.116: +1 -1 lines
Log Message:
coding style

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