ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.46
Committed: Mon Apr 5 15:52:26 2010 UTC (14 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.45: +247 -274 lines
Log Message:
Major internal restructuring

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     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package jsr166y;
8 jsr166 1.17
9     import java.util.concurrent.*;
10    
11 dl 1.1 import java.io.Serializable;
12 jsr166 1.17 import java.util.Collection;
13     import java.util.Collections;
14     import java.util.List;
15 dl 1.32 import java.util.RandomAccess;
16 jsr166 1.17 import java.util.Map;
17     import java.util.WeakHashMap;
18 dl 1.1
19     /**
20 jsr166 1.26 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
21     * A {@code ForkJoinTask} is a thread-like entity that is much
22 dl 1.2 * lighter weight than a normal thread. Huge numbers of tasks and
23     * subtasks may be hosted by a small number of actual threads in a
24     * ForkJoinPool, at the price of some usage limitations.
25 dl 1.4 *
26 jsr166 1.28 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27     * to a {@link ForkJoinPool}. Once started, it will usually in turn
28     * start other subtasks. As indicated by the name of this class,
29     * many programs using {@code ForkJoinTask} employ only methods
30     * {@link #fork} and {@link #join}, or derivatives such as {@link
31     * #invokeAll}. However, this class also provides a number of other
32     * methods that can come into play in advanced usages, as well as
33     * extension mechanics that allow support of new forms of fork/join
34     * processing.
35 dl 1.4 *
36 jsr166 1.28 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37     * The efficiency of {@code ForkJoinTask}s stems from a set of
38     * restrictions (that are only partially statically enforceable)
39     * reflecting their intended use as computational tasks calculating
40     * pure functions or operating on purely isolated objects. The
41     * primary coordination mechanisms are {@link #fork}, that arranges
42     * asynchronous execution, and {@link #join}, that doesn't proceed
43     * until the task's result has been computed. Computations should
44     * avoid {@code synchronized} methods or blocks, and should minimize
45     * other blocking synchronization apart from joining other tasks or
46     * using synchronizers such as Phasers that are advertised to
47     * cooperate with fork/join scheduling. Tasks should also not perform
48     * blocking IO, and should ideally access variables that are
49     * completely independent of those accessed by other running
50     * tasks. Minor breaches of these restrictions, for example using
51     * shared output streams, may be tolerable in practice, but frequent
52     * use may result in poor performance, and the potential to
53     * indefinitely stall if the number of threads not waiting for IO or
54     * other external synchronization becomes exhausted. This usage
55     * restriction is in part enforced by not permitting checked
56     * exceptions such as {@code IOExceptions} to be thrown. However,
57     * computations may still encounter unchecked exceptions, that are
58 dl 1.32 * rethrown to callers attempting to join them. These exceptions may
59 jsr166 1.44 * additionally include {@link RejectedExecutionException} stemming
60     * from internal resource exhaustion, such as failure to allocate
61     * internal task queues.
62 dl 1.1 *
63 dl 1.2 * <p>The primary method for awaiting completion and extracting
64     * results of a task is {@link #join}, but there are several variants:
65     * The {@link Future#get} methods support interruptible and/or timed
66 jsr166 1.8 * waits for completion and report results using {@code Future}
67 dl 1.2 * conventions. Method {@link #helpJoin} enables callers to actively
68     * execute other tasks while awaiting joins, which is sometimes more
69     * efficient but only applies when all subtasks are known to be
70     * strictly tree-structured. Method {@link #invoke} is semantically
71 dl 1.35 * equivalent to {@code fork(); join()} but always attempts to begin
72     * execution in the current thread. The "<em>quiet</em>" forms of
73     * these methods do not extract results or report exceptions. These
74 dl 1.2 * may be useful when a set of tasks are being executed, and you need
75     * to delay processing of results or exceptions until all complete.
76 jsr166 1.8 * Method {@code invokeAll} (available in multiple versions)
77 dl 1.2 * performs the most common form of parallel invocation: forking a set
78     * of tasks and joining them all.
79     *
80 dl 1.35 * <p>The execution status of tasks may be queried at several levels
81     * of detail: {@link #isDone} is true if a task completed in any way
82     * (including the case where a task was cancelled without executing);
83     * {@link #isCompletedNormally} is true if a task completed without
84 dl 1.42 * cancellation or encountering an exception; {@link #isCancelled} is
85     * true if the task was cancelled (in which case {@link #getException}
86     * returns a {@link java.util.concurrent.CancellationException}); and
87     * {@link #isCompletedAbnormally} is true if a task was either
88     * cancelled or encountered an exception, in which case {@link
89     * #getException} will return either the encountered exception or
90     * {@link java.util.concurrent.CancellationException}.
91 dl 1.35 *
92 jsr166 1.28 * <p>The ForkJoinTask class is not usually directly subclassed.
93 dl 1.2 * Instead, you subclass one of the abstract classes that support a
94 dl 1.27 * particular style of fork/join processing, typically {@link
95     * RecursiveAction} for computations that do not return results, or
96     * {@link RecursiveTask} for those that do. Normally, a concrete
97 dl 1.2 * ForkJoinTask subclass declares fields comprising its parameters,
98 jsr166 1.8 * established in a constructor, and then defines a {@code compute}
99 dl 1.2 * method that somehow uses the control methods supplied by this base
100 jsr166 1.8 * class. While these methods have {@code public} access (to allow
101 dl 1.32 * instances of different task subclasses to call each other's
102 dl 1.2 * methods), some of them may only be called from within other
103 dl 1.13 * ForkJoinTasks (as may be determined using method {@link
104     * #inForkJoinPool}). Attempts to invoke them in other contexts
105 jsr166 1.14 * result in exceptions or errors, possibly including
106 dl 1.13 * ClassCastException.
107 dl 1.1 *
108 dl 1.32 * <p>Most base support methods are {@code final}, to prevent
109     * overriding of implementations that are intrinsically tied to the
110     * underlying lightweight task scheduling framework. Developers
111     * creating new basic styles of fork/join processing should minimally
112     * implement {@code protected} methods {@link #exec}, {@link
113     * #setRawResult}, and {@link #getRawResult}, while also introducing
114     * an abstract computational method that can be implemented in its
115     * subclasses, possibly relying on other {@code protected} methods
116     * provided by this class.
117 dl 1.1 *
118     * <p>ForkJoinTasks should perform relatively small amounts of
119 dl 1.32 * computation. Large tasks should be split into smaller subtasks,
120     * usually via recursive decomposition. As a very rough rule of thumb,
121     * a task should perform more than 100 and less than 10000 basic
122     * computational steps. If tasks are too big, then parallelism cannot
123     * improve throughput. If too small, then memory and internal task
124     * maintenance overhead may overwhelm processing.
125 dl 1.1 *
126 jsr166 1.37 * <p>This class provides {@code adapt} methods for {@link Runnable}
127     * and {@link Callable}, that may be of use when mixing execution of
128     * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
129     * are of this form, consider using a pool in
130     * {@linkplain ForkJoinPool#setAsyncMode async mode}.
131 dl 1.27 *
132 dl 1.32 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
133     * used in extensions such as remote execution frameworks. It is
134     * sensible to serialize tasks only before or after, but not during,
135     * execution. Serialization is not relied on during execution itself.
136 jsr166 1.12 *
137     * @since 1.7
138     * @author Doug Lea
139 dl 1.1 */
140     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
141 dl 1.2
142 dl 1.46 /*
143     * See the internal documentation of class ForkJoinPool for a
144     * general implementation overview. ForkJoinTasks are mainly
145     * responsible for maintaining their "status" field amidst relays
146     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
147     * methods of this class are more-or-less layered into (1) basic
148     * status maintenance (2) execution and awaiting completion (3)
149     * user-level methods that additionally report results. This is
150     * sometimes hard to see because this file orders exported methods
151     * in a way that flows well in javadocs.
152     */
153    
154 dl 1.1 /**
155 dl 1.2 * Run control status bits packed into a single int to minimize
156     * footprint and to ensure atomicity (via CAS). Status is
157     * initially zero, and takes on nonnegative values until
158 dl 1.1 * completed, upon which status holds COMPLETED. CANCELLED, or
159     * EXCEPTIONAL, which use the top 3 bits. Tasks undergoing
160     * blocking waits by other threads have SIGNAL_MASK bits set --
161     * bit 15 for external (nonFJ) waits, and the rest a count of
162     * waiting FJ threads. (This representation relies on
163 dl 1.46 * ForkJoinPool max thread limits). Signal counts are not directly
164     * incremented by ForkJoinTask methods, but instead via a call to
165     * requestSignal within ForkJoinPool.preJoin, once their need is
166     * established.
167     *
168     * Completion of a stolen task with SIGNAL_MASK bits set awakens
169     * any waiters via notifyAll. Even though suboptimal for some
170     * purposes, we use basic builtin wait/notify to take advantage of
171     * "monitor inflation" in JVMs that we would otherwise need to
172     * emulate to avoid adding further per-task bookkeeping overhead.
173     * We want these monitors to be "fat", i.e., not use biasing or
174     * thin-lock techniques, so use some odd coding idioms that tend
175     * to avoid them.
176     *
177     * Note that bits 16-28 are currently unused. Also value
178     * 0x80000000 is available as spare completion value.
179 dl 1.1 */
180 jsr166 1.9 volatile int status; // accessed directly by pool and workers
181 dl 1.1
182 dl 1.46 private static final int COMPLETION_MASK = 0xe0000000;
183     private static final int NORMAL = 0xe0000000; // == mask
184     private static final int CANCELLED = 0xc0000000;
185     private static final int EXCEPTIONAL = 0xa0000000;
186     private static final int SIGNAL_MASK = 0x0000ffff;
187     private static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
188     private static final int EXTERNAL_SIGNAL = 0x00008000;
189 dl 1.1
190     /**
191     * Table of exceptions thrown by tasks, to enable reporting by
192     * callers. Because exceptions are rare, we don't directly keep
193 jsr166 1.10 * them with task objects, but instead use a weak ref table. Note
194 dl 1.1 * that cancellation exceptions don't appear in the table, but are
195     * instead recorded as status values.
196 jsr166 1.10 * TODO: Use ConcurrentReferenceHashMap
197 dl 1.1 */
198     static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
199     Collections.synchronizedMap
200     (new WeakHashMap<ForkJoinTask<?>, Throwable>());
201    
202 dl 1.46 // Maintaining completion status
203 dl 1.1
204     /**
205 dl 1.46 * Marks completion and wakes up threads waiting to join this task,
206     * also clearing signal request bits.
207     *
208     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
209 dl 1.1 */
210 dl 1.46 private void setCompletion(int completion) {
211     int s;
212     while ((s = status) >= 0) {
213     if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
214     if ((s & SIGNAL_MASK) != 0) {
215     Thread t = Thread.currentThread();
216     if (t instanceof ForkJoinWorkerThread)
217     ((ForkJoinWorkerThread) t).pool.updateRunningCount
218     (s & INTERNAL_SIGNAL_MASK);
219     synchronized (this) { notifyAll(); }
220     }
221     return;
222     }
223     }
224 dl 1.1 }
225    
226     /**
227 dl 1.46 * Record exception and set exceptional completion
228 dl 1.1 */
229 dl 1.46 private void setDoneExceptionally(Throwable rex) {
230     exceptionMap.put(this, rex);
231     setCompletion(EXCEPTIONAL);
232 dl 1.1 }
233    
234     /**
235 dl 1.46 * Main internal execution method: Unless done, calls exec and
236     * records completion.
237 jsr166 1.10 *
238 dl 1.46 * @return true if ran and completed normally
239 dl 1.1 */
240 dl 1.46 final boolean tryExec() {
241     try {
242     if (status < 0 || !exec())
243     return false;
244     } catch (Throwable rex) {
245     setDoneExceptionally(rex);
246     return false;
247 dl 1.1 }
248 dl 1.46 setCompletion(NORMAL); // must be outside try block
249     return true;
250 dl 1.1 }
251    
252     /**
253 dl 1.46 * Increments internal signal count (thus requesting signal upon
254     * completion) unless already done. Call only once per join.
255     * Used by ForkJoinPool.preJoin.
256     *
257     * @return status
258 dl 1.1 */
259 dl 1.46 final int requestSignal() {
260 dl 1.1 int s;
261 dl 1.46 do {} while ((s = status) >= 0 &&
262     !UNSAFE.compareAndSwapInt(this, statusOffset, s, s + 1));
263     return s;
264 dl 1.1 }
265 dl 1.46
266 dl 1.1 /**
267 dl 1.46 * Sets external signal request unless already done.
268     *
269     * @return status
270 dl 1.1 */
271 dl 1.46 private int requestExternalSignal() {
272     int s;
273     do {} while ((s = status) >= 0 &&
274     !UNSAFE.compareAndSwapInt(this, statusOffset,
275     s, s | EXTERNAL_SIGNAL));
276     return s;
277 dl 1.1 }
278    
279 dl 1.46 /*
280     * Awaiting completion. The four versions, internal vs external X
281     * untimed vs timed, have the same overall structure but differ
282     * from each other enough to defy simple integration.
283 dl 1.1 */
284    
285     /**
286 dl 1.46 * Blocks a worker until this task is done, also maintaining pool
287     * and signal counts
288 dl 1.1 */
289 dl 1.46 private void awaitDone(ForkJoinWorkerThread w) {
290     if (status >= 0) {
291     w.pool.preJoin(this);
292     while (status >= 0) {
293     try { // minimize lock scope
294     synchronized(this) {
295     if (status >= 0)
296     wait();
297     else { // help release; also helps avoid lock-biasing
298     notifyAll();
299     break;
300     }
301     }
302     } catch (InterruptedException ie) {
303     cancelIfTerminating();
304 dl 1.1 }
305     }
306     }
307     }
308    
309     /**
310 dl 1.46 * Blocks a non-ForkJoin thread until this task is done.
311 dl 1.1 */
312 dl 1.46 private void externalAwaitDone() {
313     if (requestExternalSignal() >= 0) {
314     boolean interrupted = false;
315     while (status >= 0) {
316     try {
317     synchronized(this) {
318     if (status >= 0)
319     wait();
320     else {
321     notifyAll();
322     break;
323     }
324     }
325     } catch (InterruptedException ie) {
326     interrupted = true;
327     }
328 dl 1.1 }
329 dl 1.46 if (interrupted)
330     Thread.currentThread().interrupt();
331 dl 1.1 }
332     }
333    
334     /**
335 dl 1.46 * Blocks a worker until this task is done or timeout elapses
336 dl 1.1 */
337 dl 1.46 private void timedAwaitDone(ForkJoinWorkerThread w, long nanos) {
338     if (status >= 0) {
339     long startTime = System.nanoTime();
340     ForkJoinPool pool = w.pool;
341     pool.preJoin(this);
342     while (status >= 0) {
343     long nt = nanos - (System.nanoTime() - startTime);
344     if (nt > 0) {
345     long ms = nt / 1000000;
346     int ns = (int) (nt % 1000000);
347     try {
348     synchronized(this) { if (status >= 0) wait(ms, ns); }
349     } catch (InterruptedException ie) {
350     cancelIfTerminating();
351     }
352     }
353     else {
354     int s; // adjust running count on timeout
355     while ((s = status) >= 0 &&
356     (s & INTERNAL_SIGNAL_MASK) != 0) {
357     if (UNSAFE.compareAndSwapInt(this, statusOffset,
358     s, s - 1)) {
359     pool.updateRunningCount(1);
360     break;
361     }
362     }
363     break;
364 dl 1.1 }
365     }
366     }
367     }
368    
369     /**
370 dl 1.46 * Blocks a non-ForkJoin thread until this task is done or timeout elapses
371 dl 1.1 */
372 dl 1.46 private void externalTimedAwaitDone(long nanos) {
373     if (requestExternalSignal() >= 0) {
374     long startTime = System.nanoTime();
375     boolean interrupted = false;
376     while (status >= 0) {
377     long nt = nanos - (System.nanoTime() - startTime);
378     if (nt <= 0)
379 dl 1.1 break;
380 dl 1.46 long ms = nt / 1000000;
381     int ns = (int) (nt % 1000000);
382     try {
383     synchronized(this) { if (status >= 0) wait(ms, ns); }
384     } catch (InterruptedException ie) {
385     interrupted = true;
386 dl 1.1 }
387     }
388 dl 1.46 if (interrupted)
389     Thread.currentThread().interrupt();
390 dl 1.1 }
391     }
392    
393 dl 1.46 // reporting results
394 dl 1.1
395     /**
396 dl 1.46 * Returns result or throws the exception associated with status.
397     * Uses Unsafe as a workaround for javac not allowing rethrow of
398     * unchecked exceptions.
399 dl 1.1 */
400 dl 1.46 private V reportResult() {
401     if ((status & COMPLETION_MASK) < NORMAL) {
402     Throwable ex = getException();
403     if (ex != null)
404     UNSAFE.throwException(ex);
405 dl 1.1 }
406 dl 1.46 return getRawResult();
407 dl 1.1 }
408    
409     /**
410 jsr166 1.10 * Returns result or throws exception using j.u.c.Future conventions.
411 dl 1.38 * Only call when {@code isDone} known to be true or thread known
412     * to be interrupted.
413 dl 1.1 */
414     private V reportFutureResult()
415 jsr166 1.37 throws InterruptedException, ExecutionException {
416 dl 1.34 if (Thread.interrupted())
417     throw new InterruptedException();
418 dl 1.1 int s = status & COMPLETION_MASK;
419     if (s < NORMAL) {
420     Throwable ex;
421     if (s == CANCELLED)
422     throw new CancellationException();
423     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
424     throw new ExecutionException(ex);
425     }
426     return getRawResult();
427     }
428    
429     /**
430     * Returns result or throws exception using j.u.c.Future conventions
431 jsr166 1.10 * with timeouts.
432 dl 1.1 */
433     private V reportTimedFutureResult()
434     throws InterruptedException, ExecutionException, TimeoutException {
435 dl 1.34 if (Thread.interrupted())
436     throw new InterruptedException();
437 dl 1.1 Throwable ex;
438     int s = status & COMPLETION_MASK;
439     if (s == NORMAL)
440     return getRawResult();
441 jsr166 1.37 else if (s == CANCELLED)
442 dl 1.1 throw new CancellationException();
443 jsr166 1.37 else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
444 dl 1.1 throw new ExecutionException(ex);
445 jsr166 1.37 else
446     throw new TimeoutException();
447 dl 1.1 }
448    
449     // public methods
450    
451     /**
452     * Arranges to asynchronously execute this task. While it is not
453     * necessarily enforced, it is a usage error to fork a task more
454 jsr166 1.31 * than once unless it has completed and been reinitialized.
455 dl 1.43 * Subsequent modifications to the state of this task or any data
456     * it operates on are not necessarily consistently observable by
457     * any thread other than the one executing it unless preceded by a
458     * call to {@link #join} or related methods, or a call to {@link
459     * #isDone} returning {@code true}.
460 dl 1.18 *
461 jsr166 1.31 * <p>This method may be invoked only from within {@code
462     * ForkJoinTask} computations (as may be determined using method
463     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
464     * result in exceptions or errors, possibly including {@code
465     * ClassCastException}.
466     *
467     * @return {@code this}, to simplify usage
468 dl 1.1 */
469 dl 1.18 public final ForkJoinTask<V> fork() {
470 jsr166 1.14 ((ForkJoinWorkerThread) Thread.currentThread())
471     .pushTask(this);
472 dl 1.18 return this;
473 dl 1.1 }
474    
475     /**
476 dl 1.41 * Returns the result of the computation when it {@link #isDone is done}.
477 jsr166 1.31 * This method differs from {@link #get()} in that
478     * abnormal completion results in {@code RuntimeException} or
479     * {@code Error}, not {@code ExecutionException}.
480 dl 1.1 *
481     * @return the computed result
482     */
483     public final V join() {
484 dl 1.46 quietlyJoin();
485     return reportResult();
486 dl 1.1 }
487    
488     /**
489 dl 1.2 * Commences performing this task, awaits its completion if
490 dl 1.34 * necessary, and return its result, or throws an (unchecked)
491     * exception if the underlying computation did so.
492 jsr166 1.10 *
493 dl 1.1 * @return the computed result
494     */
495     public final V invoke() {
496 dl 1.46 if (!tryExec())
497     quietlyJoin();
498     return reportResult();
499 dl 1.1 }
500    
501     /**
502 dl 1.34 * Forks the given tasks, returning when {@code isDone} holds for
503     * each task or an (unchecked) exception is encountered, in which
504 jsr166 1.39 * case the exception is rethrown. If either task encounters an
505     * exception, the other one may be, but is not guaranteed to be,
506     * cancelled. If both tasks throw an exception, then this method
507     * throws one of them. The individual status of each task may be
508 dl 1.34 * checked using {@link #getException()} and related methods.
509 jsr166 1.31 *
510     * <p>This method may be invoked only from within {@code
511     * ForkJoinTask} computations (as may be determined using method
512     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
513     * result in exceptions or errors, possibly including {@code
514     * ClassCastException}.
515 jsr166 1.10 *
516 dl 1.27 * @param t1 the first task
517     * @param t2 the second task
518     * @throws NullPointerException if any task is null
519 dl 1.1 */
520 jsr166 1.31 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
521 dl 1.2 t2.fork();
522     t1.invoke();
523     t2.join();
524 dl 1.1 }
525    
526     /**
527 dl 1.27 * Forks the given tasks, returning when {@code isDone} holds for
528 dl 1.34 * each task or an (unchecked) exception is encountered, in which
529     * case the exception is rethrown. If any task encounters an
530     * exception, others may be, but are not guaranteed to be,
531     * cancelled. If more than one task encounters an exception, then
532     * this method throws any one of these exceptions. The individual
533     * status of each task may be checked using {@link #getException()}
534     * and related methods.
535 jsr166 1.31 *
536     * <p>This method may be invoked only from within {@code
537     * ForkJoinTask} computations (as may be determined using method
538     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
539     * result in exceptions or errors, possibly including {@code
540     * ClassCastException}.
541 jsr166 1.14 *
542 dl 1.27 * @param tasks the tasks
543 dl 1.34 * @throws NullPointerException if any task is null
544 dl 1.1 */
545 dl 1.2 public static void invokeAll(ForkJoinTask<?>... tasks) {
546     Throwable ex = null;
547     int last = tasks.length - 1;
548     for (int i = last; i >= 0; --i) {
549     ForkJoinTask<?> t = tasks[i];
550     if (t == null) {
551     if (ex == null)
552     ex = new NullPointerException();
553     }
554     else if (i != 0)
555     t.fork();
556     else {
557     t.quietlyInvoke();
558     if (ex == null)
559     ex = t.getException();
560     }
561     }
562     for (int i = 1; i <= last; ++i) {
563     ForkJoinTask<?> t = tasks[i];
564     if (t != null) {
565     if (ex != null)
566     t.cancel(false);
567     else {
568     t.quietlyJoin();
569     if (ex == null)
570     ex = t.getException();
571     }
572     }
573 dl 1.1 }
574 dl 1.2 if (ex != null)
575 dl 1.46 UNSAFE.throwException(ex);
576 dl 1.1 }
577    
578     /**
579 dl 1.32 * Forks all tasks in the specified collection, returning when
580 dl 1.34 * {@code isDone} holds for each task or an (unchecked) exception
581     * is encountered. If any task encounters an exception, others
582     * may be, but are not guaranteed to be, cancelled. If more than
583     * one task encounters an exception, then this method throws any
584     * one of these exceptions. The individual status of each task
585     * may be checked using {@link #getException()} and related
586     * methods. The behavior of this operation is undefined if the
587     * specified collection is modified while the operation is in
588     * progress.
589 jsr166 1.31 *
590     * <p>This method may be invoked only from within {@code
591     * ForkJoinTask} computations (as may be determined using method
592     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
593     * result in exceptions or errors, possibly including {@code
594     * ClassCastException}.
595 jsr166 1.10 *
596 dl 1.2 * @param tasks the collection of tasks
597 dl 1.19 * @return the tasks argument, to simplify usage
598 jsr166 1.10 * @throws NullPointerException if tasks or any element are null
599 dl 1.1 */
600 dl 1.19 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
601 dl 1.32 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
602 jsr166 1.14 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
603 dl 1.19 return tasks;
604 dl 1.2 }
605 jsr166 1.15 @SuppressWarnings("unchecked")
606 dl 1.2 List<? extends ForkJoinTask<?>> ts =
607 jsr166 1.14 (List<? extends ForkJoinTask<?>>) tasks;
608 dl 1.2 Throwable ex = null;
609     int last = ts.size() - 1;
610     for (int i = last; i >= 0; --i) {
611     ForkJoinTask<?> t = ts.get(i);
612     if (t == null) {
613     if (ex == null)
614     ex = new NullPointerException();
615     }
616     else if (i != 0)
617     t.fork();
618     else {
619     t.quietlyInvoke();
620     if (ex == null)
621     ex = t.getException();
622     }
623     }
624     for (int i = 1; i <= last; ++i) {
625     ForkJoinTask<?> t = ts.get(i);
626     if (t != null) {
627     if (ex != null)
628     t.cancel(false);
629     else {
630     t.quietlyJoin();
631     if (ex == null)
632     ex = t.getException();
633     }
634     }
635     }
636     if (ex != null)
637 dl 1.46 UNSAFE.throwException(ex);
638 dl 1.19 return tasks;
639 dl 1.1 }
640    
641     /**
642 dl 1.33 * Attempts to cancel execution of this task. This attempt will
643     * fail if the task has already completed, has already been
644     * cancelled, or could not be cancelled for some other reason. If
645     * successful, and this task has not started when cancel is
646     * called, execution of this task is suppressed, {@link
647     * #isCancelled} will report true, and {@link #join} will result
648     * in a {@code CancellationException} being thrown.
649 dl 1.1 *
650     * <p>This method may be overridden in subclasses, but if so, must
651     * still ensure that these minimal properties hold. In particular,
652 jsr166 1.29 * the {@code cancel} method itself must not throw exceptions.
653 dl 1.1 *
654 jsr166 1.28 * <p>This method is designed to be invoked by <em>other</em>
655 dl 1.1 * tasks. To terminate the current task, you can just return or
656     * throw an unchecked exception from its computation method, or
657 jsr166 1.24 * invoke {@link #completeExceptionally}.
658 dl 1.1 *
659     * @param mayInterruptIfRunning this value is ignored in the
660 dl 1.33 * default implementation because tasks are not
661 jsr166 1.14 * cancelled via interruption
662 dl 1.1 *
663 jsr166 1.23 * @return {@code true} if this task is now cancelled
664 dl 1.1 */
665     public boolean cancel(boolean mayInterruptIfRunning) {
666     setCompletion(CANCELLED);
667     return (status & COMPLETION_MASK) == CANCELLED;
668     }
669    
670 dl 1.46 /**
671     * Cancels, ignoring any exceptions it throws. Used during worker
672     * and pool shutdown.
673     */
674     final void cancelIgnoringExceptions() {
675     try {
676     cancel(false);
677     } catch (Throwable ignore) {
678     }
679     }
680    
681     /**
682     * Cancels ignoring exceptions if worker is terminating
683     */
684     private void cancelIfTerminating() {
685     Thread t = Thread.currentThread();
686     if ((t instanceof ForkJoinWorkerThread) &&
687     ((ForkJoinWorkerThread) t).isTerminating()) {
688     try {
689     cancel(false);
690     } catch (Throwable ignore) {
691     }
692     }
693     }
694    
695 dl 1.34 public final boolean isDone() {
696     return status < 0;
697     }
698    
699     public final boolean isCancelled() {
700     return (status & COMPLETION_MASK) == CANCELLED;
701     }
702    
703     /**
704 jsr166 1.23 * Returns {@code true} if this task threw an exception or was cancelled.
705 jsr166 1.10 *
706 jsr166 1.23 * @return {@code true} if this task threw an exception or was cancelled
707 dl 1.3 */
708     public final boolean isCompletedAbnormally() {
709     return (status & COMPLETION_MASK) < NORMAL;
710     }
711    
712     /**
713 dl 1.34 * Returns {@code true} if this task completed without throwing an
714     * exception and was not cancelled.
715     *
716     * @return {@code true} if this task completed without throwing an
717     * exception and was not cancelled
718     */
719     public final boolean isCompletedNormally() {
720     return (status & COMPLETION_MASK) == NORMAL;
721     }
722    
723     /**
724 dl 1.3 * Returns the exception thrown by the base computation, or a
725 jsr166 1.29 * {@code CancellationException} if cancelled, or {@code null} if
726     * none or if the method has not yet completed.
727 jsr166 1.10 *
728 jsr166 1.23 * @return the exception, or {@code null} if none
729 dl 1.3 */
730     public final Throwable getException() {
731     int s = status & COMPLETION_MASK;
732 jsr166 1.37 return ((s >= NORMAL) ? null :
733     (s == CANCELLED) ? new CancellationException() :
734     exceptionMap.get(this));
735 dl 1.3 }
736    
737     /**
738 dl 1.1 * Completes this task abnormally, and if not already aborted or
739     * cancelled, causes it to throw the given exception upon
740 jsr166 1.8 * {@code join} and related operations. This method may be used
741 dl 1.1 * to induce exceptions in asynchronous tasks, or to force
742 dl 1.2 * completion of tasks that would not otherwise complete. Its use
743 dl 1.27 * in other situations is discouraged. This method is
744 jsr166 1.8 * overridable, but overridden versions must invoke {@code super}
745 dl 1.2 * implementation to maintain guarantees.
746     *
747 jsr166 1.44 * @param ex the exception to throw. If this exception is not a
748     * {@code RuntimeException} or {@code Error}, the actual exception
749     * thrown will be a {@code RuntimeException} with cause {@code ex}.
750 dl 1.1 */
751     public void completeExceptionally(Throwable ex) {
752     setDoneExceptionally((ex instanceof RuntimeException) ||
753 jsr166 1.14 (ex instanceof Error) ? ex :
754 dl 1.1 new RuntimeException(ex));
755     }
756    
757     /**
758     * Completes this task, and if not already aborted or cancelled,
759 jsr166 1.8 * returning a {@code null} result upon {@code join} and related
760 dl 1.1 * operations. This method may be used to provide results for
761     * asynchronous tasks, or to provide alternative handling for
762 dl 1.2 * tasks that would not otherwise complete normally. Its use in
763 dl 1.27 * other situations is discouraged. This method is
764 jsr166 1.8 * overridable, but overridden versions must invoke {@code super}
765 dl 1.2 * implementation to maintain guarantees.
766 dl 1.1 *
767 jsr166 1.10 * @param value the result value for this task
768 dl 1.1 */
769     public void complete(V value) {
770     try {
771     setRawResult(value);
772 jsr166 1.14 } catch (Throwable rex) {
773 dl 1.1 setDoneExceptionally(rex);
774     return;
775     }
776 dl 1.46 setCompletion(NORMAL);
777 dl 1.1 }
778    
779 dl 1.3 public final V get() throws InterruptedException, ExecutionException {
780 dl 1.46 quietlyJoin();
781 dl 1.3 return reportFutureResult();
782     }
783 dl 1.46
784 dl 1.3 public final V get(long timeout, TimeUnit unit)
785     throws InterruptedException, ExecutionException, TimeoutException {
786 dl 1.25 long nanos = unit.toNanos(timeout);
787 dl 1.46 Thread t = Thread.currentThread();
788     if (t instanceof ForkJoinWorkerThread) {
789     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
790     if (!w.unpushTask(this) || !tryExec())
791     timedAwaitDone(w, nanos);
792     }
793     else
794     externalTimedAwaitDone(nanos);
795 dl 1.3 return reportTimedFutureResult();
796     }
797    
798 dl 1.1 /**
799 dl 1.41 * Possibly executes other tasks until this task {@link #isDone is
800     * done}, then returns the result of the computation. This method
801     * may be more efficient than {@code join}, but is only applicable
802     * when there are no potential dependencies between continuation
803     * of the current task and that of any other task that might be
804     * executed while helping. (This usually holds for pure
805     * divide-and-conquer tasks).
806 jsr166 1.31 *
807     * <p>This method may be invoked only from within {@code
808     * ForkJoinTask} computations (as may be determined using method
809     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
810     * result in exceptions or errors, possibly including {@code
811     * ClassCastException}.
812 jsr166 1.10 *
813 dl 1.2 * @return the computed result
814     */
815     public final V helpJoin() {
816 dl 1.46 quietlyHelpJoin();
817     return reportResult();
818 dl 1.2 }
819    
820     /**
821 dl 1.41 * Possibly executes other tasks until this task {@link #isDone is
822     * done}. This method may be useful when processing collections
823     * of tasks when some have been cancelled or otherwise known to
824     * have aborted.
825 jsr166 1.31 *
826     * <p>This method may be invoked only from within {@code
827     * ForkJoinTask} computations (as may be determined using method
828     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
829     * result in exceptions or errors, possibly including {@code
830     * ClassCastException}.
831 dl 1.2 */
832     public final void quietlyHelpJoin() {
833 dl 1.46 ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
834     if (!w.unpushTask(this) || !tryExec()) {
835     while (status >= 0) {
836     ForkJoinTask<?> t = w.scanWhileJoining(this);
837     if (t == null) {
838     if (status >= 0)
839     awaitDone(w);
840     break;
841     }
842     t.tryExec();
843     }
844 dl 1.2 }
845     }
846    
847     /**
848     * Joins this task, without returning its result or throwing an
849     * exception. This method may be useful when processing
850     * collections of tasks when some have been cancelled or otherwise
851     * known to have aborted.
852     */
853     public final void quietlyJoin() {
854 dl 1.46 Thread t = Thread.currentThread();
855     if (t instanceof ForkJoinWorkerThread) {
856     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
857     if (!w.unpushTask(this) || !tryExec())
858     awaitDone(w);
859 dl 1.2 }
860 dl 1.46 else
861     externalAwaitDone();
862 dl 1.2 }
863    
864     /**
865     * Commences performing this task and awaits its completion if
866     * necessary, without returning its result or throwing an
867     * exception. This method may be useful when processing
868     * collections of tasks when some have been cancelled or otherwise
869     * known to have aborted.
870     */
871     public final void quietlyInvoke() {
872 dl 1.46 if (!tryExec())
873 dl 1.2 quietlyJoin();
874     }
875    
876     /**
877 dl 1.3 * Possibly executes tasks until the pool hosting the current task
878 dl 1.33 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
879     * be of use in designs in which many tasks are forked, but none
880     * are explicitly joined, instead executing them until all are
881     * processed.
882 jsr166 1.31 *
883     * <p>This method may be invoked only from within {@code
884     * ForkJoinTask} computations (as may be determined using method
885     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
886     * result in exceptions or errors, possibly including {@code
887     * ClassCastException}.
888 dl 1.3 */
889     public static void helpQuiesce() {
890 jsr166 1.14 ((ForkJoinWorkerThread) Thread.currentThread())
891     .helpQuiescePool();
892 dl 1.3 }
893    
894     /**
895 dl 1.1 * Resets the internal bookkeeping state of this task, allowing a
896 jsr166 1.8 * subsequent {@code fork}. This method allows repeated reuse of
897 dl 1.1 * this task, but only if reuse occurs when this task has either
898     * never been forked, or has been forked, then completed and all
899     * outstanding joins of this task have also completed. Effects
900 dl 1.30 * under any other usage conditions are not guaranteed.
901     * This method may be useful when executing
902 dl 1.1 * pre-constructed trees of subtasks in loops.
903     */
904     public void reinitialize() {
905     if ((status & COMPLETION_MASK) == EXCEPTIONAL)
906     exceptionMap.remove(this);
907     status = 0;
908     }
909    
910     /**
911 dl 1.2 * Returns the pool hosting the current task execution, or null
912 dl 1.13 * if this task is executing outside of any ForkJoinPool.
913 jsr166 1.10 *
914 dl 1.27 * @see #inForkJoinPool
915 jsr166 1.23 * @return the pool, or {@code null} if none
916 dl 1.1 */
917 dl 1.2 public static ForkJoinPool getPool() {
918     Thread t = Thread.currentThread();
919 jsr166 1.15 return (t instanceof ForkJoinWorkerThread) ?
920     ((ForkJoinWorkerThread) t).pool : null;
921 dl 1.1 }
922    
923     /**
924 jsr166 1.14 * Returns {@code true} if the current thread is executing as a
925 dl 1.13 * ForkJoinPool computation.
926 jsr166 1.14 *
927     * @return {@code true} if the current thread is executing as a
928 dl 1.13 * ForkJoinPool computation, or false otherwise
929     */
930     public static boolean inForkJoinPool() {
931     return Thread.currentThread() instanceof ForkJoinWorkerThread;
932     }
933    
934     /**
935 dl 1.2 * Tries to unschedule this task for execution. This method will
936     * typically succeed if this task is the most recently forked task
937     * by the current thread, and has not commenced executing in
938     * another thread. This method may be useful when arranging
939     * alternative local processing of tasks that could have been, but
940 jsr166 1.31 * were not, stolen.
941     *
942     * <p>This method may be invoked only from within {@code
943     * ForkJoinTask} computations (as may be determined using method
944     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
945     * result in exceptions or errors, possibly including {@code
946     * ClassCastException}.
947 jsr166 1.10 *
948 jsr166 1.23 * @return {@code true} if unforked
949 dl 1.1 */
950 dl 1.2 public boolean tryUnfork() {
951 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
952     .unpushTask(this);
953 dl 1.1 }
954    
955     /**
956 dl 1.2 * Returns an estimate of the number of tasks that have been
957     * forked by the current worker thread but not yet executed. This
958     * value may be useful for heuristic decisions about whether to
959 jsr166 1.31 * fork other tasks.
960     *
961     * <p>This method may be invoked only from within {@code
962     * ForkJoinTask} computations (as may be determined using method
963     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
964     * result in exceptions or errors, possibly including {@code
965     * ClassCastException}.
966     *
967 dl 1.2 * @return the number of tasks
968     */
969     public static int getQueuedTaskCount() {
970 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
971     .getQueueSize();
972 dl 1.2 }
973    
974     /**
975 jsr166 1.10 * Returns an estimate of how many more locally queued tasks are
976 dl 1.1 * held by the current worker thread than there are other worker
977 dl 1.2 * threads that might steal them. This value may be useful for
978     * heuristic decisions about whether to fork other tasks. In many
979     * usages of ForkJoinTasks, at steady state, each worker should
980     * aim to maintain a small constant surplus (for example, 3) of
981     * tasks, and to process computations locally if this threshold is
982 jsr166 1.31 * exceeded.
983     *
984     * <p>This method may be invoked only from within {@code
985     * ForkJoinTask} computations (as may be determined using method
986     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
987     * result in exceptions or errors, possibly including {@code
988     * ClassCastException}.
989     *
990 dl 1.1 * @return the surplus number of tasks, which may be negative
991     */
992 dl 1.2 public static int getSurplusQueuedTaskCount() {
993 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
994 dl 1.1 .getEstimatedSurplusTaskCount();
995     }
996    
997 dl 1.2 // Extension methods
998 dl 1.1
999     /**
1000 jsr166 1.23 * Returns the result that would be returned by {@link #join}, even
1001     * if this task completed abnormally, or {@code null} if this task
1002     * is not known to have been completed. This method is designed
1003     * to aid debugging, as well as to support extensions. Its use in
1004     * any other context is discouraged.
1005 dl 1.1 *
1006 jsr166 1.23 * @return the result, or {@code null} if not completed
1007 dl 1.1 */
1008     public abstract V getRawResult();
1009    
1010     /**
1011     * Forces the given value to be returned as a result. This method
1012     * is designed to support extensions, and should not in general be
1013     * called otherwise.
1014     *
1015     * @param value the value
1016     */
1017     protected abstract void setRawResult(V value);
1018    
1019     /**
1020     * Immediately performs the base action of this task. This method
1021     * is designed to support extensions, and should not in general be
1022     * called otherwise. The return value controls whether this task
1023     * is considered to be done normally. It may return false in
1024     * asynchronous actions that require explicit invocations of
1025 dl 1.34 * {@link #complete} to become joinable. It may also throw an
1026     * (unchecked) exception to indicate abnormal exit.
1027 jsr166 1.10 *
1028 jsr166 1.23 * @return {@code true} if completed normally
1029 dl 1.1 */
1030     protected abstract boolean exec();
1031    
1032 dl 1.2 /**
1033 dl 1.25 * Returns, but does not unschedule or execute, a task queued by
1034     * the current thread but not yet executed, if one is immediately
1035 dl 1.6 * available. There is no guarantee that this task will actually
1036 dl 1.25 * be polled or executed next. Conversely, this method may return
1037     * null even if a task exists but cannot be accessed without
1038     * contention with other threads. This method is designed
1039     * primarily to support extensions, and is unlikely to be useful
1040 jsr166 1.31 * otherwise.
1041     *
1042     * <p>This method may be invoked only from within {@code
1043     * ForkJoinTask} computations (as may be determined using method
1044     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1045     * result in exceptions or errors, possibly including {@code
1046     * ClassCastException}.
1047 dl 1.2 *
1048 jsr166 1.23 * @return the next task, or {@code null} if none are available
1049 dl 1.2 */
1050     protected static ForkJoinTask<?> peekNextLocalTask() {
1051 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1052     .peekTask();
1053 dl 1.2 }
1054    
1055     /**
1056 dl 1.6 * Unschedules and returns, without executing, the next task
1057     * queued by the current thread but not yet executed. This method
1058     * is designed primarily to support extensions, and is unlikely to
1059 jsr166 1.31 * be useful otherwise.
1060     *
1061     * <p>This method may be invoked only from within {@code
1062     * ForkJoinTask} computations (as may be determined using method
1063     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1064     * result in exceptions or errors, possibly including {@code
1065     * ClassCastException}.
1066 dl 1.2 *
1067 jsr166 1.23 * @return the next task, or {@code null} if none are available
1068 dl 1.2 */
1069     protected static ForkJoinTask<?> pollNextLocalTask() {
1070 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1071     .pollLocalTask();
1072 dl 1.2 }
1073 jsr166 1.7
1074 dl 1.2 /**
1075 dl 1.6 * Unschedules and returns, without executing, the next task
1076     * queued by the current thread but not yet executed, if one is
1077     * available, or if not available, a task that was forked by some
1078     * other thread, if available. Availability may be transient, so a
1079 jsr166 1.9 * {@code null} result does not necessarily imply quiescence
1080 dl 1.6 * of the pool this task is operating in. This method is designed
1081     * primarily to support extensions, and is unlikely to be useful
1082 jsr166 1.31 * otherwise.
1083     *
1084     * <p>This method may be invoked only from within {@code
1085     * ForkJoinTask} computations (as may be determined using method
1086     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1087     * result in exceptions or errors, possibly including {@code
1088     * ClassCastException}.
1089 dl 1.4 *
1090 jsr166 1.23 * @return a task, or {@code null} if none are available
1091 dl 1.2 */
1092     protected static ForkJoinTask<?> pollTask() {
1093 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1094     .pollTask();
1095 dl 1.2 }
1096    
1097 dl 1.25 /**
1098     * Adaptor for Runnables. This implements RunnableFuture
1099     * to be compliant with AbstractExecutorService constraints
1100     * when used in ForkJoinPool.
1101     */
1102     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1103     implements RunnableFuture<T> {
1104     final Runnable runnable;
1105     final T resultOnCompletion;
1106     T result;
1107     AdaptedRunnable(Runnable runnable, T result) {
1108     if (runnable == null) throw new NullPointerException();
1109     this.runnable = runnable;
1110     this.resultOnCompletion = result;
1111     }
1112     public T getRawResult() { return result; }
1113     public void setRawResult(T v) { result = v; }
1114     public boolean exec() {
1115     runnable.run();
1116     result = resultOnCompletion;
1117     return true;
1118     }
1119     public void run() { invoke(); }
1120     private static final long serialVersionUID = 5232453952276885070L;
1121     }
1122    
1123     /**
1124     * Adaptor for Callables
1125     */
1126     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1127     implements RunnableFuture<T> {
1128 dl 1.27 final Callable<? extends T> callable;
1129 dl 1.25 T result;
1130 dl 1.27 AdaptedCallable(Callable<? extends T> callable) {
1131 dl 1.25 if (callable == null) throw new NullPointerException();
1132     this.callable = callable;
1133     }
1134     public T getRawResult() { return result; }
1135     public void setRawResult(T v) { result = v; }
1136     public boolean exec() {
1137     try {
1138     result = callable.call();
1139     return true;
1140     } catch (Error err) {
1141     throw err;
1142     } catch (RuntimeException rex) {
1143     throw rex;
1144     } catch (Exception ex) {
1145     throw new RuntimeException(ex);
1146     }
1147     }
1148     public void run() { invoke(); }
1149     private static final long serialVersionUID = 2838392045355241008L;
1150     }
1151 dl 1.18
1152     /**
1153 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1154     * method of the given {@code Runnable} as its action, and returns
1155     * a null result upon {@link #join}.
1156 dl 1.18 *
1157     * @param runnable the runnable action
1158     * @return the task
1159     */
1160 dl 1.27 public static ForkJoinTask<?> adapt(Runnable runnable) {
1161 dl 1.25 return new AdaptedRunnable<Void>(runnable, null);
1162 dl 1.18 }
1163    
1164     /**
1165 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1166     * method of the given {@code Runnable} as its action, and returns
1167     * the given result upon {@link #join}.
1168 dl 1.18 *
1169     * @param runnable the runnable action
1170     * @param result the result upon completion
1171     * @return the task
1172     */
1173     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1174 dl 1.25 return new AdaptedRunnable<T>(runnable, result);
1175 dl 1.18 }
1176    
1177     /**
1178 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1179     * method of the given {@code Callable} as its action, and returns
1180     * its result upon {@link #join}, translating any checked exceptions
1181     * encountered into {@code RuntimeException}.
1182 dl 1.18 *
1183     * @param callable the callable action
1184     * @return the task
1185     */
1186 dl 1.27 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1187 dl 1.25 return new AdaptedCallable<T>(callable);
1188 dl 1.18 }
1189    
1190 dl 1.1 // Serialization support
1191    
1192     private static final long serialVersionUID = -7721805057305804111L;
1193    
1194     /**
1195 jsr166 1.45 * Saves the state to a stream.
1196 dl 1.1 *
1197     * @serialData the current run status and the exception thrown
1198 jsr166 1.23 * during execution, or {@code null} if none
1199 dl 1.1 * @param s the stream
1200     */
1201     private void writeObject(java.io.ObjectOutputStream s)
1202     throws java.io.IOException {
1203     s.defaultWriteObject();
1204     s.writeObject(getException());
1205     }
1206    
1207     /**
1208 jsr166 1.45 * Reconstitutes the instance from a stream.
1209 jsr166 1.10 *
1210 dl 1.1 * @param s the stream
1211     */
1212     private void readObject(java.io.ObjectInputStream s)
1213     throws java.io.IOException, ClassNotFoundException {
1214     s.defaultReadObject();
1215 dl 1.2 status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1216     status |= EXTERNAL_SIGNAL; // conservatively set external signal
1217 dl 1.1 Object ex = s.readObject();
1218     if (ex != null)
1219 jsr166 1.14 setDoneExceptionally((Throwable) ex);
1220 dl 1.1 }
1221    
1222 jsr166 1.22 // Unsafe mechanics
1223    
1224     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1225     private static final long statusOffset =
1226     objectFieldOffset("status", ForkJoinTask.class);
1227    
1228     private static long objectFieldOffset(String field, Class<?> klazz) {
1229     try {
1230     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1231     } catch (NoSuchFieldException e) {
1232     // Convert Exception to corresponding Error
1233     NoSuchFieldError error = new NoSuchFieldError(field);
1234     error.initCause(e);
1235     throw error;
1236     }
1237     }
1238    
1239     /**
1240     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1241     * Replace with a simple call to Unsafe.getUnsafe when integrating
1242     * into a jdk.
1243     *
1244     * @return a sun.misc.Unsafe
1245     */
1246 jsr166 1.16 private static sun.misc.Unsafe getUnsafe() {
1247 jsr166 1.5 try {
1248 jsr166 1.16 return sun.misc.Unsafe.getUnsafe();
1249 jsr166 1.5 } catch (SecurityException se) {
1250     try {
1251     return java.security.AccessController.doPrivileged
1252 jsr166 1.22 (new java.security
1253     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1254 jsr166 1.16 public sun.misc.Unsafe run() throws Exception {
1255 jsr166 1.22 java.lang.reflect.Field f = sun.misc
1256     .Unsafe.class.getDeclaredField("theUnsafe");
1257     f.setAccessible(true);
1258     return (sun.misc.Unsafe) f.get(null);
1259 jsr166 1.5 }});
1260     } catch (java.security.PrivilegedActionException e) {
1261 jsr166 1.16 throw new RuntimeException("Could not initialize intrinsics",
1262     e.getCause());
1263 jsr166 1.5 }
1264     }
1265     }
1266 dl 1.1 }