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

File Contents

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