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.37 by jsr166, Tue Aug 4 20:24:54 2009 UTC vs.
Revision 1.63 by dl, Sat Sep 18 12:10:21 2010 UTC

# Line 7 | Line 7
7   package jsr166y;
8  
9   import java.util.concurrent.*;
10
10   import java.io.Serializable;
11   import java.util.Collection;
12   import java.util.Collections;
# Line 28 | Line 27 | import java.util.WeakHashMap;
27   * start other subtasks.  As indicated by the name of this class,
28   * many programs using {@code ForkJoinTask} employ only methods
29   * {@link #fork} and {@link #join}, or derivatives such as {@link
30 < * #invokeAll}.  However, this class also provides a number of other
31 < * methods that can come into play in advanced usages, as well as
32 < * extension mechanics that allow support of new forms of fork/join
33 < * processing.
30 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
31 > * provides a number of other methods that can come into play in
32 > * advanced usages, as well as extension mechanics that allow
33 > * support of new forms of fork/join processing.
34   *
35   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
36   * The efficiency of {@code ForkJoinTask}s stems from a set of
# Line 56 | Line 55 | import java.util.WeakHashMap;
55   * exceptions such as {@code IOExceptions} to be thrown. However,
56   * computations may still encounter unchecked exceptions, that are
57   * rethrown to callers attempting to join them. These exceptions may
58 < * additionally include RejectedExecutionExceptions stemming from
59 < * internal resource exhaustion such as failure to allocate internal
60 < * task queues.
58 > * additionally include {@link RejectedExecutionException} stemming
59 > * from internal resource exhaustion, such as failure to allocate
60 > * internal task queues.
61   *
62   * <p>The primary method for awaiting completion and extracting
63   * results of a task is {@link #join}, but there are several variants:
64   * The {@link Future#get} methods support interruptible and/or timed
65   * waits for completion and report results using {@code Future}
66 < * 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
66 > * conventions. Method {@link #invoke} is semantically
67   * equivalent to {@code fork(); join()} but always attempts to begin
68   * execution in the current thread. The "<em>quiet</em>" forms of
69   * these methods do not extract results or report exceptions. These
# Line 80 | Line 76 | import java.util.WeakHashMap;
76   * <p>The execution status of tasks may be queried at several levels
77   * of detail: {@link #isDone} is true if a task completed in any way
78   * (including the case where a task was cancelled without executing);
83 * {@link #isCancelled} is true if completion was due to cancellation;
79   * {@link #isCompletedNormally} is true if a task completed without
80 < * cancellation or encountering an exception; {@link
81 < * #isCompletedExceptionally} is true if if the task encountered an
82 < * exception (in which case {@link #getException} returns the
83 < * exception); {@link #isCancelled} is true if the task was cancelled
84 < * (in which case {@link #getException} returns a {@link
85 < * java.util.concurrent.CancellationException}); and {@link
86 < * #isCompletedAbnormally} is true if a task was either cancelled or
92 < * encountered an exception.
80 > * cancellation or encountering an exception; {@link #isCancelled} is
81 > * true if the task was cancelled (in which case {@link #getException}
82 > * returns a {@link java.util.concurrent.CancellationException}); and
83 > * {@link #isCompletedAbnormally} is true if a task was either
84 > * cancelled or encountered an exception, in which case {@link
85 > * #getException} will return either the encountered exception or
86 > * {@link java.util.concurrent.CancellationException}.
87   *
88   * <p>The ForkJoinTask class is not usually directly subclassed.
89   * Instead, you subclass one of the abstract classes that support a
# Line 105 | Line 99 | import java.util.WeakHashMap;
99   * ForkJoinTasks (as may be determined using method {@link
100   * #inForkJoinPool}).  Attempts to invoke them in other contexts
101   * result in exceptions or errors, possibly including
102 < * ClassCastException.
102 > * {@code ClassCastException}.
103   *
104   * <p>Most base support methods are {@code final}, to prevent
105   * overriding of implementations that are intrinsically tied to the
# Line 127 | Line 121 | import java.util.WeakHashMap;
121   *
122   * <p>This class provides {@code adapt} methods for {@link Runnable}
123   * and {@link Callable}, that may be of use when mixing execution of
124 < * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
125 < * are of this form, consider using a pool in
132 < * {@linkplain ForkJoinPool#setAsyncMode async mode}.
124 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
125 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
126   *
127   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
128   * used in extensions such as remote execution frameworks. It is
# Line 141 | Line 134 | import java.util.WeakHashMap;
134   */
135   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
136  
137 <    /**
138 <     * Run control status bits packed into a single int to minimize
139 <     * footprint and to ensure atomicity (via CAS).  Status is
140 <     * initially zero, and takes on nonnegative values until
141 <     * completed, upon which status holds COMPLETED. CANCELLED, or
142 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
143 <     * blocking waits by other threads have SIGNAL_MASK bits set --
144 <     * bit 15 for external (nonFJ) waits, and the rest a count of
145 <     * waiting FJ threads.  (This representation relies on
146 <     * ForkJoinPool max thread limits). Completion of a stolen task
147 <     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
148 <     * though suboptimal for some purposes, we use basic builtin
149 <     * wait/notify to take advantage of "monitor inflation" in JVMs
150 <     * that we would otherwise need to emulate to avoid adding further
151 <     * per-task bookkeeping overhead. Note that bits 16-28 are
152 <     * currently unused. Also value 0x80000000 is available as spare
153 <     * completion value.
137 >    /*
138 >     * See the internal documentation of class ForkJoinPool for a
139 >     * general implementation overview.  ForkJoinTasks are mainly
140 >     * responsible for maintaining their "status" field amidst relays
141 >     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
142 >     * methods of this class are more-or-less layered into (1) basic
143 >     * status maintenance (2) execution and awaiting completion (3)
144 >     * user-level methods that additionally report results. This is
145 >     * sometimes hard to see because this file orders exported methods
146 >     * in a way that flows well in javadocs. In particular, most
147 >     * join mechanics are in method quietlyJoin, below.
148 >     */
149 >
150 >    /*
151 >     * The status field holds run control status bits packed into a
152 >     * single int to minimize footprint and to ensure atomicity (via
153 >     * CAS).  Status is initially zero, and takes on nonnegative
154 >     * values until completed, upon which status holds value
155 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
156 >     * waits by other threads have the SIGNAL bit set.  Completion of
157 >     * a stolen task with SIGNAL set awakens any waiters via
158 >     * notifyAll. Even though suboptimal for some purposes, we use
159 >     * basic builtin wait/notify to take advantage of "monitor
160 >     * inflation" in JVMs that we would otherwise need to emulate to
161 >     * avoid adding further per-task bookkeeping overhead.  We want
162 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
163 >     * techniques, so use some odd coding idioms that tend to avoid
164 >     * them.
165       */
166 +
167 +    /** The run status of this task */
168      volatile int status; // accessed directly by pool and workers
169  
170 <    static final int COMPLETION_MASK      = 0xe0000000;
171 <    static final int NORMAL               = 0xe0000000; // == mask
172 <    static final int CANCELLED            = 0xc0000000;
173 <    static final int EXCEPTIONAL          = 0xa0000000;
168 <    static final int SIGNAL_MASK          = 0x0000ffff;
169 <    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
170 <    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
170 >    private static final int NORMAL      = -1;
171 >    private static final int CANCELLED   = -2;
172 >    private static final int EXCEPTIONAL = -3;
173 >    private static final int SIGNAL      =  1;
174  
175      /**
176       * Table of exceptions thrown by tasks, to enable reporting by
# Line 181 | Line 184 | public abstract class ForkJoinTask<V> im
184          Collections.synchronizedMap
185          (new WeakHashMap<ForkJoinTask<?>, Throwable>());
186  
187 <    // within-package utilities
185 <
186 <    /**
187 <     * Gets current worker thread, or null if not a worker thread.
188 <     */
189 <    static ForkJoinWorkerThread getWorker() {
190 <        Thread t = Thread.currentThread();
191 <        return ((t instanceof ForkJoinWorkerThread) ?
192 <                (ForkJoinWorkerThread) t : null);
193 <    }
194 <
195 <    final boolean casStatus(int cmp, int val) {
196 <        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
197 <    }
187 >    // Maintaining completion status
188  
189      /**
190 <     * Workaround for not being able to rethrow unchecked exceptions.
191 <     */
202 <    static void rethrowException(Throwable ex) {
203 <        if (ex != null)
204 <            UNSAFE.throwException(ex);
205 <    }
206 <
207 <    // Setting completion status
208 <
209 <    /**
210 <     * Marks completion and wakes up threads waiting to join this task.
190 >     * Marks completion and wakes up threads waiting to join this task,
191 >     * also clearing signal request bits.
192       *
193       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
194       */
195 <    final void setCompletion(int completion) {
196 <        ForkJoinPool pool = getPool();
197 <        if (pool != null) {
198 <            int s; // Clear signal bits while setting completion status
199 <            do {} while ((s = status) >= 0 && !casStatus(s, completion));
200 <
201 <            if ((s & SIGNAL_MASK) != 0) {
221 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
222 <                    pool.updateRunningCount(s);
223 <                synchronized (this) { notifyAll(); }
195 >    private void setCompletion(int completion) {
196 >        int s;
197 >        while ((s = status) >= 0) {
198 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
199 >                if (s != 0)
200 >                    synchronized (this) { notifyAll(); }
201 >                break;
202              }
203          }
226        else
227            externallySetCompletion(completion);
204      }
205  
206      /**
207 <     * Version of setCompletion for non-FJ threads.  Leaves signal
208 <     * bits for unblocked threads to adjust, and always notifies.
209 <     */
234 <    private void externallySetCompletion(int completion) {
235 <        int s;
236 <        do {} while ((s = status) >= 0 &&
237 <                     !casStatus(s, (s & SIGNAL_MASK) | completion));
238 <        synchronized (this) { notifyAll(); }
239 <    }
240 <
241 <    /**
242 <     * Sets status to indicate normal completion.
243 <     */
244 <    final void setNormalCompletion() {
245 <        // Try typical fast case -- single CAS, no signal, not already done.
246 <        // Manually expand casStatus to improve chances of inlining it
247 <        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
248 <            setCompletion(NORMAL);
249 <    }
250 <
251 <    // internal waiting and notification
252 <
253 <    /**
254 <     * Performs the actual monitor wait for awaitDone.
207 >     * Records exception and sets exceptional completion.
208 >     *
209 >     * @return status on exit
210       */
211 <    private void doAwaitDone() {
212 <        // Minimize lock bias and in/de-flation effects by maximizing
213 <        // chances of waiting inside sync
259 <        try {
260 <            while (status >= 0)
261 <                synchronized (this) { if (status >= 0) wait(); }
262 <        } catch (InterruptedException ie) {
263 <            onInterruptedWait();
264 <        }
211 >    private void setExceptionalCompletion(Throwable rex) {
212 >        exceptionMap.put(this, rex);
213 >        setCompletion(EXCEPTIONAL);
214      }
215  
216      /**
217 <     * Performs the actual timed monitor wait for awaitDone.
217 >     * Blocks a worker thread until completion. Called only by
218 >     * pool. Currently unused -- pool-based waits use timeout
219 >     * version below.
220       */
221 <    private void doAwaitDone(long startTime, long nanos) {
222 <        synchronized (this) {
221 >    final void internalAwaitDone() {
222 >        int s;         // the odd construction reduces lock bias effects
223 >        while ((s = status) >= 0) {
224              try {
225 <                while (status >= 0) {
226 <                    long nt = nanos - (System.nanoTime() - startTime);
227 <                    if (nt <= 0)
276 <                        break;
277 <                    wait(nt / 1000000, (int) (nt % 1000000));
225 >                synchronized (this) {
226 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
227 >                        wait();
228                  }
229              } catch (InterruptedException ie) {
230 <                onInterruptedWait();
281 <            }
282 <        }
283 <    }
284 <
285 <    // Awaiting completion
286 <
287 <    /**
288 <     * Sets status to indicate there is joiner, then waits for join,
289 <     * surrounded with pool notifications.
290 <     *
291 <     * @return status upon exit
292 <     */
293 <    private int awaitDone(ForkJoinWorkerThread w,
294 <                          boolean maintainParallelism) {
295 <        ForkJoinPool pool = (w == null) ? null : w.pool;
296 <        int s;
297 <        while ((s = status) >= 0) {
298 <            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
299 <                if (pool == null || !pool.preJoin(this, maintainParallelism))
300 <                    doAwaitDone();
301 <                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
302 <                    adjustPoolCountsOnUnblock(pool);
303 <                break;
230 >                cancelIfTerminating();
231              }
232          }
306        return s;
233      }
234  
235      /**
236 <     * Timed version of awaitDone
236 >     * Blocks a worker thread until completed or timed out.  Called
237 >     * only by pool.
238       *
239 <     * @return status upon exit
239 >     * @return status on exit
240       */
241 <    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
315 <        ForkJoinPool pool = (w == null) ? null : w.pool;
241 >    final int internalAwaitDone(long millis) {
242          int s;
243 <        while ((s = status) >= 0) {
244 <            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
245 <                long startTime = System.nanoTime();
246 <                if (pool == null || !pool.preJoin(this, false))
247 <                    doAwaitDone(startTime, nanos);
322 <                if ((s = status) >= 0) {
323 <                    adjustPoolCountsOnCancelledWait(pool);
324 <                    s = status;
243 >        if ((s = status) >= 0) {
244 >            try {
245 >                synchronized (this) {
246 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
247 >                        wait(millis, 0);
248                  }
249 <                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
250 <                    adjustPoolCountsOnUnblock(pool);
328 <                break;
249 >            } catch (InterruptedException ie) {
250 >                cancelIfTerminating();
251              }
252 +            s = status;
253          }
254          return s;
255      }
256  
257      /**
258 <     * Notifies pool that thread is unblocked. Called by signalled
336 <     * threads when woken by non-FJ threads (which is atypical).
258 >     * Blocks a non-worker-thread until completion.
259       */
260 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
260 >    private void externalAwaitDone() {
261          int s;
262 <        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
263 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
264 <            pool.updateRunningCount(s);
265 <    }
266 <
267 <    /**
268 <     * Notifies pool to adjust counts on cancelled or timed out wait.
269 <     */
270 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
271 <        if (pool != null) {
272 <            int s;
273 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
274 <                if (casStatus(s, s - 1)) {
353 <                    pool.updateRunningCount(1);
262 >        while ((s = status) >= 0) {
263 >            synchronized (this) {
264 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
265 >                    boolean interrupted = false;
266 >                    while (status >= 0) {
267 >                        try {
268 >                            wait();
269 >                        } catch (InterruptedException ie) {
270 >                            interrupted = true;
271 >                        }
272 >                    }
273 >                    if (interrupted)
274 >                        Thread.currentThread().interrupt();
275                      break;
276                  }
277              }
# Line 358 | Line 279 | public abstract class ForkJoinTask<V> im
279      }
280  
281      /**
282 <     * Handles interruptions during waits.
283 <     */
284 <    private void onInterruptedWait() {
364 <        ForkJoinWorkerThread w = getWorker();
365 <        if (w == null)
366 <            Thread.currentThread().interrupt(); // re-interrupt
367 <        else if (w.isTerminating())
368 <            cancelIgnoringExceptions();
369 <        // else if FJworker, ignore interrupt
370 <    }
371 <
372 <    // Recording and reporting exceptions
373 <
374 <    private void setDoneExceptionally(Throwable rex) {
375 <        exceptionMap.put(this, rex);
376 <        setCompletion(EXCEPTIONAL);
377 <    }
378 <
379 <    /**
380 <     * Throws the exception associated with status s.
381 <     *
382 <     * @throws the exception
383 <     */
384 <    private void reportException(int s) {
385 <        if ((s &= COMPLETION_MASK) < NORMAL) {
386 <            if (s == CANCELLED)
387 <                throw new CancellationException();
388 <            else
389 <                rethrowException(exceptionMap.get(this));
390 <        }
391 <    }
392 <
393 <    /**
394 <     * Returns result or throws exception using j.u.c.Future conventions.
395 <     * Only call when {@code isDone} known to be true.
396 <     */
397 <    private V reportFutureResult()
398 <        throws InterruptedException, ExecutionException {
399 <        if (Thread.interrupted())
400 <            throw new InterruptedException();
401 <        int s = status & COMPLETION_MASK;
402 <        if (s < NORMAL) {
403 <            Throwable ex;
404 <            if (s == CANCELLED)
405 <                throw new CancellationException();
406 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
407 <                throw new ExecutionException(ex);
408 <        }
409 <        return getRawResult();
410 <    }
411 <
412 <    /**
413 <     * Returns result or throws exception using j.u.c.Future conventions
414 <     * with timeouts.
415 <     */
416 <    private V reportTimedFutureResult()
417 <        throws InterruptedException, ExecutionException, TimeoutException {
418 <        if (Thread.interrupted())
419 <            throw new InterruptedException();
420 <        Throwable ex;
421 <        int s = status & COMPLETION_MASK;
422 <        if (s == NORMAL)
423 <            return getRawResult();
424 <        else if (s == CANCELLED)
425 <            throw new CancellationException();
426 <        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
427 <            throw new ExecutionException(ex);
428 <        else
429 <            throw new TimeoutException();
430 <    }
431 <
432 <    // internal execution methods
433 <
434 <    /**
435 <     * Calls exec, recording completion, and rethrowing exception if
436 <     * encountered. Caller should normally check status before calling.
437 <     *
438 <     * @return true if completed normally
439 <     */
440 <    private boolean tryExec() {
441 <        try { // try block must contain only call to exec
442 <            if (!exec())
443 <                return false;
444 <        } catch (Throwable rex) {
445 <            setDoneExceptionally(rex);
446 <            rethrowException(rex);
447 <            return false; // not reached
448 <        }
449 <        setNormalCompletion();
450 <        return true;
451 <    }
452 <
453 <    /**
454 <     * Main execution method used by worker threads. Invokes
455 <     * base computation unless already complete.
282 >     * Unless done, calls exec and records status if completed, but
283 >     * doesn't wait for completion otherwise. Primary execution method
284 >     * for ForkJoinWorkerThread.
285       */
286      final void quietlyExec() {
458        if (status >= 0) {
459            try {
460                if (!exec())
461                    return;
462            } catch (Throwable rex) {
463                setDoneExceptionally(rex);
464                return;
465            }
466            setNormalCompletion();
467        }
468    }
469
470    /**
471     * Calls exec(), recording but not rethrowing exception.
472     * Caller should normally check status before calling.
473     *
474     * @return true if completed normally
475     */
476    private boolean tryQuietlyInvoke() {
287          try {
288 <            if (!exec())
289 <                return false;
288 >            if (status < 0 || !exec())
289 >                return;
290          } catch (Throwable rex) {
291 <            setDoneExceptionally(rex);
292 <            return false;
483 <        }
484 <        setNormalCompletion();
485 <        return true;
486 <    }
487 <
488 <    /**
489 <     * Cancels, ignoring any exceptions it throws.
490 <     */
491 <    final void cancelIgnoringExceptions() {
492 <        try {
493 <            cancel(false);
494 <        } catch (Throwable ignore) {
291 >            setExceptionalCompletion(rex);
292 >            return;
293          }
294 <    }
497 <
498 <    /**
499 <     * Main implementation of helpJoin
500 <     */
501 <    private int busyJoin(ForkJoinWorkerThread w) {
502 <        int s;
503 <        ForkJoinTask<?> t;
504 <        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
505 <            t.quietlyExec();
506 <        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
294 >        setCompletion(NORMAL); // must be outside try block
295      }
296  
297      // public methods
# Line 512 | Line 300 | public abstract class ForkJoinTask<V> im
300       * Arranges to asynchronously execute this task.  While it is not
301       * necessarily enforced, it is a usage error to fork a task more
302       * than once unless it has completed and been reinitialized.
303 +     * Subsequent modifications to the state of this task or any data
304 +     * it operates on are not necessarily consistently observable by
305 +     * any thread other than the one executing it unless preceded by a
306 +     * call to {@link #join} or related methods, or a call to {@link
307 +     * #isDone} returning {@code true}.
308       *
309       * <p>This method may be invoked only from within {@code
310       * ForkJoinTask} computations (as may be determined using method
# Line 528 | Line 321 | public abstract class ForkJoinTask<V> im
321      }
322  
323      /**
324 <     * Returns the result of the computation when it is ready.
324 >     * Returns the result of the computation when it {@link #isDone is done}.
325       * This method differs from {@link #get()} in that
326       * abnormal completion results in {@code RuntimeException} or
327       * {@code Error}, not {@code ExecutionException}.
# Line 536 | Line 329 | public abstract class ForkJoinTask<V> im
329       * @return the computed result
330       */
331      public final V join() {
332 <        ForkJoinWorkerThread w = getWorker();
333 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
334 <            reportException(awaitDone(w, true));
332 >        quietlyJoin();
333 >        Throwable ex;
334 >        if (status < NORMAL && (ex = getException()) != null)
335 >            UNSAFE.throwException(ex);
336          return getRawResult();
337      }
338  
339      /**
340       * Commences performing this task, awaits its completion if
341 <     * necessary, and return its result, or throws an (unchecked)
342 <     * exception if the underlying computation did so.
341 >     * necessary, and returns its result, or throws an (unchecked)
342 >     * {@code RuntimeException} or {@code Error} if the underlying
343 >     * computation did so.
344       *
345       * @return the computed result
346       */
347      public final V invoke() {
348 <        if (status >= 0 && tryExec())
349 <            return getRawResult();
350 <        else
351 <            return join();
348 >        quietlyInvoke();
349 >        Throwable ex;
350 >        if (status < NORMAL && (ex = getException()) != null)
351 >            UNSAFE.throwException(ex);
352 >        return getRawResult();
353      }
354  
355      /**
356       * Forks the given tasks, returning when {@code isDone} holds for
357       * each task or an (unchecked) exception is encountered, in which
358 <     * case the exception is rethrown.  If more than one task
358 >     * case the exception is rethrown. If more than one task
359       * encounters an exception, then this method throws any one of
360 <     * these exceptions.  The individual status of each task may be
361 <     * checked using {@link #getException()} and related methods.
360 >     * these exceptions. If any task encounters an exception, the
361 >     * other may be cancelled. However, the execution status of
362 >     * individual tasks is not guaranteed upon exceptional return. The
363 >     * status of each task may be obtained using {@link
364 >     * #getException()} and related methods to check if they have been
365 >     * cancelled, completed normally or exceptionally, or left
366 >     * unprocessed.
367       *
368       * <p>This method may be invoked only from within {@code
369       * ForkJoinTask} computations (as may be determined using method
# Line 583 | Line 384 | public abstract class ForkJoinTask<V> im
384      /**
385       * Forks the given tasks, returning when {@code isDone} holds for
386       * each task or an (unchecked) exception is encountered, in which
387 <     * case the exception is rethrown. If any task encounters an
388 <     * exception, others may be, but are not guaranteed to be,
389 <     * cancelled.  If more than one task encounters an exception, then
390 <     * this method throws any one of these exceptions.  The individual
391 <     * status of each task may be checked using {@link #getException()}
392 <     * and related methods.
387 >     * case the exception is rethrown. If more than one task
388 >     * encounters an exception, then this method throws any one of
389 >     * these exceptions. If any task encounters an exception, others
390 >     * may be cancelled. However, the execution status of individual
391 >     * tasks is not guaranteed upon exceptional return. The status of
392 >     * each task may be obtained using {@link #getException()} and
393 >     * related methods to check if they have been cancelled, completed
394 >     * normally or exceptionally, or left unprocessed.
395       *
396       * <p>This method may be invoked only from within {@code
397       * ForkJoinTask} computations (as may be determined using method
# Line 612 | Line 415 | public abstract class ForkJoinTask<V> im
415                  t.fork();
416              else {
417                  t.quietlyInvoke();
418 <                if (ex == null)
418 >                if (ex == null && t.status < NORMAL)
419                      ex = t.getException();
420              }
421          }
# Line 623 | Line 426 | public abstract class ForkJoinTask<V> im
426                      t.cancel(false);
427                  else {
428                      t.quietlyJoin();
429 <                    if (ex == null)
429 >                    if (ex == null && t.status < NORMAL)
430                          ex = t.getException();
431                  }
432              }
433          }
434          if (ex != null)
435 <            rethrowException(ex);
435 >            UNSAFE.throwException(ex);
436      }
437  
438      /**
439       * Forks all tasks in the specified collection, returning when
440       * {@code isDone} holds for each task or an (unchecked) exception
441 <     * is encountered.  If any task encounters an exception, others
442 <     * may be, but are not guaranteed to be, cancelled.  If more than
443 <     * one task encounters an exception, then this method throws any
444 <     * one of these exceptions.  The individual status of each task
445 <     * may be checked using {@link #getException()} and related
446 <     * methods.  The behavior of this operation is undefined if the
447 <     * specified collection is modified while the operation is in
448 <     * progress.
441 >     * is encountered, in which case the exception is rethrown. If
442 >     * more than one task encounters an exception, then this method
443 >     * throws any one of these exceptions. If any task encounters an
444 >     * exception, others may be cancelled. However, the execution
445 >     * status of individual tasks is not guaranteed upon exceptional
446 >     * return. The status of each task may be obtained using {@link
447 >     * #getException()} and related methods to check if they have been
448 >     * cancelled, completed normally or exceptionally, or left
449 >     * unprocessed.
450       *
451       * <p>This method may be invoked only from within {@code
452       * ForkJoinTask} computations (as may be determined using method
# Line 674 | Line 478 | public abstract class ForkJoinTask<V> im
478                  t.fork();
479              else {
480                  t.quietlyInvoke();
481 <                if (ex == null)
481 >                if (ex == null && t.status < NORMAL)
482                      ex = t.getException();
483              }
484          }
# Line 685 | Line 489 | public abstract class ForkJoinTask<V> im
489                      t.cancel(false);
490                  else {
491                      t.quietlyJoin();
492 <                    if (ex == null)
492 >                    if (ex == null && t.status < NORMAL)
493                          ex = t.getException();
494                  }
495              }
496          }
497          if (ex != null)
498 <            rethrowException(ex);
498 >            UNSAFE.throwException(ex);
499          return tasks;
500      }
501  
# Line 721 | Line 525 | public abstract class ForkJoinTask<V> im
525       */
526      public boolean cancel(boolean mayInterruptIfRunning) {
527          setCompletion(CANCELLED);
528 <        return (status & COMPLETION_MASK) == CANCELLED;
528 >        return status == CANCELLED;
529      }
530  
531      /**
532 <     * Returns {@code true} if the computation performed by this task
533 <     * has completed (or has been cancelled).
534 <     *
535 <     * @return {@code true} if this computation has completed
532 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
533 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
534 >     * exceptions, but if it does anyway, we have no recourse during
535 >     * shutdown, so guard against this case.
536       */
537 <    public final boolean isDone() {
538 <        return status < 0;
537 >    final void cancelIgnoringExceptions() {
538 >        try {
539 >            cancel(false);
540 >        } catch (Throwable ignore) {
541 >        }
542      }
543  
544      /**
545 <     * Returns {@code true} if this task was cancelled.
546 <     *
740 <     * @return {@code true} if this task was cancelled
545 >     * Cancels if current thread is a terminating worker thread,
546 >     * ignoring any exceptions thrown by cancel.
547       */
548 +    final void cancelIfTerminating() {
549 +        Thread t = Thread.currentThread();
550 +        if ((t instanceof ForkJoinWorkerThread) &&
551 +            ((ForkJoinWorkerThread) t).isTerminating()) {
552 +            try {
553 +                cancel(false);
554 +            } catch (Throwable ignore) {
555 +            }
556 +        }
557 +    }
558 +
559 +    public final boolean isDone() {
560 +        return status < 0;
561 +    }
562 +
563      public final boolean isCancelled() {
564 <        return (status & COMPLETION_MASK) == CANCELLED;
564 >        return status == CANCELLED;
565      }
566  
567      /**
# Line 749 | Line 570 | public abstract class ForkJoinTask<V> im
570       * @return {@code true} if this task threw an exception or was cancelled
571       */
572      public final boolean isCompletedAbnormally() {
573 <        return (status & COMPLETION_MASK) < NORMAL;
573 >        return status < NORMAL;
574      }
575  
576      /**
# Line 760 | Line 581 | public abstract class ForkJoinTask<V> im
581       * exception and was not cancelled
582       */
583      public final boolean isCompletedNormally() {
584 <        return (status & COMPLETION_MASK) == NORMAL;
764 <    }
765 <
766 <    /**
767 <     * Returns {@code true} if this task threw an exception.
768 <     *
769 <     * @return {@code true} if this task threw an exception
770 <     */
771 <    public final boolean isCompletedExceptionally() {
772 <        return (status & COMPLETION_MASK) == EXCEPTIONAL;
584 >        return status == NORMAL;
585      }
586  
587      /**
# Line 780 | Line 592 | public abstract class ForkJoinTask<V> im
592       * @return the exception, or {@code null} if none
593       */
594      public final Throwable getException() {
595 <        int s = status & COMPLETION_MASK;
595 >        int s = status;
596          return ((s >= NORMAL)    ? null :
597                  (s == CANCELLED) ? new CancellationException() :
598                  exceptionMap.get(this));
# Line 796 | Line 608 | public abstract class ForkJoinTask<V> im
608       * overridable, but overridden versions must invoke {@code super}
609       * implementation to maintain guarantees.
610       *
611 <     * @param ex the exception to throw. If this exception is
612 <     * not a RuntimeException or Error, the actual exception thrown
613 <     * will be a RuntimeException with cause ex.
611 >     * @param ex the exception to throw. If this exception is not a
612 >     * {@code RuntimeException} or {@code Error}, the actual exception
613 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
614       */
615      public void completeExceptionally(Throwable ex) {
616 <        setDoneExceptionally((ex instanceof RuntimeException) ||
617 <                             (ex instanceof Error) ? ex :
618 <                             new RuntimeException(ex));
616 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
617 >                                 (ex instanceof Error) ? ex :
618 >                                 new RuntimeException(ex));
619      }
620  
621      /**
622       * Completes this task, and if not already aborted or cancelled,
623 <     * returning a {@code null} result upon {@code join} and related
624 <     * operations. This method may be used to provide results for
625 <     * asynchronous tasks, or to provide alternative handling for
626 <     * tasks that would not otherwise complete normally. Its use in
627 <     * other situations is discouraged. This method is
628 <     * overridable, but overridden versions must invoke {@code super}
629 <     * implementation to maintain guarantees.
623 >     * returning the given value as the result of subsequent
624 >     * invocations of {@code join} and related operations. This method
625 >     * may be used to provide results for asynchronous tasks, or to
626 >     * provide alternative handling for tasks that would not otherwise
627 >     * complete normally. Its use in other situations is
628 >     * discouraged. This method is overridable, but overridden
629 >     * versions must invoke {@code super} implementation to maintain
630 >     * guarantees.
631       *
632       * @param value the result value for this task
633       */
# Line 822 | Line 635 | public abstract class ForkJoinTask<V> im
635          try {
636              setRawResult(value);
637          } catch (Throwable rex) {
638 <            setDoneExceptionally(rex);
638 >            setExceptionalCompletion(rex);
639              return;
640          }
641 <        setNormalCompletion();
829 <    }
830 <
831 <    public final V get() throws InterruptedException, ExecutionException {
832 <        ForkJoinWorkerThread w = getWorker();
833 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
834 <            awaitDone(w, true);
835 <        return reportFutureResult();
836 <    }
837 <
838 <    public final V get(long timeout, TimeUnit unit)
839 <        throws InterruptedException, ExecutionException, TimeoutException {
840 <        long nanos = unit.toNanos(timeout);
841 <        ForkJoinWorkerThread w = getWorker();
842 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
843 <            awaitDone(w, nanos);
844 <        return reportTimedFutureResult();
641 >        setCompletion(NORMAL);
642      }
643  
644      /**
645 <     * Possibly executes other tasks until this task is ready, then
646 <     * returns the result of the computation.  This method may be more
850 <     * efficient than {@code join}, but is only applicable when
851 <     * there are no potential dependencies between continuation of the
852 <     * current task and that of any other task that might be executed
853 <     * while helping. (This usually holds for pure divide-and-conquer
854 <     * tasks).
855 <     *
856 <     * <p>This method may be invoked only from within {@code
857 <     * ForkJoinTask} computations (as may be determined using method
858 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
859 <     * result in exceptions or errors, possibly including {@code
860 <     * ClassCastException}.
645 >     * Waits if necessary for the computation to complete, and then
646 >     * retrieves its result.
647       *
648       * @return the computed result
649 +     * @throws CancellationException if the computation was cancelled
650 +     * @throws ExecutionException if the computation threw an
651 +     * exception
652 +     * @throws InterruptedException if the current thread is not a
653 +     * member of a ForkJoinPool and was interrupted while waiting
654       */
655 <    public final V helpJoin() {
656 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
657 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
658 <            reportException(busyJoin(w));
655 >    public final V get() throws InterruptedException, ExecutionException {
656 >        int s;
657 >        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
658 >            quietlyJoin();
659 >            s = status;
660 >        }
661 >        else {
662 >            while ((s = status) >= 0) {
663 >                synchronized (this) { // interruptible form of awaitDone
664 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
665 >                                                 s, SIGNAL)) {
666 >                        while (status >= 0)
667 >                            wait();
668 >                    }
669 >                }
670 >            }
671 >        }
672 >        if (s < NORMAL) {
673 >            Throwable ex;
674 >            if (s == CANCELLED)
675 >                throw new CancellationException();
676 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
677 >                throw new ExecutionException(ex);
678 >        }
679          return getRawResult();
680      }
681  
682      /**
683 <     * Possibly executes other tasks until this task is ready.  This
684 <     * method may be useful when processing collections of tasks when
874 <     * some have been cancelled or otherwise known to have aborted.
683 >     * Waits if necessary for at most the given time for the computation
684 >     * to complete, and then retrieves its result, if available.
685       *
686 <     * <p>This method may be invoked only from within {@code
687 <     * ForkJoinTask} computations (as may be determined using method
688 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
689 <     * result in exceptions or errors, possibly including {@code
690 <     * ClassCastException}.
686 >     * @param timeout the maximum time to wait
687 >     * @param unit the time unit of the timeout argument
688 >     * @return the computed result
689 >     * @throws CancellationException if the computation was cancelled
690 >     * @throws ExecutionException if the computation threw an
691 >     * exception
692 >     * @throws InterruptedException if the current thread is not a
693 >     * member of a ForkJoinPool and was interrupted while waiting
694 >     * @throws TimeoutException if the wait timed out
695       */
696 <    public final void quietlyHelpJoin() {
697 <        if (status >= 0) {
698 <            ForkJoinWorkerThread w =
699 <                (ForkJoinWorkerThread) Thread.currentThread();
700 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
701 <                busyJoin(w);
696 >    public final V get(long timeout, TimeUnit unit)
697 >        throws InterruptedException, ExecutionException, TimeoutException {
698 >        Thread t = Thread.currentThread();
699 >        ForkJoinPool pool;
700 >        if (t instanceof ForkJoinWorkerThread) {
701 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
702 >            if (status >= 0 && w.unpushTask(this))
703 >                quietlyExec();
704 >            pool = w.pool;
705 >        }
706 >        else
707 >            pool = null;
708 >        /*
709 >         * Timed wait loop intermixes cases for FJ (pool != null) and
710 >         * non FJ threads. For FJ, decrement pool count but don't try
711 >         * for replacement; increment count on completion. For non-FJ,
712 >         * deal with interrupts. This is messy, but a little less so
713 >         * than is splitting the FJ and nonFJ cases.
714 >         */
715 >        boolean interrupted = false;
716 >        boolean dec = false; // true if pool count decremented
717 >        long nanos = unit.toNanos(timeout);
718 >        for (;;) {
719 >            if (pool == null && Thread.interrupted()) {
720 >                interrupted = true;
721 >                break;
722 >            }
723 >            int s = status;
724 >            if (s < 0)
725 >                break;
726 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
727 >                long startTime = System.nanoTime();
728 >                long nt; // wait time
729 >                while (status >= 0 &&
730 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
731 >                    if (pool != null && !dec)
732 >                        dec = pool.tryDecrementRunningCount();
733 >                    else {
734 >                        long ms = nt / 1000000;
735 >                        int ns = (int) (nt % 1000000);
736 >                        try {
737 >                            synchronized (this) {
738 >                                if (status >= 0)
739 >                                    wait(ms, ns);
740 >                            }
741 >                        } catch (InterruptedException ie) {
742 >                            if (pool != null)
743 >                                cancelIfTerminating();
744 >                            else {
745 >                                interrupted = true;
746 >                                break;
747 >                            }
748 >                        }
749 >                    }
750 >                }
751 >                break;
752 >            }
753          }
754 +        if (pool != null && dec)
755 +            pool.incrementRunningCount();
756 +        if (interrupted)
757 +            throw new InterruptedException();
758 +        int es = status;
759 +        if (es != NORMAL) {
760 +            Throwable ex;
761 +            if (es == CANCELLED)
762 +                throw new CancellationException();
763 +            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
764 +                throw new ExecutionException(ex);
765 +            throw new TimeoutException();
766 +        }
767 +        return getRawResult();
768      }
769  
770      /**
771 <     * Joins this task, without returning its result or throwing an
771 >     * Joins this task, without returning its result or throwing its
772       * exception. This method may be useful when processing
773       * collections of tasks when some have been cancelled or otherwise
774       * known to have aborted.
775       */
776      public final void quietlyJoin() {
777 <        if (status >= 0) {
778 <            ForkJoinWorkerThread w = getWorker();
779 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
780 <                awaitDone(w, true);
777 >        Thread t;
778 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
779 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
780 >            if (status >= 0) {
781 >                if (w.unpushTask(this)) {
782 >                    boolean completed;
783 >                    try {
784 >                        completed = exec();
785 >                    } catch (Throwable rex) {
786 >                        setExceptionalCompletion(rex);
787 >                        return;
788 >                    }
789 >                    if (completed) {
790 >                        setCompletion(NORMAL);
791 >                        return;
792 >                    }
793 >                }
794 >                w.joinTask(this);
795 >            }
796          }
797 +        else
798 +            externalAwaitDone();
799      }
800  
801      /**
802       * Commences performing this task and awaits its completion if
803 <     * necessary, without returning its result or throwing an
804 <     * exception. This method may be useful when processing
909 <     * collections of tasks when some have been cancelled or otherwise
910 <     * known to have aborted.
803 >     * necessary, without returning its result or throwing its
804 >     * exception.
805       */
806      public final void quietlyInvoke() {
807 <        if (status >= 0 && !tryQuietlyInvoke())
808 <            quietlyJoin();
807 >        if (status >= 0) {
808 >            boolean completed;
809 >            try {
810 >                completed = exec();
811 >            } catch (Throwable rex) {
812 >                setExceptionalCompletion(rex);
813 >                return;
814 >            }
815 >            if (completed)
816 >                setCompletion(NORMAL);
817 >            else
818 >                quietlyJoin();
819 >        }
820      }
821  
822      /**
# Line 943 | Line 848 | public abstract class ForkJoinTask<V> im
848       * pre-constructed trees of subtasks in loops.
849       */
850      public void reinitialize() {
851 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
851 >        if (status == EXCEPTIONAL)
852              exceptionMap.remove(this);
853          status = 0;
854      }
# Line 1233 | Line 1138 | public abstract class ForkJoinTask<V> im
1138      private static final long serialVersionUID = -7721805057305804111L;
1139  
1140      /**
1141 <     * Save the state to a stream.
1141 >     * Saves the state to a stream (that is, serializes it).
1142       *
1143       * @serialData the current run status and the exception thrown
1144       * during execution, or {@code null} if none
# Line 1246 | Line 1151 | public abstract class ForkJoinTask<V> im
1151      }
1152  
1153      /**
1154 <     * Reconstitute the instance from a stream.
1154 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1155       *
1156       * @param s the stream
1157       */
1158      private void readObject(java.io.ObjectInputStream s)
1159          throws java.io.IOException, ClassNotFoundException {
1160          s.defaultReadObject();
1256        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1257        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1161          Object ex = s.readObject();
1162          if (ex != null)
1163 <            setDoneExceptionally((Throwable) ex);
1163 >            setExceptionalCompletion((Throwable) ex);
1164      }
1165  
1166      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines