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.36 by dl, Tue Aug 4 13:16:54 2009 UTC vs.
Revision 1.48 by dl, Thu May 27 16:46:48 2010 UTC

# Line 56 | Line 56 | import java.util.WeakHashMap;
56   * exceptions such as {@code IOExceptions} to be thrown. However,
57   * computations may still encounter unchecked exceptions, that are
58   * rethrown to callers attempting to join them. These exceptions may
59 < * additionally include RejectedExecutionExceptions stemming from
60 < * internal resource exhaustion such as failure to allocate internal
61 < * task queues.
59 > * additionally include {@link RejectedExecutionException} stemming
60 > * from internal resource exhaustion, such as failure to allocate
61 > * internal task queues.
62   *
63   * <p>The primary method for awaiting completion and extracting
64   * results of a task is {@link #join}, but there are several variants:
# Line 80 | Line 80 | import java.util.WeakHashMap;
80   * <p>The execution status of tasks may be queried at several levels
81   * of detail: {@link #isDone} is true if a task completed in any way
82   * (including the case where a task was cancelled without executing);
83 * {@link #isCancelled} is true if completion was due to cancellation;
83   * {@link #isCompletedNormally} is true if a task completed without
84 < * cancellation or encountering an exception; {@link
85 < * #isCompletedExceptionally} is true if if the task encountered an
86 < * exception (in which case {@link #getException} returns the
87 < * exception); {@link #isCancelled} is true if the task was cancelled
88 < * (in which case {@link #getException} returns a {@link
89 < * java.util.concurrent.CancellationException}); and {@link
90 < * #isCompletedAbnormally} is true if a task was either cancelled or
92 < * encountered an exception.
84 > * cancellation or encountering an exception; {@link #isCancelled} is
85 > * true if the task was cancelled (in which case {@link #getException}
86 > * returns a {@link java.util.concurrent.CancellationException}); and
87 > * {@link #isCompletedAbnormally} is true if a task was either
88 > * cancelled or encountered an exception, in which case {@link
89 > * #getException} will return either the encountered exception or
90 > * {@link java.util.concurrent.CancellationException}.
91   *
92   * <p>The ForkJoinTask class is not usually directly subclassed.
93   * Instead, you subclass one of the abstract classes that support a
# Line 125 | Line 123 | import java.util.WeakHashMap;
123   * improve throughput. If too small, then memory and internal task
124   * maintenance overhead may overwhelm processing.
125   *
126 < * <p>This class provides {@code adapt} methods for {@link
127 < * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
128 < * may be of use when mixing execution of ForkJoinTasks with other
129 < * kinds of tasks. When all tasks are of this form, consider using a
130 < * pool in {@link ForkJoinPool#setAsyncMode async mode}.
126 > * <p>This class provides {@code adapt} methods for {@link Runnable}
127 > * and {@link Callable}, that may be of use when mixing execution of
128 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
129 > * are of this form, consider using a pool in
130 > * {@linkplain ForkJoinPool#setAsyncMode async mode}.
131   *
132   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
133   * used in extensions such as remote execution frameworks. It is
# Line 141 | Line 139 | import java.util.WeakHashMap;
139   */
140   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
141  
142 +    /*
143 +     * See the internal documentation of class ForkJoinPool for a
144 +     * general implementation overview.  ForkJoinTasks are mainly
145 +     * responsible for maintaining their "status" field amidst relays
146 +     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
147 +     * methods of this class are more-or-less layered into (1) basic
148 +     * status maintenance (2) execution and awaiting completion (3)
149 +     * user-level methods that additionally report results. This is
150 +     * sometimes hard to see because this file orders exported methods
151 +     * in a way that flows well in javadocs.
152 +     */
153 +
154      /**
155       * Run control status bits packed into a single int to minimize
156       * footprint and to ensure atomicity (via CAS).  Status is
157       * initially zero, and takes on nonnegative values until
158       * completed, upon which status holds COMPLETED. CANCELLED, or
159       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
160 <     * blocking waits by other threads have SIGNAL_MASK bits set --
161 <     * bit 15 for external (nonFJ) waits, and the rest a count of
162 <     * waiting FJ threads.  (This representation relies on
163 <     * ForkJoinPool max thread limits). Completion of a stolen task
164 <     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
165 <     * though suboptimal for some purposes, we use basic builtin
166 <     * wait/notify to take advantage of "monitor inflation" in JVMs
167 <     * that we would otherwise need to emulate to avoid adding further
168 <     * per-task bookkeeping overhead. Note that bits 16-28 are
169 <     * currently unused. Also value 0x80000000 is available as spare
170 <     * completion value.
160 >     * blocking waits by other threads have the SIGNAL bit set.
161 >     *
162 >     * Completion of a stolen task with SIGNAL set awakens any waiters
163 >     * via notifyAll. Even though suboptimal for some purposes, we use
164 >     * basic builtin wait/notify to take advantage of "monitor
165 >     * inflation" in JVMs that we would otherwise need to emulate to
166 >     * avoid adding further per-task bookkeeping overhead.  We want
167 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
168 >     * techniques, so use some odd coding idioms that tend to avoid
169 >     * them.
170 >     *
171 >     * Note that bits 1-28 are currently unused. Also value
172 >     * 0x80000000 is available as spare completion value.
173       */
174      volatile int status; // accessed directly by pool and workers
175  
176 <    static final int COMPLETION_MASK      = 0xe0000000;
177 <    static final int NORMAL               = 0xe0000000; // == mask
178 <    static final int CANCELLED            = 0xc0000000;
179 <    static final int EXCEPTIONAL          = 0xa0000000;
180 <    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
176 >    private static final int COMPLETION_MASK      = 0xe0000000;
177 >    private static final int NORMAL               = 0xe0000000; // == mask
178 >    private static final int CANCELLED            = 0xc0000000;
179 >    private static final int EXCEPTIONAL          = 0xa0000000;
180 >    private static final int SIGNAL               = 0x00000001;
181  
182      /**
183       * Table of exceptions thrown by tasks, to enable reporting by
# Line 181 | Line 191 | public abstract class ForkJoinTask<V> im
191          Collections.synchronizedMap
192          (new WeakHashMap<ForkJoinTask<?>, Throwable>());
193  
194 <    // within-package utilities
194 >    // Maintaining completion status
195  
196      /**
197 <     * Gets current worker thread, or null if not a worker thread.
198 <     */
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 <    }
198 <
199 <    /**
200 <     * Workaround for not being able to rethrow unchecked exceptions.
201 <     */
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.
197 >     * Marks completion and wakes up threads waiting to join this task,
198 >     * also clearing signal request bits.
199       *
200       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
201 +     * @return status on exit
202       */
203 <    final void setCompletion(int completion) {
215 <        ForkJoinPool pool = getPool();
216 <        if (pool != null) {
217 <            int s; // Clear signal bits while setting completion status
218 <            do {} while ((s = status) >= 0 && !casStatus(s, completion));
219 <
220 <            if ((s & SIGNAL_MASK) != 0) {
221 <                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
222 <                    pool.updateRunningCount(s);
223 <                synchronized (this) { notifyAll(); }
224 <            }
225 <        }
226 <        else
227 <            externallySetCompletion(completion);
228 <    }
229 <
230 <    /**
231 <     * Version of setCompletion for non-FJ threads.  Leaves signal
232 <     * bits for unblocked threads to adjust, and always notifies.
233 <     */
234 <    private void externallySetCompletion(int completion) {
203 >    private int setCompletion(int completion) {
204          int s;
205 <        do {} while ((s = status) >= 0 &&
206 <                     !casStatus(s, (s & SIGNAL_MASK) | completion));
207 <        synchronized (this) { notifyAll(); }
208 <    }
209 <
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.
255 <     */
256 <    private void doAwaitDone() {
257 <        // Minimize lock bias and in/de-flation effects by maximizing
258 <        // 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 <        }
265 <    }
266 <
267 <    /**
268 <     * Performs the actual timed monitor wait for awaitDone.
269 <     */
270 <    private void doAwaitDone(long startTime, long nanos) {
271 <        synchronized (this) {
272 <            try {
273 <                while (status >= 0) {
274 <                    long nt = nanos - (System.nanoTime() - startTime);
275 <                    if (nt <= 0)
276 <                        break;
277 <                    wait(nt / 1000000, (int) (nt % 1000000));
278 <                }
279 <            } catch (InterruptedException ie) {
280 <                onInterruptedWait();
205 >        while ((s = status) >= 0) {
206 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
207 >                if ((s & SIGNAL) != 0)
208 >                    synchronized (this) { notifyAll(); }
209 >                return completion;
210              }
211          }
212 +        return s;
213      }
214  
285    // Awaiting completion
286
215      /**
216 <     * Sets status to indicate there is joiner, then waits for join,
217 <     * surrounded with pool notifications.
290 <     *
291 <     * @return status upon exit
216 >     * Record exception and set exceptional completion
217 >     * @return status on exit
218       */
219 <    private int awaitDone(ForkJoinWorkerThread w,
220 <                          boolean maintainParallelism) {
221 <        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;
304 <            }
305 <        }
306 <        return s;
219 >    private int setExceptionalCompletion(Throwable rex) {
220 >        exceptionMap.put(this, rex);
221 >        return setCompletion(EXCEPTIONAL);
222      }
223  
224      /**
225 <     * Timed version of awaitDone
311 <     *
312 <     * @return status upon exit
225 >     * Blocks a worker thread until completion. Called only by pool.
226       */
227 <    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
315 <        ForkJoinPool pool = (w == null) ? null : w.pool;
227 >    final void internalAwaitDone() {
228          int s;
229          while ((s = status) >= 0) {
230 <            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
231 <                long startTime = System.nanoTime();
232 <                if (pool == null || !pool.preJoin(this, false))
233 <                    doAwaitDone(startTime, nanos);
234 <                if ((s = status) >= 0) {
235 <                    adjustPoolCountsOnCancelledWait(pool);
236 <                    s = status;
230 >            synchronized(this) {
231 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
232 >                    do {
233 >                        try {
234 >                            wait();
235 >                        } catch (InterruptedException ie) {
236 >                            cancelIfTerminating();
237 >                        }
238 >                    } while (status >= 0);
239 >                    break;
240                  }
326                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
327                    adjustPoolCountsOnUnblock(pool);
328                break;
241              }
242          }
331        return s;
243      }
244  
245      /**
246 <     * Notifies pool that thread is unblocked. Called by signalled
247 <     * threads when woken by non-FJ threads (which is atypical).
246 >     * Blocks a non-worker-thread until completion.
247 >     * @return status on exit
248       */
249 <    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
249 >    private int externalAwaitDone() {
250          int s;
251 <        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
252 <        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
253 <            pool.updateRunningCount(s);
254 <    }
255 <
256 <    /**
257 <     * Notifies pool to adjust counts on cancelled or timed out wait.
258 <     */
259 <    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
260 <        if (pool != null) {
261 <            int s;
262 <            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
263 <                if (casStatus(s, s - 1)) {
353 <                    pool.updateRunningCount(1);
251 >        while ((s = status) >= 0) {
252 >            synchronized(this) {
253 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
254 >                    boolean interrupted = false;
255 >                    do {
256 >                        try {
257 >                            wait();
258 >                        } catch (InterruptedException ie) {
259 >                            interrupted = true;
260 >                        }
261 >                    } while ((s = status) >= 0);
262 >                    if (interrupted)
263 >                        Thread.currentThread().interrupt();
264                      break;
265                  }
266              }
267          }
268 +        return s;
269      }
270  
271      /**
272 <     * Handles interruptions during waits.
273 <     */
363 <    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 ExecutionException, InterruptedException {
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 <        if (s == CANCELLED)
425 <            throw new CancellationException();
426 <        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
427 <            throw new ExecutionException(ex);
428 <        throw new TimeoutException();
429 <    }
430 <
431 <    // internal execution methods
432 <
433 <    /**
434 <     * Calls exec, recording completion, and rethrowing exception if
435 <     * encountered. Caller should normally check status before calling.
436 <     *
437 <     * @return true if completed normally
272 >     * Unless done, calls exec and records status if completed, but
273 >     * doesn't wait for completion otherwise.
274       */
275 <    private boolean tryExec() {
276 <        try { // try block must contain only call to exec
277 <            if (!exec())
278 <                return false;
275 >    final void tryExec() {
276 >        try {
277 >            if (status < 0 || !exec())
278 >                return;
279          } catch (Throwable rex) {
280 <            setDoneExceptionally(rex);
281 <            rethrowException(rex);
446 <            return false; // not reached
280 >            setExceptionalCompletion(rex);
281 >            return;
282          }
283 <        setNormalCompletion();
449 <        return true;
283 >        setCompletion(NORMAL); // must be outside try block
284      }
285  
286      /**
287 <     * Main execution method used by worker threads. Invokes
288 <     * base computation unless already complete.
287 >     * If not done and this task is next in worker queue, runs it,
288 >     * else waits for it.
289 >     * @return status on exit
290       */
291 <    final void quietlyExec() {
292 <        if (status >= 0) {
293 <            try {
294 <                if (!exec())
295 <                    return;
296 <            } catch (Throwable rex) {
297 <                setDoneExceptionally(rex);
298 <                return;
291 >    private int waitingJoin() {
292 >        int s = status;
293 >        if (s < 0)
294 >            return s;
295 >        Thread t = Thread.currentThread();
296 >        if (t instanceof ForkJoinWorkerThread) {
297 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
298 >            if (w.unpushTask(this)) {
299 >                boolean completed;
300 >                try {
301 >                    completed = exec();
302 >                } catch (Throwable rex) {
303 >                    return setExceptionalCompletion(rex);
304 >                }
305 >                if (completed)
306 >                    return setCompletion(NORMAL);
307              }
308 <            setNormalCompletion();
308 >            return w.pool.awaitJoin(this);
309          }
310 +        else
311 +            return externalAwaitDone();
312      }
313  
314      /**
315 <     * Calls exec(), recording but not rethrowing exception.
316 <     * Caller should normally check status before calling.
317 <     *
473 <     * @return true if completed normally
315 >     * Unless done, calls exec and records status if completed, or
316 >     * waits for completion otherwise.
317 >     * @return status on exit
318       */
319 <    private boolean tryQuietlyInvoke() {
319 >    private int waitingInvoke() {
320 >        int s = status;
321 >        if (s < 0)
322 >            return s;
323 >        boolean completed;
324          try {
325 <            if (!exec())
478 <                return false;
325 >            completed = exec();
326          } catch (Throwable rex) {
327 <            setDoneExceptionally(rex);
481 <            return false;
327 >            return setExceptionalCompletion(rex);
328          }
329 <        setNormalCompletion();
330 <        return true;
329 >        if (completed)
330 >            return setCompletion(NORMAL);
331 >        return waitingJoin();
332      }
333  
334      /**
335 <     * Cancels, ignoring any exceptions it throws.
335 >     * If this task is next in worker queue, runs it, else processes other
336 >     * tasks until complete.
337 >     * @return status on exit
338       */
339 <    final void cancelIgnoringExceptions() {
340 <        try {
341 <            cancel(false);
342 <        } catch (Throwable ignore) {
339 >    private int busyJoin() {
340 >        int s = status;
341 >        if (s < 0)
342 >            return s;
343 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
344 >        if (w.unpushTask(this)) {
345 >            boolean completed;
346 >            try {
347 >                completed = exec();
348 >            } catch (Throwable rex) {
349 >                return setExceptionalCompletion(rex);
350 >            }
351 >            if (completed)
352 >                return setCompletion(NORMAL);
353          }
354 +        return w.execWhileJoining(this);
355      }
356  
357      /**
358 <     * Main implementation of helpJoin
358 >     * Returns result or throws exception associated with given status.
359 >     * @param s the status
360       */
361 <    private int busyJoin(ForkJoinWorkerThread w) {
362 <        int s;
363 <        ForkJoinTask<?> t;
364 <        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
365 <            t.quietlyExec();
505 <        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
361 >    private V reportResult(int s) {
362 >        Throwable ex;
363 >        if (s < NORMAL && (ex = getException()) != null)
364 >            UNSAFE.throwException(ex);
365 >        return getRawResult();
366      }
367  
368      // public methods
# Line 511 | Line 371 | public abstract class ForkJoinTask<V> im
371       * Arranges to asynchronously execute this task.  While it is not
372       * necessarily enforced, it is a usage error to fork a task more
373       * than once unless it has completed and been reinitialized.
374 +     * Subsequent modifications to the state of this task or any data
375 +     * it operates on are not necessarily consistently observable by
376 +     * any thread other than the one executing it unless preceded by a
377 +     * call to {@link #join} or related methods, or a call to {@link
378 +     * #isDone} returning {@code true}.
379       *
380       * <p>This method may be invoked only from within {@code
381       * ForkJoinTask} computations (as may be determined using method
# Line 527 | Line 392 | public abstract class ForkJoinTask<V> im
392      }
393  
394      /**
395 <     * Returns the result of the computation when it is ready.
395 >     * Returns the result of the computation when it {@link #isDone is done}.
396       * This method differs from {@link #get()} in that
397       * abnormal completion results in {@code RuntimeException} or
398       * {@code Error}, not {@code ExecutionException}.
# Line 535 | Line 400 | public abstract class ForkJoinTask<V> im
400       * @return the computed result
401       */
402      public final V join() {
403 <        ForkJoinWorkerThread w = getWorker();
539 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
540 <            reportException(awaitDone(w, true));
541 <        return getRawResult();
403 >        return reportResult(waitingJoin());
404      }
405  
406      /**
# Line 549 | Line 411 | public abstract class ForkJoinTask<V> im
411       * @return the computed result
412       */
413      public final V invoke() {
414 <        if (status >= 0 && tryExec())
553 <            return getRawResult();
554 <        else
555 <            return join();
414 >        return reportResult(waitingInvoke());
415      }
416  
417      /**
418       * Forks the given tasks, returning when {@code isDone} holds for
419       * each task or an (unchecked) exception is encountered, in which
420 <     * case the exception is rethrown.  If more than one task
421 <     * encounters an exception, then this method throws any one of
422 <     * these exceptions.  The individual status of each task may be
420 >     * case the exception is rethrown.  If either task encounters an
421 >     * exception, the other one may be, but is not guaranteed to be,
422 >     * cancelled.  If both tasks throw an exception, then this method
423 >     * throws one of them.  The individual status of each task may be
424       * checked using {@link #getException()} and related methods.
425       *
426       * <p>This method may be invoked only from within {@code
# Line 609 | Line 469 | public abstract class ForkJoinTask<V> im
469              }
470              else if (i != 0)
471                  t.fork();
472 <            else {
473 <                t.quietlyInvoke();
614 <                if (ex == null)
615 <                    ex = t.getException();
616 <            }
472 >            else if (t.waitingInvoke() < NORMAL && ex == null)
473 >                ex = t.getException();
474          }
475          for (int i = 1; i <= last; ++i) {
476              ForkJoinTask<?> t = tasks[i];
477              if (t != null) {
478                  if (ex != null)
479                      t.cancel(false);
480 <                else {
481 <                    t.quietlyJoin();
625 <                    if (ex == null)
626 <                        ex = t.getException();
627 <                }
480 >                else if (t.waitingJoin() < NORMAL && ex == null)
481 >                    ex = t.getException();
482              }
483          }
484          if (ex != null)
485 <            rethrowException(ex);
485 >            UNSAFE.throwException(ex);
486      }
487  
488      /**
# Line 671 | Line 525 | public abstract class ForkJoinTask<V> im
525              }
526              else if (i != 0)
527                  t.fork();
528 <            else {
529 <                t.quietlyInvoke();
676 <                if (ex == null)
677 <                    ex = t.getException();
678 <            }
528 >            else if (t.waitingInvoke() < NORMAL && ex == null)
529 >                ex = t.getException();
530          }
531          for (int i = 1; i <= last; ++i) {
532              ForkJoinTask<?> t = ts.get(i);
533              if (t != null) {
534                  if (ex != null)
535                      t.cancel(false);
536 <                else {
537 <                    t.quietlyJoin();
687 <                    if (ex == null)
688 <                        ex = t.getException();
689 <                }
536 >                else if (t.waitingJoin() < NORMAL && ex == null)
537 >                    ex = t.getException();
538              }
539          }
540          if (ex != null)
541 <            rethrowException(ex);
541 >            UNSAFE.throwException(ex);
542          return tasks;
543      }
544  
# Line 724 | Line 572 | public abstract class ForkJoinTask<V> im
572      }
573  
574      /**
575 <     * Returns {@code true} if the computation performed by this task
576 <     * has completed (or has been cancelled).
729 <     *
730 <     * @return {@code true} if this computation has completed
575 >     * Cancels, ignoring any exceptions it throws. Used during worker
576 >     * and pool shutdown.
577       */
578 <    public final boolean isDone() {
579 <        return status < 0;
578 >    final void cancelIgnoringExceptions() {
579 >        try {
580 >            cancel(false);
581 >        } catch (Throwable ignore) {
582 >        }
583      }
584  
585      /**
586 <     * Returns {@code true} if this task was cancelled.
738 <     *
739 <     * @return {@code true} if this task was cancelled
586 >     * Cancels ignoring exceptions if worker is terminating
587       */
588 +    private void cancelIfTerminating() {
589 +        Thread t = Thread.currentThread();
590 +        if ((t instanceof ForkJoinWorkerThread) &&
591 +            ((ForkJoinWorkerThread) t).isTerminating()) {
592 +            try {
593 +                cancel(false);
594 +            } catch (Throwable ignore) {
595 +            }
596 +        }
597 +    }
598 +
599 +    public final boolean isDone() {
600 +        return status < 0;
601 +    }
602 +
603      public final boolean isCancelled() {
604          return (status & COMPLETION_MASK) == CANCELLED;
605      }
# Line 763 | Line 625 | public abstract class ForkJoinTask<V> im
625      }
626  
627      /**
766     * Returns {@code true} if this task threw an exception.
767     *
768     * @return {@code true} if this task threw an exception
769     */
770    public final boolean isCompletedExceptionally() {
771        return (status & COMPLETION_MASK) == EXCEPTIONAL;
772    }
773
774    /**
628       * Returns the exception thrown by the base computation, or a
629       * {@code CancellationException} if cancelled, or {@code null} if
630       * none or if the method has not yet completed.
# Line 780 | Line 633 | public abstract class ForkJoinTask<V> im
633       */
634      public final Throwable getException() {
635          int s = status & COMPLETION_MASK;
636 <        if (s >= NORMAL)
637 <            return null;
638 <        if (s == CANCELLED)
786 <            return new CancellationException();
787 <        return exceptionMap.get(this);
636 >        return ((s >= NORMAL)    ? null :
637 >                (s == CANCELLED) ? new CancellationException() :
638 >                exceptionMap.get(this));
639      }
640  
641      /**
# Line 797 | Line 648 | public abstract class ForkJoinTask<V> im
648       * overridable, but overridden versions must invoke {@code super}
649       * implementation to maintain guarantees.
650       *
651 <     * @param ex the exception to throw. If this exception is
652 <     * not a RuntimeException or Error, the actual exception thrown
653 <     * will be a RuntimeException with cause ex.
651 >     * @param ex the exception to throw. If this exception is not a
652 >     * {@code RuntimeException} or {@code Error}, the actual exception
653 >     * thrown will be a {@code RuntimeException} with cause {@code ex}.
654       */
655      public void completeExceptionally(Throwable ex) {
656 <        setDoneExceptionally((ex instanceof RuntimeException) ||
657 <                             (ex instanceof Error) ? ex :
658 <                             new RuntimeException(ex));
656 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
657 >                                 (ex instanceof Error) ? ex :
658 >                                 new RuntimeException(ex));
659      }
660  
661      /**
# Line 823 | Line 674 | public abstract class ForkJoinTask<V> im
674          try {
675              setRawResult(value);
676          } catch (Throwable rex) {
677 <            setDoneExceptionally(rex);
677 >            setExceptionalCompletion(rex);
678              return;
679          }
680 <        setNormalCompletion();
680 >        setCompletion(NORMAL);
681      }
682  
683      public final V get() throws InterruptedException, ExecutionException {
684 <        ForkJoinWorkerThread w = getWorker();
685 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
686 <            awaitDone(w, true);
687 <        return reportFutureResult();
684 >        int s = waitingJoin() & COMPLETION_MASK;
685 >        if (Thread.interrupted())
686 >            throw new InterruptedException();
687 >        if (s < NORMAL) {
688 >            Throwable ex;
689 >            if (s == CANCELLED)
690 >                throw new CancellationException();
691 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
692 >                throw new ExecutionException(ex);
693 >        }
694 >        return getRawResult();
695      }
696  
697      public final V get(long timeout, TimeUnit unit)
698          throws InterruptedException, ExecutionException, TimeoutException {
699 <        long nanos = unit.toNanos(timeout);
700 <        ForkJoinWorkerThread w = getWorker();
701 <        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
702 <            awaitDone(w, nanos);
703 <        return reportTimedFutureResult();
699 >        Thread t = Thread.currentThread();
700 >        ForkJoinPool pool;
701 >        if (t instanceof ForkJoinWorkerThread) {
702 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
703 >            if (status >= 0 && w.unpushTask(this))
704 >                tryExec();
705 >            pool = w.pool;
706 >        }
707 >        else
708 >            pool = null;
709 >        /*
710 >         * Timed wait loop intermixes cases for fj (pool != null) and
711 >         * non FJ threads. For FJ, decrement pool count but don't try
712 >         * for replacement; increment count on completion. For non-FJ,
713 >         * deal with interrupts. This is messy, but a little less so
714 >         * than is splitting the FJ and nonFJ cases.
715 >         */
716 >        boolean interrupted = false;
717 >        boolean dec = false; // true if pool count decremented
718 >        for (;;) {
719 >            if (Thread.interrupted() && pool == null) {
720 >                interrupted = true;
721 >                break;
722 >            }
723 >            int s = status;
724 >            if (s < 0)
725 >                break;
726 >            if (UNSAFE.compareAndSwapInt(this, statusOffset,
727 >                                         s, s | SIGNAL)) {
728 >                long startTime = System.nanoTime();
729 >                long nanos = unit.toNanos(timeout);
730 >                long nt; // wait time
731 >                while (status >= 0 &&
732 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
733 >                    if (pool != null && !dec)
734 >                        dec = pool.tryDecrementRunningCount();
735 >                    else {
736 >                        long ms = nt / 1000000;
737 >                        int ns = (int) (nt % 1000000);
738 >                        try {
739 >                            synchronized(this) {
740 >                                if (status >= 0)
741 >                                    wait(ms, ns);
742 >                            }
743 >                        } catch (InterruptedException ie) {
744 >                            if (pool != null)
745 >                                cancelIfTerminating();
746 >                            else {
747 >                                interrupted = true;
748 >                                break;
749 >                            }
750 >                        }
751 >                    }
752 >                }
753 >                break;
754 >            }
755 >        }
756 >        if (pool != null && dec)
757 >            pool.updateRunningCount(1);
758 >        if (interrupted)
759 >            throw new InterruptedException();
760 >        int es = status & COMPLETION_MASK;
761 >        if (es != NORMAL) {
762 >            Throwable ex;
763 >            if (es == CANCELLED)
764 >                throw new CancellationException();
765 >            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
766 >                throw new ExecutionException(ex);
767 >            throw new TimeoutException();
768 >        }
769 >        return getRawResult();
770      }
771  
772      /**
773 <     * Possibly executes other tasks until this task is ready, then
774 <     * returns the result of the computation.  This method may be more
775 <     * efficient than {@code join}, but is only applicable when
776 <     * there are no potential dependencies between continuation of the
777 <     * current task and that of any other task that might be executed
778 <     * while helping. (This usually holds for pure divide-and-conquer
779 <     * tasks).
773 >     * Possibly executes other tasks until this task {@link #isDone is
774 >     * done}, then returns the result of the computation.  This method
775 >     * may be more efficient than {@code join}, but is only applicable
776 >     * when there are no potential dependencies between continuation
777 >     * of the current task and that of any other task that might be
778 >     * executed while helping. (This usually holds for pure
779 >     * divide-and-conquer tasks).
780       *
781       * <p>This method may be invoked only from within {@code
782       * ForkJoinTask} computations (as may be determined using method
# Line 863 | Line 787 | public abstract class ForkJoinTask<V> im
787       * @return the computed result
788       */
789      public final V helpJoin() {
790 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
867 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
868 <            reportException(busyJoin(w));
869 <        return getRawResult();
790 >        return reportResult(busyJoin());
791      }
792  
793      /**
794 <     * Possibly executes other tasks until this task is ready.  This
795 <     * method may be useful when processing collections of tasks when
796 <     * some have been cancelled or otherwise known to have aborted.
794 >     * Possibly executes other tasks until this task {@link #isDone is
795 >     * done}.  This method may be useful when processing collections
796 >     * of tasks when some have been cancelled or otherwise known to
797 >     * have aborted.
798       *
799       * <p>This method may be invoked only from within {@code
800       * ForkJoinTask} computations (as may be determined using method
# Line 881 | Line 803 | public abstract class ForkJoinTask<V> im
803       * ClassCastException}.
804       */
805      public final void quietlyHelpJoin() {
806 <        if (status >= 0) {
885 <            ForkJoinWorkerThread w =
886 <                (ForkJoinWorkerThread) Thread.currentThread();
887 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
888 <                busyJoin(w);
889 <        }
806 >        busyJoin();
807      }
808  
809      /**
# Line 896 | Line 813 | public abstract class ForkJoinTask<V> im
813       * known to have aborted.
814       */
815      public final void quietlyJoin() {
816 <        if (status >= 0) {
900 <            ForkJoinWorkerThread w = getWorker();
901 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
902 <                awaitDone(w, true);
903 <        }
816 >        waitingJoin();
817      }
818  
819      /**
# Line 911 | Line 824 | public abstract class ForkJoinTask<V> im
824       * known to have aborted.
825       */
826      public final void quietlyInvoke() {
827 <        if (status >= 0 && !tryQuietlyInvoke())
915 <            quietlyJoin();
827 >        waitingInvoke();
828      }
829  
830      /**
# Line 1234 | Line 1146 | public abstract class ForkJoinTask<V> im
1146      private static final long serialVersionUID = -7721805057305804111L;
1147  
1148      /**
1149 <     * Save the state to a stream.
1149 >     * Saves the state to a stream.
1150       *
1151       * @serialData the current run status and the exception thrown
1152       * during execution, or {@code null} if none
# Line 1247 | Line 1159 | public abstract class ForkJoinTask<V> im
1159      }
1160  
1161      /**
1162 <     * Reconstitute the instance from a stream.
1162 >     * Reconstitutes the instance from a stream.
1163       *
1164       * @param s the stream
1165       */
1166      private void readObject(java.io.ObjectInputStream s)
1167          throws java.io.IOException, ClassNotFoundException {
1168          s.defaultReadObject();
1169 <        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1258 <        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1169 >        status |= SIGNAL; // conservatively set external signal
1170          Object ex = s.readObject();
1171          if (ex != null)
1172 <            setDoneExceptionally((Throwable) ex);
1172 >            setExceptionalCompletion((Throwable) ex);
1173      }
1174  
1175      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines