ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.33
Committed: Tue Aug 4 00:36:45 2009 UTC (14 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.32: +12 -14 lines
Log Message:
Improve cancel specs

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.28 * additionally include RejectedExecutionExceptions stemming from
60     * internal resource exhaustion such as failure to allocate internal
61     * 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 jsr166 1.8 * equivalent to {@code fork(); join()} but always attempts to
72 dl 1.2 * begin execution in the current thread. The "<em>quiet</em>" forms
73     * of these methods do not extract results or report exceptions. These
74     * 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 jsr166 1.28 * <p>The ForkJoinTask class is not usually directly subclassed.
81 dl 1.2 * Instead, you subclass one of the abstract classes that support a
82 dl 1.27 * particular style of fork/join processing, typically {@link
83     * RecursiveAction} for computations that do not return results, or
84     * {@link RecursiveTask} for those that do. Normally, a concrete
85 dl 1.2 * ForkJoinTask subclass declares fields comprising its parameters,
86 jsr166 1.8 * established in a constructor, and then defines a {@code compute}
87 dl 1.2 * method that somehow uses the control methods supplied by this base
88 jsr166 1.8 * class. While these methods have {@code public} access (to allow
89 dl 1.32 * instances of different task subclasses to call each other's
90 dl 1.2 * methods), some of them may only be called from within other
91 dl 1.13 * ForkJoinTasks (as may be determined using method {@link
92     * #inForkJoinPool}). Attempts to invoke them in other contexts
93 jsr166 1.14 * result in exceptions or errors, possibly including
94 dl 1.13 * ClassCastException.
95 dl 1.1 *
96 dl 1.32 * <p>Most base support methods are {@code final}, to prevent
97     * overriding of implementations that are intrinsically tied to the
98     * underlying lightweight task scheduling framework. Developers
99     * creating new basic styles of fork/join processing should minimally
100     * implement {@code protected} methods {@link #exec}, {@link
101     * #setRawResult}, and {@link #getRawResult}, while also introducing
102     * an abstract computational method that can be implemented in its
103     * subclasses, possibly relying on other {@code protected} methods
104     * provided by this class.
105 dl 1.1 *
106     * <p>ForkJoinTasks should perform relatively small amounts of
107 dl 1.32 * computation. Large tasks should be split into smaller subtasks,
108     * usually via recursive decomposition. As a very rough rule of thumb,
109     * a task should perform more than 100 and less than 10000 basic
110     * computational steps. If tasks are too big, then parallelism cannot
111     * improve throughput. If too small, then memory and internal task
112     * maintenance overhead may overwhelm processing.
113 dl 1.1 *
114 dl 1.27 * <p>This class provides {@code adapt} methods for {@link
115     * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
116     * may be of use when mixing execution of ForkJoinTasks with other
117     * kinds of tasks. When all tasks are of this form, consider using a
118     * pool in {@link ForkJoinPool#setAsyncMode}.
119     *
120 dl 1.32 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
121     * used in extensions such as remote execution frameworks. It is
122     * sensible to serialize tasks only before or after, but not during,
123     * execution. Serialization is not relied on during execution itself.
124 jsr166 1.12 *
125     * @since 1.7
126     * @author Doug Lea
127 dl 1.1 */
128     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
129 dl 1.2
130 dl 1.1 /**
131 dl 1.2 * Run control status bits packed into a single int to minimize
132     * footprint and to ensure atomicity (via CAS). Status is
133     * initially zero, and takes on nonnegative values until
134 dl 1.1 * completed, upon which status holds COMPLETED. CANCELLED, or
135     * EXCEPTIONAL, which use the top 3 bits. Tasks undergoing
136     * blocking waits by other threads have SIGNAL_MASK bits set --
137     * bit 15 for external (nonFJ) waits, and the rest a count of
138     * waiting FJ threads. (This representation relies on
139     * ForkJoinPool max thread limits). Completion of a stolen task
140     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
141     * though suboptimal for some purposes, we use basic builtin
142     * wait/notify to take advantage of "monitor inflation" in JVMs
143     * that we would otherwise need to emulate to avoid adding further
144     * per-task bookkeeping overhead. Note that bits 16-28 are
145     * currently unused. Also value 0x80000000 is available as spare
146     * completion value.
147     */
148 jsr166 1.9 volatile int status; // accessed directly by pool and workers
149 dl 1.1
150     static final int COMPLETION_MASK = 0xe0000000;
151     static final int NORMAL = 0xe0000000; // == mask
152     static final int CANCELLED = 0xc0000000;
153     static final int EXCEPTIONAL = 0xa0000000;
154     static final int SIGNAL_MASK = 0x0000ffff;
155     static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
156     static final int EXTERNAL_SIGNAL = 0x00008000; // top bit of low word
157    
158     /**
159     * Table of exceptions thrown by tasks, to enable reporting by
160     * callers. Because exceptions are rare, we don't directly keep
161 jsr166 1.10 * them with task objects, but instead use a weak ref table. Note
162 dl 1.1 * that cancellation exceptions don't appear in the table, but are
163     * instead recorded as status values.
164 jsr166 1.10 * TODO: Use ConcurrentReferenceHashMap
165 dl 1.1 */
166     static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
167     Collections.synchronizedMap
168     (new WeakHashMap<ForkJoinTask<?>, Throwable>());
169    
170     // within-package utilities
171    
172     /**
173 jsr166 1.10 * Gets current worker thread, or null if not a worker thread.
174 dl 1.1 */
175     static ForkJoinWorkerThread getWorker() {
176     Thread t = Thread.currentThread();
177 jsr166 1.14 return ((t instanceof ForkJoinWorkerThread) ?
178     (ForkJoinWorkerThread) t : null);
179 dl 1.1 }
180    
181     final boolean casStatus(int cmp, int val) {
182 jsr166 1.11 return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
183 dl 1.1 }
184    
185     /**
186     * Workaround for not being able to rethrow unchecked exceptions.
187     */
188     static void rethrowException(Throwable ex) {
189     if (ex != null)
190 jsr166 1.11 UNSAFE.throwException(ex);
191 dl 1.1 }
192    
193     // Setting completion status
194    
195     /**
196 jsr166 1.10 * Marks completion and wakes up threads waiting to join this task.
197     *
198 dl 1.1 * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
199     */
200     final void setCompletion(int completion) {
201 dl 1.2 ForkJoinPool pool = getPool();
202 dl 1.1 if (pool != null) {
203     int s; // Clear signal bits while setting completion status
204 jsr166 1.14 do {} while ((s = status) >= 0 && !casStatus(s, completion));
205 dl 1.1
206     if ((s & SIGNAL_MASK) != 0) {
207     if ((s &= INTERNAL_SIGNAL_MASK) != 0)
208     pool.updateRunningCount(s);
209 jsr166 1.14 synchronized (this) { notifyAll(); }
210 dl 1.1 }
211     }
212     else
213     externallySetCompletion(completion);
214     }
215    
216     /**
217     * Version of setCompletion for non-FJ threads. Leaves signal
218     * bits for unblocked threads to adjust, and always notifies.
219     */
220     private void externallySetCompletion(int completion) {
221     int s;
222 jsr166 1.14 do {} while ((s = status) >= 0 &&
223     !casStatus(s, (s & SIGNAL_MASK) | completion));
224     synchronized (this) { notifyAll(); }
225 dl 1.1 }
226    
227     /**
228 jsr166 1.14 * Sets status to indicate normal completion.
229 dl 1.1 */
230     final void setNormalCompletion() {
231     // Try typical fast case -- single CAS, no signal, not already done.
232     // Manually expand casStatus to improve chances of inlining it
233 jsr166 1.11 if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
234 dl 1.1 setCompletion(NORMAL);
235     }
236    
237     // internal waiting and notification
238    
239     /**
240 jsr166 1.14 * Performs the actual monitor wait for awaitDone.
241 dl 1.1 */
242     private void doAwaitDone() {
243     // Minimize lock bias and in/de-flation effects by maximizing
244     // chances of waiting inside sync
245     try {
246     while (status >= 0)
247 jsr166 1.14 synchronized (this) { if (status >= 0) wait(); }
248 dl 1.1 } catch (InterruptedException ie) {
249     onInterruptedWait();
250     }
251     }
252    
253     /**
254 jsr166 1.14 * Performs the actual timed monitor wait for awaitDone.
255 dl 1.1 */
256     private void doAwaitDone(long startTime, long nanos) {
257 jsr166 1.14 synchronized (this) {
258 dl 1.1 try {
259     while (status >= 0) {
260 dl 1.25 long nt = nanos - (System.nanoTime() - startTime);
261 dl 1.1 if (nt <= 0)
262     break;
263 jsr166 1.14 wait(nt / 1000000, (int) (nt % 1000000));
264 dl 1.1 }
265     } catch (InterruptedException ie) {
266     onInterruptedWait();
267     }
268     }
269     }
270    
271     // Awaiting completion
272    
273     /**
274     * Sets status to indicate there is joiner, then waits for join,
275     * surrounded with pool notifications.
276 jsr166 1.10 *
277 dl 1.1 * @return status upon exit
278     */
279 jsr166 1.14 private int awaitDone(ForkJoinWorkerThread w,
280     boolean maintainParallelism) {
281     ForkJoinPool pool = (w == null) ? null : w.pool;
282 dl 1.1 int s;
283     while ((s = status) >= 0) {
284 jsr166 1.14 if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
285 dl 1.1 if (pool == null || !pool.preJoin(this, maintainParallelism))
286     doAwaitDone();
287     if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
288     adjustPoolCountsOnUnblock(pool);
289     break;
290     }
291     }
292     return s;
293     }
294    
295     /**
296     * Timed version of awaitDone
297 jsr166 1.14 *
298 dl 1.1 * @return status upon exit
299     */
300 dl 1.3 private int awaitDone(ForkJoinWorkerThread w, long nanos) {
301 jsr166 1.14 ForkJoinPool pool = (w == null) ? null : w.pool;
302 dl 1.1 int s;
303     while ((s = status) >= 0) {
304 jsr166 1.14 if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
305 dl 1.1 long startTime = System.nanoTime();
306     if (pool == null || !pool.preJoin(this, false))
307     doAwaitDone(startTime, nanos);
308     if ((s = status) >= 0) {
309     adjustPoolCountsOnCancelledWait(pool);
310     s = status;
311     }
312     if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
313     adjustPoolCountsOnUnblock(pool);
314     break;
315     }
316     }
317     return s;
318     }
319    
320     /**
321 jsr166 1.10 * Notifies pool that thread is unblocked. Called by signalled
322 dl 1.1 * threads when woken by non-FJ threads (which is atypical).
323     */
324     private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
325     int s;
326 jsr166 1.14 do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
327 dl 1.1 if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
328     pool.updateRunningCount(s);
329     }
330    
331     /**
332 jsr166 1.10 * Notifies pool to adjust counts on cancelled or timed out wait.
333 dl 1.1 */
334     private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
335     if (pool != null) {
336     int s;
337     while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
338     if (casStatus(s, s - 1)) {
339     pool.updateRunningCount(1);
340     break;
341     }
342     }
343     }
344     }
345    
346 dl 1.2 /**
347 jsr166 1.10 * Handles interruptions during waits.
348 dl 1.2 */
349 dl 1.1 private void onInterruptedWait() {
350 dl 1.2 ForkJoinWorkerThread w = getWorker();
351     if (w == null)
352     Thread.currentThread().interrupt(); // re-interrupt
353     else if (w.isTerminating())
354 dl 1.3 cancelIgnoringExceptions();
355 dl 1.2 // else if FJworker, ignore interrupt
356 dl 1.1 }
357    
358     // Recording and reporting exceptions
359    
360     private void setDoneExceptionally(Throwable rex) {
361     exceptionMap.put(this, rex);
362     setCompletion(EXCEPTIONAL);
363     }
364    
365     /**
366 jsr166 1.10 * Throws the exception associated with status s.
367     *
368 dl 1.1 * @throws the exception
369     */
370     private void reportException(int s) {
371     if ((s &= COMPLETION_MASK) < NORMAL) {
372     if (s == CANCELLED)
373     throw new CancellationException();
374     else
375     rethrowException(exceptionMap.get(this));
376     }
377     }
378    
379     /**
380 jsr166 1.10 * Returns result or throws exception using j.u.c.Future conventions.
381 jsr166 1.14 * Only call when {@code isDone} known to be true.
382 dl 1.1 */
383     private V reportFutureResult()
384     throws ExecutionException, InterruptedException {
385     int s = status & COMPLETION_MASK;
386     if (s < NORMAL) {
387     Throwable ex;
388     if (s == CANCELLED)
389     throw new CancellationException();
390     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
391     throw new ExecutionException(ex);
392     if (Thread.interrupted())
393     throw new InterruptedException();
394     }
395     return getRawResult();
396     }
397    
398     /**
399     * Returns result or throws exception using j.u.c.Future conventions
400 jsr166 1.10 * with timeouts.
401 dl 1.1 */
402     private V reportTimedFutureResult()
403     throws InterruptedException, ExecutionException, TimeoutException {
404     Throwable ex;
405     int s = status & COMPLETION_MASK;
406     if (s == NORMAL)
407     return getRawResult();
408     if (s == CANCELLED)
409     throw new CancellationException();
410     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
411     throw new ExecutionException(ex);
412     if (Thread.interrupted())
413     throw new InterruptedException();
414     throw new TimeoutException();
415     }
416    
417     // internal execution methods
418    
419     /**
420     * Calls exec, recording completion, and rethrowing exception if
421 jsr166 1.10 * encountered. Caller should normally check status before calling.
422     *
423 dl 1.1 * @return true if completed normally
424     */
425     private boolean tryExec() {
426     try { // try block must contain only call to exec
427     if (!exec())
428     return false;
429     } catch (Throwable rex) {
430     setDoneExceptionally(rex);
431     rethrowException(rex);
432     return false; // not reached
433     }
434     setNormalCompletion();
435     return true;
436     }
437    
438     /**
439     * Main execution method used by worker threads. Invokes
440 jsr166 1.10 * base computation unless already complete.
441 dl 1.1 */
442     final void quietlyExec() {
443     if (status >= 0) {
444     try {
445     if (!exec())
446     return;
447 jsr166 1.14 } catch (Throwable rex) {
448 dl 1.1 setDoneExceptionally(rex);
449     return;
450     }
451     setNormalCompletion();
452     }
453     }
454    
455     /**
456 jsr166 1.10 * Calls exec(), recording but not rethrowing exception.
457     * Caller should normally check status before calling.
458     *
459 dl 1.1 * @return true if completed normally
460     */
461     private boolean tryQuietlyInvoke() {
462     try {
463     if (!exec())
464     return false;
465     } catch (Throwable rex) {
466     setDoneExceptionally(rex);
467     return false;
468     }
469     setNormalCompletion();
470     return true;
471     }
472    
473     /**
474 jsr166 1.10 * Cancels, ignoring any exceptions it throws.
475 dl 1.1 */
476 dl 1.3 final void cancelIgnoringExceptions() {
477 dl 1.1 try {
478     cancel(false);
479 jsr166 1.14 } catch (Throwable ignore) {
480 dl 1.1 }
481     }
482    
483 dl 1.3 /**
484     * Main implementation of helpJoin
485     */
486     private int busyJoin(ForkJoinWorkerThread w) {
487     int s;
488     ForkJoinTask<?> t;
489     while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
490     t.quietlyExec();
491 jsr166 1.14 return (s >= 0) ? awaitDone(w, false) : s; // block if no work
492 dl 1.3 }
493    
494 dl 1.1 // public methods
495    
496     /**
497     * Arranges to asynchronously execute this task. While it is not
498     * necessarily enforced, it is a usage error to fork a task more
499 jsr166 1.31 * than once unless it has completed and been reinitialized.
500 dl 1.18 *
501 jsr166 1.31 * <p>This method may be invoked only from within {@code
502     * ForkJoinTask} computations (as may be determined using method
503     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
504     * result in exceptions or errors, possibly including {@code
505     * ClassCastException}.
506     *
507     * @return {@code this}, to simplify usage
508 dl 1.1 */
509 dl 1.18 public final ForkJoinTask<V> fork() {
510 jsr166 1.14 ((ForkJoinWorkerThread) Thread.currentThread())
511     .pushTask(this);
512 dl 1.18 return this;
513 dl 1.1 }
514    
515     /**
516     * Returns the result of the computation when it is ready.
517 jsr166 1.31 * This method differs from {@link #get()} in that
518     * abnormal completion results in {@code RuntimeException} or
519     * {@code Error}, not {@code ExecutionException}.
520 dl 1.1 *
521     * @return the computed result
522     */
523     public final V join() {
524     ForkJoinWorkerThread w = getWorker();
525     if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
526     reportException(awaitDone(w, true));
527     return getRawResult();
528     }
529    
530     /**
531 dl 1.2 * Commences performing this task, awaits its completion if
532     * necessary, and return its result.
533 jsr166 1.10 *
534 dl 1.1 * @throws Throwable (a RuntimeException, Error, or unchecked
535 jsr166 1.10 * exception) if the underlying computation did so
536 dl 1.1 * @return the computed result
537     */
538     public final V invoke() {
539     if (status >= 0 && tryExec())
540     return getRawResult();
541     else
542     return join();
543     }
544    
545     /**
546 jsr166 1.31 * Forks the given tasks, returning when {@code isDone} holds
547     * for each task or an exception is encountered.
548     *
549     * <p>This method may be invoked only from within {@code
550     * ForkJoinTask} computations (as may be determined using method
551     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
552     * result in exceptions or errors, possibly including {@code
553     * ClassCastException}.
554 jsr166 1.10 *
555 dl 1.27 * @param t1 the first task
556     * @param t2 the second task
557     * @throws NullPointerException if any task is null
558     * @throws RuntimeException or Error if a task did so
559 dl 1.1 */
560 jsr166 1.31 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
561 dl 1.2 t2.fork();
562     t1.invoke();
563     t2.join();
564 dl 1.1 }
565    
566     /**
567 dl 1.27 * Forks the given tasks, returning when {@code isDone} holds for
568     * each task or an exception is encountered. If any task
569     * encounters an exception, others may be, but are not guaranteed
570 jsr166 1.31 * to be, cancelled.
571     *
572     * <p>This method may be invoked only from within {@code
573     * ForkJoinTask} computations (as may be determined using method
574     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
575     * result in exceptions or errors, possibly including {@code
576     * ClassCastException}.
577 jsr166 1.14 *
578 dl 1.27 * @param tasks the tasks
579 jsr166 1.10 * @throws NullPointerException if tasks or any element are null
580     * @throws RuntimeException or Error if any task did so
581 dl 1.1 */
582 dl 1.2 public static void invokeAll(ForkJoinTask<?>... tasks) {
583     Throwable ex = null;
584     int last = tasks.length - 1;
585     for (int i = last; i >= 0; --i) {
586     ForkJoinTask<?> t = tasks[i];
587     if (t == null) {
588     if (ex == null)
589     ex = new NullPointerException();
590     }
591     else if (i != 0)
592     t.fork();
593     else {
594     t.quietlyInvoke();
595     if (ex == null)
596     ex = t.getException();
597     }
598     }
599     for (int i = 1; i <= last; ++i) {
600     ForkJoinTask<?> t = tasks[i];
601     if (t != null) {
602     if (ex != null)
603     t.cancel(false);
604     else {
605     t.quietlyJoin();
606     if (ex == null)
607     ex = t.getException();
608     }
609     }
610 dl 1.1 }
611 dl 1.2 if (ex != null)
612     rethrowException(ex);
613 dl 1.1 }
614    
615     /**
616 dl 1.32 * Forks all tasks in the specified collection, returning when
617     * {@code isDone} holds for each task or an exception is
618     * encountered. If any task encounters an exception, others may
619     * be, but are not guaranteed to be, cancelled. The behavior of
620     * this operation is undefined if the specified collection is
621     * modified while the operation is in progress.
622 jsr166 1.31 *
623     * <p>This method may be invoked only from within {@code
624     * ForkJoinTask} computations (as may be determined using method
625     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
626     * result in exceptions or errors, possibly including {@code
627     * ClassCastException}.
628 jsr166 1.10 *
629 dl 1.2 * @param tasks the collection of tasks
630 dl 1.19 * @return the tasks argument, to simplify usage
631 jsr166 1.10 * @throws NullPointerException if tasks or any element are null
632     * @throws RuntimeException or Error if any task did so
633 dl 1.1 */
634 dl 1.19 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
635 dl 1.32 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
636 jsr166 1.14 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
637 dl 1.19 return tasks;
638 dl 1.2 }
639 jsr166 1.15 @SuppressWarnings("unchecked")
640 dl 1.2 List<? extends ForkJoinTask<?>> ts =
641 jsr166 1.14 (List<? extends ForkJoinTask<?>>) tasks;
642 dl 1.2 Throwable ex = null;
643     int last = ts.size() - 1;
644     for (int i = last; i >= 0; --i) {
645     ForkJoinTask<?> t = ts.get(i);
646     if (t == null) {
647     if (ex == null)
648     ex = new NullPointerException();
649     }
650     else if (i != 0)
651     t.fork();
652     else {
653     t.quietlyInvoke();
654     if (ex == null)
655     ex = t.getException();
656     }
657     }
658     for (int i = 1; i <= last; ++i) {
659     ForkJoinTask<?> t = ts.get(i);
660     if (t != null) {
661     if (ex != null)
662     t.cancel(false);
663     else {
664     t.quietlyJoin();
665     if (ex == null)
666     ex = t.getException();
667     }
668     }
669     }
670     if (ex != null)
671     rethrowException(ex);
672 dl 1.19 return tasks;
673 dl 1.1 }
674    
675     /**
676 jsr166 1.23 * Returns {@code true} if the computation performed by this task
677     * has completed (or has been cancelled).
678 jsr166 1.10 *
679 jsr166 1.23 * @return {@code true} if this computation has completed
680 dl 1.1 */
681     public final boolean isDone() {
682     return status < 0;
683     }
684    
685     /**
686 jsr166 1.23 * Returns {@code true} if this task was cancelled.
687 jsr166 1.10 *
688 jsr166 1.23 * @return {@code true} if this task was cancelled
689 dl 1.1 */
690     public final boolean isCancelled() {
691     return (status & COMPLETION_MASK) == CANCELLED;
692     }
693    
694     /**
695 dl 1.33 * Attempts to cancel execution of this task. This attempt will
696     * fail if the task has already completed, has already been
697     * cancelled, or could not be cancelled for some other reason. If
698     * successful, and this task has not started when cancel is
699     * called, execution of this task is suppressed, {@link
700     * #isCancelled} will report true, and {@link #join} will result
701     * in a {@code CancellationException} being thrown.
702 dl 1.1 *
703     * <p>This method may be overridden in subclasses, but if so, must
704     * still ensure that these minimal properties hold. In particular,
705 jsr166 1.29 * the {@code cancel} method itself must not throw exceptions.
706 dl 1.1 *
707 jsr166 1.28 * <p>This method is designed to be invoked by <em>other</em>
708 dl 1.1 * tasks. To terminate the current task, you can just return or
709     * throw an unchecked exception from its computation method, or
710 jsr166 1.24 * invoke {@link #completeExceptionally}.
711 dl 1.1 *
712     * @param mayInterruptIfRunning this value is ignored in the
713 dl 1.33 * default implementation because tasks are not
714 jsr166 1.14 * cancelled via interruption
715 dl 1.1 *
716 jsr166 1.23 * @return {@code true} if this task is now cancelled
717 dl 1.1 */
718     public boolean cancel(boolean mayInterruptIfRunning) {
719     setCompletion(CANCELLED);
720     return (status & COMPLETION_MASK) == CANCELLED;
721     }
722    
723     /**
724 jsr166 1.23 * Returns {@code true} if this task threw an exception or was cancelled.
725 jsr166 1.10 *
726 jsr166 1.23 * @return {@code true} if this task threw an exception or was cancelled
727 dl 1.3 */
728     public final boolean isCompletedAbnormally() {
729     return (status & COMPLETION_MASK) < NORMAL;
730     }
731    
732     /**
733     * Returns the exception thrown by the base computation, or a
734 jsr166 1.29 * {@code CancellationException} if cancelled, or {@code null} if
735     * none or if the method has not yet completed.
736 jsr166 1.10 *
737 jsr166 1.23 * @return the exception, or {@code null} if none
738 dl 1.3 */
739     public final Throwable getException() {
740     int s = status & COMPLETION_MASK;
741     if (s >= NORMAL)
742     return null;
743     if (s == CANCELLED)
744     return new CancellationException();
745     return exceptionMap.get(this);
746     }
747    
748     /**
749 dl 1.1 * Completes this task abnormally, and if not already aborted or
750     * cancelled, causes it to throw the given exception upon
751 jsr166 1.8 * {@code join} and related operations. This method may be used
752 dl 1.1 * to induce exceptions in asynchronous tasks, or to force
753 dl 1.2 * completion of tasks that would not otherwise complete. Its use
754 dl 1.27 * in other situations is discouraged. This method is
755 jsr166 1.8 * overridable, but overridden versions must invoke {@code super}
756 dl 1.2 * implementation to maintain guarantees.
757     *
758 dl 1.1 * @param ex the exception to throw. If this exception is
759     * not a RuntimeException or Error, the actual exception thrown
760     * will be a RuntimeException with cause ex.
761     */
762     public void completeExceptionally(Throwable ex) {
763     setDoneExceptionally((ex instanceof RuntimeException) ||
764 jsr166 1.14 (ex instanceof Error) ? ex :
765 dl 1.1 new RuntimeException(ex));
766     }
767    
768     /**
769     * Completes this task, and if not already aborted or cancelled,
770 jsr166 1.8 * returning a {@code null} result upon {@code join} and related
771 dl 1.1 * operations. This method may be used to provide results for
772     * asynchronous tasks, or to provide alternative handling for
773 dl 1.2 * tasks that would not otherwise complete normally. Its use in
774 dl 1.27 * other situations is discouraged. This method is
775 jsr166 1.8 * overridable, but overridden versions must invoke {@code super}
776 dl 1.2 * implementation to maintain guarantees.
777 dl 1.1 *
778 jsr166 1.10 * @param value the result value for this task
779 dl 1.1 */
780     public void complete(V value) {
781     try {
782     setRawResult(value);
783 jsr166 1.14 } catch (Throwable rex) {
784 dl 1.1 setDoneExceptionally(rex);
785     return;
786     }
787     setNormalCompletion();
788     }
789    
790 dl 1.3 public final V get() throws InterruptedException, ExecutionException {
791     ForkJoinWorkerThread w = getWorker();
792     if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
793     awaitDone(w, true);
794     return reportFutureResult();
795     }
796    
797     public final V get(long timeout, TimeUnit unit)
798     throws InterruptedException, ExecutionException, TimeoutException {
799 dl 1.25 long nanos = unit.toNanos(timeout);
800 dl 1.3 ForkJoinWorkerThread w = getWorker();
801     if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
802 dl 1.25 awaitDone(w, nanos);
803 dl 1.3 return reportTimedFutureResult();
804     }
805    
806 dl 1.1 /**
807 dl 1.2 * Possibly executes other tasks until this task is ready, then
808     * returns the result of the computation. This method may be more
809 jsr166 1.8 * efficient than {@code join}, but is only applicable when
810 jsr166 1.9 * there are no potential dependencies between continuation of the
811 dl 1.2 * current task and that of any other task that might be executed
812     * while helping. (This usually holds for pure divide-and-conquer
813 jsr166 1.31 * tasks).
814     *
815     * <p>This method may be invoked only from within {@code
816     * ForkJoinTask} computations (as may be determined using method
817     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
818     * result in exceptions or errors, possibly including {@code
819     * ClassCastException}.
820 jsr166 1.10 *
821 dl 1.2 * @return the computed result
822     */
823     public final V helpJoin() {
824 jsr166 1.14 ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
825 dl 1.2 if (status < 0 || !w.unpushTask(this) || !tryExec())
826 dl 1.3 reportException(busyJoin(w));
827 dl 1.2 return getRawResult();
828     }
829    
830     /**
831 dl 1.32 * Possibly executes other tasks until this task is ready. This
832     * method may be useful when processing collections of tasks when
833     * some have been cancelled or otherwise known to have aborted.
834 jsr166 1.31 *
835     * <p>This method may be invoked only from within {@code
836     * ForkJoinTask} computations (as may be determined using method
837     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
838     * result in exceptions or errors, possibly including {@code
839     * ClassCastException}.
840 dl 1.2 */
841     public final void quietlyHelpJoin() {
842     if (status >= 0) {
843     ForkJoinWorkerThread w =
844 jsr166 1.14 (ForkJoinWorkerThread) Thread.currentThread();
845 dl 1.2 if (!w.unpushTask(this) || !tryQuietlyInvoke())
846 dl 1.3 busyJoin(w);
847 dl 1.2 }
848     }
849    
850     /**
851     * Joins this task, without returning its result or throwing an
852     * exception. This method may be useful when processing
853     * collections of tasks when some have been cancelled or otherwise
854     * known to have aborted.
855     */
856     public final void quietlyJoin() {
857     if (status >= 0) {
858     ForkJoinWorkerThread w = getWorker();
859     if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
860     awaitDone(w, true);
861     }
862     }
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     if (status >= 0 && !tryQuietlyInvoke())
873     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 jsr166 1.23 * {@link #complete} to become joinable. It may throw exceptions
1026 dl 1.1 * to indicate abnormal exit.
1027 jsr166 1.10 *
1028 jsr166 1.23 * @return {@code true} if completed normally
1029 dl 1.1 * @throws Error or RuntimeException if encountered during computation
1030     */
1031     protected abstract boolean exec();
1032    
1033 dl 1.2 /**
1034 dl 1.25 * Returns, but does not unschedule or execute, a task queued by
1035     * the current thread but not yet executed, if one is immediately
1036 dl 1.6 * available. There is no guarantee that this task will actually
1037 dl 1.25 * be polled or executed next. Conversely, this method may return
1038     * null even if a task exists but cannot be accessed without
1039     * contention with other threads. This method is designed
1040     * primarily to support extensions, and is unlikely to be useful
1041 jsr166 1.31 * otherwise.
1042     *
1043     * <p>This method may be invoked only from within {@code
1044     * ForkJoinTask} computations (as may be determined using method
1045     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1046     * result in exceptions or errors, possibly including {@code
1047     * ClassCastException}.
1048 dl 1.2 *
1049 jsr166 1.23 * @return the next task, or {@code null} if none are available
1050 dl 1.2 */
1051     protected static ForkJoinTask<?> peekNextLocalTask() {
1052 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1053     .peekTask();
1054 dl 1.2 }
1055    
1056     /**
1057 dl 1.6 * Unschedules and returns, without executing, the next task
1058     * queued by the current thread but not yet executed. This method
1059     * is designed primarily to support extensions, and is unlikely to
1060 jsr166 1.31 * be useful otherwise.
1061     *
1062     * <p>This method may be invoked only from within {@code
1063     * ForkJoinTask} computations (as may be determined using method
1064     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1065     * result in exceptions or errors, possibly including {@code
1066     * ClassCastException}.
1067 dl 1.2 *
1068 jsr166 1.23 * @return the next task, or {@code null} if none are available
1069 dl 1.2 */
1070     protected static ForkJoinTask<?> pollNextLocalTask() {
1071 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1072     .pollLocalTask();
1073 dl 1.2 }
1074 jsr166 1.7
1075 dl 1.2 /**
1076 dl 1.6 * Unschedules and returns, without executing, the next task
1077     * queued by the current thread but not yet executed, if one is
1078     * available, or if not available, a task that was forked by some
1079     * other thread, if available. Availability may be transient, so a
1080 jsr166 1.9 * {@code null} result does not necessarily imply quiescence
1081 dl 1.6 * of the pool this task is operating in. This method is designed
1082     * primarily to support extensions, and is unlikely to be useful
1083 jsr166 1.31 * otherwise.
1084     *
1085     * <p>This method may be invoked only from within {@code
1086     * ForkJoinTask} computations (as may be determined using method
1087     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1088     * result in exceptions or errors, possibly including {@code
1089     * ClassCastException}.
1090 dl 1.4 *
1091 jsr166 1.23 * @return a task, or {@code null} if none are available
1092 dl 1.2 */
1093     protected static ForkJoinTask<?> pollTask() {
1094 jsr166 1.14 return ((ForkJoinWorkerThread) Thread.currentThread())
1095     .pollTask();
1096 dl 1.2 }
1097    
1098 dl 1.25 /**
1099     * Adaptor for Runnables. This implements RunnableFuture
1100     * to be compliant with AbstractExecutorService constraints
1101     * when used in ForkJoinPool.
1102     */
1103     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1104     implements RunnableFuture<T> {
1105     final Runnable runnable;
1106     final T resultOnCompletion;
1107     T result;
1108     AdaptedRunnable(Runnable runnable, T result) {
1109     if (runnable == null) throw new NullPointerException();
1110     this.runnable = runnable;
1111     this.resultOnCompletion = result;
1112     }
1113     public T getRawResult() { return result; }
1114     public void setRawResult(T v) { result = v; }
1115     public boolean exec() {
1116     runnable.run();
1117     result = resultOnCompletion;
1118     return true;
1119     }
1120     public void run() { invoke(); }
1121     private static final long serialVersionUID = 5232453952276885070L;
1122     }
1123    
1124     /**
1125     * Adaptor for Callables
1126     */
1127     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1128     implements RunnableFuture<T> {
1129 dl 1.27 final Callable<? extends T> callable;
1130 dl 1.25 T result;
1131 dl 1.27 AdaptedCallable(Callable<? extends T> callable) {
1132 dl 1.25 if (callable == null) throw new NullPointerException();
1133     this.callable = callable;
1134     }
1135     public T getRawResult() { return result; }
1136     public void setRawResult(T v) { result = v; }
1137     public boolean exec() {
1138     try {
1139     result = callable.call();
1140     return true;
1141     } catch (Error err) {
1142     throw err;
1143     } catch (RuntimeException rex) {
1144     throw rex;
1145     } catch (Exception ex) {
1146     throw new RuntimeException(ex);
1147     }
1148     }
1149     public void run() { invoke(); }
1150     private static final long serialVersionUID = 2838392045355241008L;
1151     }
1152 dl 1.18
1153     /**
1154 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1155     * method of the given {@code Runnable} as its action, and returns
1156     * a null result upon {@link #join}.
1157 dl 1.18 *
1158     * @param runnable the runnable action
1159     * @return the task
1160     */
1161 dl 1.27 public static ForkJoinTask<?> adapt(Runnable runnable) {
1162 dl 1.25 return new AdaptedRunnable<Void>(runnable, null);
1163 dl 1.18 }
1164    
1165     /**
1166 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1167     * method of the given {@code Runnable} as its action, and returns
1168     * the given result upon {@link #join}.
1169 dl 1.18 *
1170     * @param runnable the runnable action
1171     * @param result the result upon completion
1172     * @return the task
1173     */
1174     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1175 dl 1.25 return new AdaptedRunnable<T>(runnable, result);
1176 dl 1.18 }
1177    
1178     /**
1179 jsr166 1.31 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1180     * method of the given {@code Callable} as its action, and returns
1181     * its result upon {@link #join}, translating any checked exceptions
1182     * encountered into {@code RuntimeException}.
1183 dl 1.18 *
1184     * @param callable the callable action
1185     * @return the task
1186     */
1187 dl 1.27 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1188 dl 1.25 return new AdaptedCallable<T>(callable);
1189 dl 1.18 }
1190    
1191 dl 1.1 // Serialization support
1192    
1193     private static final long serialVersionUID = -7721805057305804111L;
1194    
1195     /**
1196     * Save the state to a stream.
1197     *
1198     * @serialData the current run status and the exception thrown
1199 jsr166 1.23 * during execution, or {@code null} if none
1200 dl 1.1 * @param s the stream
1201     */
1202     private void writeObject(java.io.ObjectOutputStream s)
1203     throws java.io.IOException {
1204     s.defaultWriteObject();
1205     s.writeObject(getException());
1206     }
1207    
1208     /**
1209     * Reconstitute the instance from a stream.
1210 jsr166 1.10 *
1211 dl 1.1 * @param s the stream
1212     */
1213     private void readObject(java.io.ObjectInputStream s)
1214     throws java.io.IOException, ClassNotFoundException {
1215     s.defaultReadObject();
1216 dl 1.2 status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1217     status |= EXTERNAL_SIGNAL; // conservatively set external signal
1218 dl 1.1 Object ex = s.readObject();
1219     if (ex != null)
1220 jsr166 1.14 setDoneExceptionally((Throwable) ex);
1221 dl 1.1 }
1222    
1223 jsr166 1.22 // Unsafe mechanics
1224    
1225     private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1226     private static final long statusOffset =
1227     objectFieldOffset("status", ForkJoinTask.class);
1228    
1229     private static long objectFieldOffset(String field, Class<?> klazz) {
1230     try {
1231     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1232     } catch (NoSuchFieldException e) {
1233     // Convert Exception to corresponding Error
1234     NoSuchFieldError error = new NoSuchFieldError(field);
1235     error.initCause(e);
1236     throw error;
1237     }
1238     }
1239    
1240     /**
1241     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1242     * Replace with a simple call to Unsafe.getUnsafe when integrating
1243     * into a jdk.
1244     *
1245     * @return a sun.misc.Unsafe
1246     */
1247 jsr166 1.16 private static sun.misc.Unsafe getUnsafe() {
1248 jsr166 1.5 try {
1249 jsr166 1.16 return sun.misc.Unsafe.getUnsafe();
1250 jsr166 1.5 } catch (SecurityException se) {
1251     try {
1252     return java.security.AccessController.doPrivileged
1253 jsr166 1.22 (new java.security
1254     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1255 jsr166 1.16 public sun.misc.Unsafe run() throws Exception {
1256 jsr166 1.22 java.lang.reflect.Field f = sun.misc
1257     .Unsafe.class.getDeclaredField("theUnsafe");
1258     f.setAccessible(true);
1259     return (sun.misc.Unsafe) f.get(null);
1260 jsr166 1.5 }});
1261     } catch (java.security.PrivilegedActionException e) {
1262 jsr166 1.16 throw new RuntimeException("Could not initialize intrinsics",
1263     e.getCause());
1264 jsr166 1.5 }
1265     }
1266     }
1267 dl 1.1 }