ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinTask.java (file contents):
Revision 1.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.47 by dl, Sun Apr 18 12:51:18 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines