ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.60
Committed: Sun Mar 4 15:52:41 2012 UTC (12 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.59: +56 -38 lines
Log Message:
marking -> taging; registerWorker fix

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