ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.10
Committed: Wed Aug 12 04:10:59 2009 UTC (14 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.9: +19 -40 lines
Log Message:
sync with jsr166 package

File Contents

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