ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.27
Committed: Sun Aug 2 11:54:31 2009 UTC (14 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.26: +54 -30 lines
Log Message:
Signature and documentation improvements

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