ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.91
Committed: Sun Oct 28 22:36:01 2012 UTC (11 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.90: +98 -143 lines
Log Message:
Introduce ForkJoinPool.commonPool

File Contents

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