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.18 by dl, Sat Jul 25 15:50:57 2009 UTC vs.
Revision 1.66 by dl, Sun Oct 24 19:37:26 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines