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.47 by dl, Sun Apr 18 12:51:18 2010 UTC vs.
Revision 1.66 by dl, Sun Oct 24 19:37:26 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
10
9   import java.io.Serializable;
10   import java.util.Collection;
11   import java.util.Collections;
# Line 15 | Line 13 | import java.util.List;
13   import java.util.RandomAccess;
14   import java.util.Map;
15   import java.util.WeakHashMap;
16 + import java.util.concurrent.Callable;
17 + import java.util.concurrent.CancellationException;
18 + import java.util.concurrent.ExecutionException;
19 + import java.util.concurrent.Executor;
20 + import java.util.concurrent.ExecutorService;
21 + import java.util.concurrent.Future;
22 + import java.util.concurrent.RejectedExecutionException;
23 + import java.util.concurrent.RunnableFuture;
24 + import java.util.concurrent.TimeUnit;
25 + import java.util.concurrent.TimeoutException;
26  
27   /**
28   * Abstract base class for tasks that run within a {@link ForkJoinPool}.
# Line 28 | Line 36 | import java.util.WeakHashMap;
36   * start other subtasks.  As indicated by the name of this class,
37   * many programs using {@code ForkJoinTask} employ only methods
38   * {@link #fork} and {@link #join}, or derivatives such as {@link
39 < * #invokeAll}.  However, this class also provides a number of other
40 < * methods that can come into play in advanced usages, as well as
41 < * extension mechanics that allow support of new forms of fork/join
42 < * processing.
39 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
40 > * provides a number of other methods that can come into play in
41 > * advanced usages, as well as extension mechanics that allow
42 > * support of new forms of fork/join processing.
43   *
44   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
45   * The efficiency of {@code ForkJoinTask}s stems from a set of
# Line 64 | Line 72 | import java.util.WeakHashMap;
72   * results of a task is {@link #join}, but there are several variants:
73   * The {@link Future#get} methods support interruptible and/or timed
74   * waits for completion and report results using {@code Future}
75 < * conventions. Method {@link #helpJoin} enables callers to actively
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
75 > * conventions. Method {@link #invoke} is semantically
76   * equivalent to {@code fork(); join()} but always attempts to begin
77   * execution in the current thread. The "<em>quiet</em>" forms of
78   * these methods do not extract results or report exceptions. These
# Line 103 | Line 108 | import java.util.WeakHashMap;
108   * ForkJoinTasks (as may be determined using method {@link
109   * #inForkJoinPool}).  Attempts to invoke them in other contexts
110   * result in exceptions or errors, possibly including
111 < * ClassCastException.
111 > * {@code ClassCastException}.
112   *
113   * <p>Most base support methods are {@code final}, to prevent
114   * overriding of implementations that are intrinsically tied to the
# Line 125 | Line 130 | import java.util.WeakHashMap;
130   *
131   * <p>This class provides {@code adapt} methods for {@link Runnable}
132   * and {@link Callable}, that may be of use when mixing execution of
133 < * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
134 < * are of this form, consider using a pool in
130 < * {@linkplain ForkJoinPool#setAsyncMode async mode}.
133 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
134 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
135   *
136   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
137   * used in extensions such as remote execution frameworks. It is
# Line 148 | Line 152 | public abstract class ForkJoinTask<V> im
152       * status maintenance (2) execution and awaiting completion (3)
153       * user-level methods that additionally report results. This is
154       * sometimes hard to see because this file orders exported methods
155 <     * in a way that flows well in javadocs.
155 >     * in a way that flows well in javadocs. In particular, most
156 >     * join mechanics are in method quietlyJoin, below.
157       */
158  
159 <    /**
160 <     * Run control status bits packed into a single int to minimize
161 <     * footprint and to ensure atomicity (via CAS).  Status is
162 <     * initially zero, and takes on nonnegative values until
163 <     * completed, upon which status holds COMPLETED. CANCELLED, or
164 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
165 <     * blocking waits by other threads have SIGNAL_MASK bits set --
166 <     * bit 15 for external (nonFJ) waits, and the rest a count of
167 <     * waiting FJ threads.  (This representation relies on
168 <     * ForkJoinPool max thread limits). Signal counts are not directly
169 <     * incremented by ForkJoinTask methods, but instead via a call to
170 <     * requestSignal within ForkJoinPool.preJoin, once their need is
171 <     * established.
172 <     *
173 <     * Completion of a stolen task with SIGNAL_MASK bits set awakens
169 <     * any waiters via notifyAll. Even though suboptimal for some
170 <     * purposes, we use basic builtin wait/notify to take advantage of
171 <     * "monitor inflation" in JVMs that we would otherwise need to
172 <     * emulate to avoid adding further per-task bookkeeping overhead.
173 <     * We want these monitors to be "fat", i.e., not use biasing or
174 <     * thin-lock techniques, so use some odd coding idioms that tend
175 <     * to avoid them.
176 <     *
177 <     * Note that bits 16-28 are currently unused. Also value
178 <     * 0x80000000 is available as spare completion value.
159 >    /*
160 >     * The status field holds run control status bits packed into a
161 >     * single int to minimize footprint and to ensure atomicity (via
162 >     * CAS).  Status is initially zero, and takes on nonnegative
163 >     * values until completed, upon which status holds value
164 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
165 >     * waits by other threads have the SIGNAL bit set.  Completion of
166 >     * a stolen task with SIGNAL set awakens any waiters via
167 >     * notifyAll. Even though suboptimal for some purposes, we use
168 >     * basic builtin wait/notify to take advantage of "monitor
169 >     * inflation" in JVMs that we would otherwise need to emulate to
170 >     * avoid adding further per-task bookkeeping overhead.  We want
171 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
172 >     * techniques, so use some odd coding idioms that tend to avoid
173 >     * them.
174       */
175 +
176 +    /** The run status of this task */
177      volatile int status; // accessed directly by pool and workers
178  
179 <    private static final int COMPLETION_MASK      = 0xe0000000;
180 <    private static final int NORMAL               = 0xe0000000; // == mask
181 <    private static final int CANCELLED            = 0xc0000000;
182 <    private static final int EXCEPTIONAL          = 0xa0000000;
186 <    private static final int SIGNAL_MASK          = 0x0000ffff;
187 <    private static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
188 <    private static final int EXTERNAL_SIGNAL      = 0x00008000;
179 >    private static final int NORMAL      = -1;
180 >    private static final int CANCELLED   = -2;
181 >    private static final int EXCEPTIONAL = -3;
182 >    private static final int SIGNAL      =  1;
183  
184      /**
185       * Table of exceptions thrown by tasks, to enable reporting by
# Line 211 | Line 205 | public abstract class ForkJoinTask<V> im
205          int s;
206          while ((s = status) >= 0) {
207              if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
208 <                if ((s & SIGNAL_MASK) != 0) {
215 <                    Thread t = Thread.currentThread();
216 <                    if (t instanceof ForkJoinWorkerThread)
217 <                        ((ForkJoinWorkerThread) t).pool.updateRunningCount
218 <                            (s & INTERNAL_SIGNAL_MASK);
208 >                if (s != 0)
209                      synchronized (this) { notifyAll(); }
210 <                }
221 <                return;
210 >                break;
211              }
212          }
213      }
214  
215      /**
216 <     * Record exception and set exceptional completion
216 >     * Records exception and sets exceptional completion.
217 >     *
218 >     * @return status on exit
219       */
220 <    private void setDoneExceptionally(Throwable rex) {
220 >    private void setExceptionalCompletion(Throwable rex) {
221          exceptionMap.put(this, rex);
222          setCompletion(EXCEPTIONAL);
223      }
224  
225      /**
226 <     * Main internal execution method: Unless done, calls exec and
227 <     * records completion.
228 <     *
238 <     * @return true if ran and completed normally
226 >     * Blocks a worker thread until completion. Called only by
227 >     * pool. Currently unused -- pool-based waits use timeout
228 >     * version below.
229       */
230 <    final boolean tryExec() {
231 <        try {
232 <            if (status < 0 || !exec())
233 <                return false;
234 <        } catch (Throwable rex) {
235 <            setDoneExceptionally(rex);
236 <            return false;
230 >    final void internalAwaitDone() {
231 >        int s;         // the odd construction reduces lock bias effects
232 >        while ((s = status) >= 0) {
233 >            try {
234 >                synchronized (this) {
235 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
236 >                        wait();
237 >                }
238 >            } catch (InterruptedException ie) {
239 >                cancelIfTerminating();
240 >            }
241          }
248        setCompletion(NORMAL); // must be outside try block
249        return true;
250    }
251
252    /**
253     * Increments internal signal count (thus requesting signal upon
254     * completion) unless already done.  Call only once per join.
255     * Used by ForkJoinPool.preJoin.
256     *
257     * @return status
258     */
259    final int requestSignal() {
260        int s;
261        do {} while ((s = status) >= 0 &&
262                     !UNSAFE.compareAndSwapInt(this, statusOffset, s, s + 1));
263        return s;
242      }
243  
244      /**
245 <     * Sets external signal request unless already done.
245 >     * Blocks a worker thread until completed or timed out.  Called
246 >     * only by pool.
247       *
248 <     * @return status
248 >     * @return status on exit
249       */
250 <    private int requestExternalSignal() {
250 >    final int internalAwaitDone(long millis, int nanos) {
251          int s;
252 <        do {} while ((s = status) >= 0 &&
253 <                     !UNSAFE.compareAndSwapInt(this, statusOffset,
254 <                                               s, s | EXTERNAL_SIGNAL));
255 <        return s;
256 <    }
278 <
279 <    /*
280 <     * Awaiting completion. The four versions, internal vs external X
281 <     * untimed vs timed, have the same overall structure but differ
282 <     * from each other enough to defy simple integration.
283 <     */
284 <
285 <    /**
286 <     * Blocks a worker until this task is done, also maintaining pool
287 <     * and signal counts
288 <     */
289 <    private void awaitDone(ForkJoinWorkerThread w) {
290 <        if (status >= 0) {
291 <            w.pool.preJoin(this);
292 <            while (status >= 0) {
293 <                try { // minimize lock scope
294 <                    synchronized(this) {
295 <                        if (status >= 0)
296 <                            wait();
297 <                        else { // help release; also helps avoid lock-biasing
298 <                            notifyAll();
299 <                            break;
300 <                        }
301 <                    }
302 <                } catch (InterruptedException ie) {
303 <                    cancelIfTerminating();
252 >        if ((s = status) >= 0) {
253 >            try {
254 >                synchronized (this) {
255 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
256 >                        wait(millis, nanos);
257                  }
258 +            } catch (InterruptedException ie) {
259 +                cancelIfTerminating();
260              }
261 +            s = status;
262          }
263 +        return s;
264      }
265  
266      /**
267 <     * Blocks a non-ForkJoin thread until this task is done.
267 >     * Blocks a non-worker-thread until completion.
268       */
269      private void externalAwaitDone() {
270 <        if (requestExternalSignal() >= 0) {
271 <            boolean interrupted = false;
272 <            while (status >= 0) {
273 <                try {
274 <                    synchronized(this) {
275 <                        if (status >= 0)
270 >        int s;
271 >        while ((s = status) >= 0) {
272 >            synchronized (this) {
273 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
274 >                    boolean interrupted = false;
275 >                    while (status >= 0) {
276 >                        try {
277                              wait();
278 <                        else {
279 <                            notifyAll();
322 <                            break;
323 <                        }
324 <                    }
325 <                } catch (InterruptedException ie) {
326 <                    interrupted = true;
327 <                }
328 <            }
329 <            if (interrupted)
330 <                Thread.currentThread().interrupt();
331 <        }
332 <    }
333 <
334 <    /**
335 <     * Blocks a worker until this task is done or timeout elapses
336 <     */
337 <    private void timedAwaitDone(ForkJoinWorkerThread w, long nanos) {
338 <        if (status >= 0) {
339 <            long startTime = System.nanoTime();
340 <            ForkJoinPool pool = w.pool;
341 <            pool.preJoin(this);
342 <            while (status >= 0) {
343 <                long nt = nanos - (System.nanoTime() - startTime);
344 <                if (nt > 0) {
345 <                    long ms = nt / 1000000;
346 <                    int ns = (int) (nt % 1000000);
347 <                    try {
348 <                        synchronized(this) { if (status >= 0) wait(ms, ns); }
349 <                    } catch (InterruptedException ie) {
350 <                        cancelIfTerminating();
351 <                    }
352 <                }
353 <                else {
354 <                    int s; // adjust running count on timeout
355 <                    while ((s = status) >= 0 &&
356 <                           (s & INTERNAL_SIGNAL_MASK) != 0) {
357 <                        if (UNSAFE.compareAndSwapInt(this, statusOffset,
358 <                                                     s, s - 1)) {
359 <                            pool.updateRunningCount(1);
360 <                            break;
278 >                        } catch (InterruptedException ie) {
279 >                            interrupted = true;
280                          }
281                      }
282 +                    if (interrupted)
283 +                        Thread.currentThread().interrupt();
284                      break;
285                  }
286              }
# Line 367 | Line 288 | public abstract class ForkJoinTask<V> im
288      }
289  
290      /**
291 <     * Blocks a non-ForkJoin thread until this task is done or timeout elapses
291 >     * Unless done, calls exec and records status if completed, but
292 >     * doesn't wait for completion otherwise. Primary execution method
293 >     * for ForkJoinWorkerThread.
294       */
295 <    private void externalTimedAwaitDone(long nanos) {
296 <        if (requestExternalSignal() >= 0) {
297 <            long startTime = System.nanoTime();
298 <            boolean interrupted = false;
299 <            while (status >= 0) {
300 <                long nt = nanos - (System.nanoTime() - startTime);
301 <                if (nt <= 0)
379 <                    break;
380 <                long ms = nt / 1000000;
381 <                int ns = (int) (nt % 1000000);
382 <                try {
383 <                    synchronized(this) { if (status >= 0) wait(ms, ns); }
384 <                } catch (InterruptedException ie) {
385 <                    interrupted = true;
386 <                }
387 <            }
388 <            if (interrupted)
389 <                Thread.currentThread().interrupt();
390 <        }
391 <    }
392 <
393 <    // reporting results
394 <
395 <    /**
396 <     * Returns result or throws the exception associated with status.
397 <     * Uses Unsafe as a workaround for javac not allowing rethrow of
398 <     * unchecked exceptions.
399 <     */
400 <    private V reportResult() {
401 <        if ((status & COMPLETION_MASK) < NORMAL) {
402 <            Throwable ex = getException();
403 <            if (ex != null)
404 <                UNSAFE.throwException(ex);
405 <        }
406 <        return getRawResult();
407 <    }
408 <
409 <    /**
410 <     * Returns result or throws exception using j.u.c.Future conventions.
411 <     * Only call when {@code isDone} known to be true or thread known
412 <     * to be interrupted.
413 <     */
414 <    private V reportFutureResult()
415 <        throws InterruptedException, ExecutionException {
416 <        if (Thread.interrupted())
417 <            throw new InterruptedException();
418 <        int s = status & COMPLETION_MASK;
419 <        if (s < NORMAL) {
420 <            Throwable ex;
421 <            if (s == CANCELLED)
422 <                throw new CancellationException();
423 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
424 <                throw new ExecutionException(ex);
295 >    final void quietlyExec() {
296 >        try {
297 >            if (status < 0 || !exec())
298 >                return;
299 >        } catch (Throwable rex) {
300 >            setExceptionalCompletion(rex);
301 >            return;
302          }
303 <        return getRawResult();
427 <    }
428 <
429 <    /**
430 <     * Returns result or throws exception using j.u.c.Future conventions
431 <     * with timeouts.
432 <     */
433 <    private V reportTimedFutureResult()
434 <        throws InterruptedException, ExecutionException, TimeoutException {
435 <        if (Thread.interrupted())
436 <            throw new InterruptedException();
437 <        Throwable ex;
438 <        int s = status & COMPLETION_MASK;
439 <        if (s == NORMAL)
440 <            return getRawResult();
441 <        else if (s == CANCELLED)
442 <            throw new CancellationException();
443 <        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
444 <            throw new ExecutionException(ex);
445 <        else
446 <            throw new TimeoutException();
303 >        setCompletion(NORMAL); // must be outside try block
304      }
305  
306      // public methods
# Line 482 | Line 339 | public abstract class ForkJoinTask<V> im
339       */
340      public final V join() {
341          quietlyJoin();
342 <        return reportResult();
342 >        Throwable ex;
343 >        if (status < NORMAL && (ex = getException()) != null)
344 >            UNSAFE.throwException(ex);
345 >        return getRawResult();
346      }
347  
348      /**
349       * Commences performing this task, awaits its completion if
350 <     * necessary, and return its result, or throws an (unchecked)
351 <     * exception if the underlying computation did so.
350 >     * necessary, and returns its result, or throws an (unchecked)
351 >     * {@code RuntimeException} or {@code Error} if the underlying
352 >     * computation did so.
353       *
354       * @return the computed result
355       */
356      public final V invoke() {
357 <        if (!tryExec())
358 <            quietlyJoin();
359 <        return reportResult();
357 >        quietlyInvoke();
358 >        Throwable ex;
359 >        if (status < NORMAL && (ex = getException()) != null)
360 >            UNSAFE.throwException(ex);
361 >        return getRawResult();
362      }
363  
364      /**
365       * Forks the given tasks, returning when {@code isDone} holds for
366       * each task or an (unchecked) exception is encountered, in which
367 <     * case the exception is rethrown.  If either task encounters an
368 <     * exception, the other one may be, but is not guaranteed to be,
369 <     * cancelled.  If both tasks throw an exception, then this method
370 <     * throws one of them.  The individual status of each task may be
371 <     * checked using {@link #getException()} and related methods.
367 >     * case the exception is rethrown. If more than one task
368 >     * encounters an exception, then this method throws any one of
369 >     * these exceptions. If any task encounters an exception, the
370 >     * other may be cancelled. However, the execution status of
371 >     * individual tasks is not guaranteed upon exceptional return. The
372 >     * status of each task may be obtained using {@link
373 >     * #getException()} and related methods to check if they have been
374 >     * cancelled, completed normally or exceptionally, or left
375 >     * unprocessed.
376       *
377       * <p>This method may be invoked only from within {@code
378       * ForkJoinTask} computations (as may be determined using method
# Line 526 | Line 393 | public abstract class ForkJoinTask<V> im
393      /**
394       * Forks the given tasks, returning when {@code isDone} holds for
395       * each task or an (unchecked) exception is encountered, in which
396 <     * case the exception is rethrown. If any task encounters an
397 <     * exception, others may be, but are not guaranteed to be,
398 <     * cancelled.  If more than one task encounters an exception, then
399 <     * this method throws any one of these exceptions.  The individual
400 <     * status of each task may be checked using {@link #getException()}
401 <     * and related methods.
396 >     * case the exception is rethrown. If more than one task
397 >     * encounters an exception, then this method throws any one of
398 >     * these exceptions. If any task encounters an exception, others
399 >     * may be cancelled. However, the execution status of individual
400 >     * tasks is not guaranteed upon exceptional return. The status of
401 >     * each task may be obtained using {@link #getException()} and
402 >     * related methods to check if they have been cancelled, completed
403 >     * normally or exceptionally, or left unprocessed.
404       *
405       * <p>This method may be invoked only from within {@code
406       * ForkJoinTask} computations (as may be determined using method
# Line 555 | Line 424 | public abstract class ForkJoinTask<V> im
424                  t.fork();
425              else {
426                  t.quietlyInvoke();
427 <                if (ex == null)
427 >                if (ex == null && t.status < NORMAL)
428                      ex = t.getException();
429              }
430          }
# Line 566 | Line 435 | public abstract class ForkJoinTask<V> im
435                      t.cancel(false);
436                  else {
437                      t.quietlyJoin();
438 <                    if (ex == null)
438 >                    if (ex == null && t.status < NORMAL)
439                          ex = t.getException();
440                  }
441              }
# Line 578 | Line 447 | public abstract class ForkJoinTask<V> im
447      /**
448       * Forks all tasks in the specified collection, returning when
449       * {@code isDone} holds for each task or an (unchecked) exception
450 <     * is encountered.  If any task encounters an exception, others
451 <     * may be, but are not guaranteed to be, cancelled.  If more than
452 <     * one task encounters an exception, then this method throws any
453 <     * one of these exceptions.  The individual status of each task
454 <     * may be checked using {@link #getException()} and related
455 <     * methods.  The behavior of this operation is undefined if the
456 <     * specified collection is modified while the operation is in
457 <     * progress.
450 >     * is encountered, in which case the exception is rethrown. If
451 >     * more than one task encounters an exception, then this method
452 >     * throws any one of these exceptions. If any task encounters an
453 >     * exception, others may be cancelled. However, the execution
454 >     * status of individual tasks is not guaranteed upon exceptional
455 >     * return. The status of each task may be obtained using {@link
456 >     * #getException()} and related methods to check if they have been
457 >     * cancelled, completed normally or exceptionally, or left
458 >     * unprocessed.
459       *
460       * <p>This method may be invoked only from within {@code
461       * ForkJoinTask} computations (as may be determined using method
# Line 617 | Line 487 | public abstract class ForkJoinTask<V> im
487                  t.fork();
488              else {
489                  t.quietlyInvoke();
490 <                if (ex == null)
490 >                if (ex == null && t.status < NORMAL)
491                      ex = t.getException();
492              }
493          }
# Line 628 | Line 498 | public abstract class ForkJoinTask<V> im
498                      t.cancel(false);
499                  else {
500                      t.quietlyJoin();
501 <                    if (ex == null)
501 >                    if (ex == null && t.status < NORMAL)
502                          ex = t.getException();
503                  }
504              }
# Line 664 | Line 534 | public abstract class ForkJoinTask<V> im
534       */
535      public boolean cancel(boolean mayInterruptIfRunning) {
536          setCompletion(CANCELLED);
537 <        return (status & COMPLETION_MASK) == CANCELLED;
537 >        return status == CANCELLED;
538      }
539  
540      /**
541 <     * Cancels, ignoring any exceptions it throws. Used during worker
542 <     * and pool shutdown.
541 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
542 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
543 >     * exceptions, but if it does anyway, we have no recourse during
544 >     * shutdown, so guard against this case.
545       */
546      final void cancelIgnoringExceptions() {
547          try {
# Line 679 | Line 551 | public abstract class ForkJoinTask<V> im
551      }
552  
553      /**
554 <     * Cancels ignoring exceptions if worker is terminating
554 >     * Cancels if current thread is a terminating worker thread,
555 >     * ignoring any exceptions thrown by cancel.
556       */
557 <    private void cancelIfTerminating() {
557 >    final void cancelIfTerminating() {
558          Thread t = Thread.currentThread();
559          if ((t instanceof ForkJoinWorkerThread) &&
560              ((ForkJoinWorkerThread) t).isTerminating()) {
# Line 697 | Line 570 | public abstract class ForkJoinTask<V> im
570      }
571  
572      public final boolean isCancelled() {
573 <        return (status & COMPLETION_MASK) == CANCELLED;
573 >        return status == CANCELLED;
574      }
575  
576      /**
# Line 706 | Line 579 | public abstract class ForkJoinTask<V> im
579       * @return {@code true} if this task threw an exception or was cancelled
580       */
581      public final boolean isCompletedAbnormally() {
582 <        return (status & COMPLETION_MASK) < NORMAL;
582 >        return status < NORMAL;
583      }
584  
585      /**
# Line 717 | Line 590 | public abstract class ForkJoinTask<V> im
590       * exception and was not cancelled
591       */
592      public final boolean isCompletedNormally() {
593 <        return (status & COMPLETION_MASK) == NORMAL;
593 >        return status == NORMAL;
594      }
595  
596      /**
# Line 728 | Line 601 | public abstract class ForkJoinTask<V> im
601       * @return the exception, or {@code null} if none
602       */
603      public final Throwable getException() {
604 <        int s = status & COMPLETION_MASK;
604 >        int s = status;
605          return ((s >= NORMAL)    ? null :
606                  (s == CANCELLED) ? new CancellationException() :
607                  exceptionMap.get(this));
# Line 749 | Line 622 | public abstract class ForkJoinTask<V> im
622       * thrown will be a {@code RuntimeException} with cause {@code ex}.
623       */
624      public void completeExceptionally(Throwable ex) {
625 <        setDoneExceptionally((ex instanceof RuntimeException) ||
626 <                             (ex instanceof Error) ? ex :
627 <                             new RuntimeException(ex));
625 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
626 >                                 (ex instanceof Error) ? ex :
627 >                                 new RuntimeException(ex));
628      }
629  
630      /**
631       * Completes this task, and if not already aborted or cancelled,
632 <     * returning a {@code null} result upon {@code join} and related
633 <     * operations. This method may be used to provide results for
634 <     * asynchronous tasks, or to provide alternative handling for
635 <     * tasks that would not otherwise complete normally. Its use in
636 <     * other situations is discouraged. This method is
637 <     * overridable, but overridden versions must invoke {@code super}
638 <     * implementation to maintain guarantees.
632 >     * returning the given value as the result of subsequent
633 >     * invocations of {@code join} and related operations. This method
634 >     * may be used to provide results for asynchronous tasks, or to
635 >     * provide alternative handling for tasks that would not otherwise
636 >     * complete normally. Its use in other situations is
637 >     * discouraged. This method is overridable, but overridden
638 >     * versions must invoke {@code super} implementation to maintain
639 >     * guarantees.
640       *
641       * @param value the result value for this task
642       */
# Line 770 | Line 644 | public abstract class ForkJoinTask<V> im
644          try {
645              setRawResult(value);
646          } catch (Throwable rex) {
647 <            setDoneExceptionally(rex);
647 >            setExceptionalCompletion(rex);
648              return;
649          }
650          setCompletion(NORMAL);
651      }
652  
779    public final V get() throws InterruptedException, ExecutionException {
780        quietlyJoin();
781        return reportFutureResult();
782    }
783
784    public final V get(long timeout, TimeUnit unit)
785        throws InterruptedException, ExecutionException, TimeoutException {
786        long nanos = unit.toNanos(timeout);
787        Thread t = Thread.currentThread();
788        if (t instanceof ForkJoinWorkerThread) {
789            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
790            if (!w.unpushTask(this) || !tryExec())
791                timedAwaitDone(w, nanos);
792        }
793        else
794            externalTimedAwaitDone(nanos);
795        return reportTimedFutureResult();
796    }
797
653      /**
654 <     * Possibly executes other tasks until this task {@link #isDone is
655 <     * done}, then returns the result of the computation.  This method
801 <     * may be more efficient than {@code join}, but is only applicable
802 <     * when there are no potential dependencies between continuation
803 <     * of the current task and that of any other task that might be
804 <     * executed while helping. (This usually holds for pure
805 <     * divide-and-conquer tasks).
806 <     *
807 <     * <p>This method may be invoked only from within {@code
808 <     * ForkJoinTask} computations (as may be determined using method
809 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
810 <     * result in exceptions or errors, possibly including {@code
811 <     * ClassCastException}.
654 >     * Waits if necessary for the computation to complete, and then
655 >     * retrieves its result.
656       *
657       * @return the computed result
658 +     * @throws CancellationException if the computation was cancelled
659 +     * @throws ExecutionException if the computation threw an
660 +     * exception
661 +     * @throws InterruptedException if the current thread is not a
662 +     * member of a ForkJoinPool and was interrupted while waiting
663       */
664 <    public final V helpJoin() {
665 <        quietlyHelpJoin();
666 <        return reportResult();
664 >    public final V get() throws InterruptedException, ExecutionException {
665 >        int s;
666 >        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
667 >            quietlyJoin();
668 >            s = status;
669 >        }
670 >        else {
671 >            while ((s = status) >= 0) {
672 >                synchronized (this) { // interruptible form of awaitDone
673 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
674 >                                                 s, SIGNAL)) {
675 >                        while (status >= 0)
676 >                            wait();
677 >                    }
678 >                }
679 >            }
680 >        }
681 >        if (s < NORMAL) {
682 >            Throwable ex;
683 >            if (s == CANCELLED)
684 >                throw new CancellationException();
685 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
686 >                throw new ExecutionException(ex);
687 >        }
688 >        return getRawResult();
689      }
690  
691      /**
692 <     * Possibly executes other tasks until this task {@link #isDone is
693 <     * done}.  This method may be useful when processing collections
823 <     * of tasks when some have been cancelled or otherwise known to
824 <     * have aborted.
692 >     * Waits if necessary for at most the given time for the computation
693 >     * to complete, and then retrieves its result, if available.
694       *
695 <     * <p>This method may be invoked only from within {@code
696 <     * ForkJoinTask} computations (as may be determined using method
697 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
698 <     * result in exceptions or errors, possibly including {@code
699 <     * ClassCastException}.
695 >     * @param timeout the maximum time to wait
696 >     * @param unit the time unit of the timeout argument
697 >     * @return the computed result
698 >     * @throws CancellationException if the computation was cancelled
699 >     * @throws ExecutionException if the computation threw an
700 >     * exception
701 >     * @throws InterruptedException if the current thread is not a
702 >     * member of a ForkJoinPool and was interrupted while waiting
703 >     * @throws TimeoutException if the wait timed out
704       */
705 <    public final void quietlyHelpJoin() {
706 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
707 <        if (!w.unpushTask(this) || !tryExec()) {
708 <            for (;;) {
709 <                ForkJoinTask<?> t;
710 <                if (status < 0)
711 <                    return;
712 <                else if ((t = w.scanWhileJoining(this)) != null)
713 <                    t.tryExec();
714 <                else if (status < 0)
715 <                    return;
716 <                else if (w.pool.preBlockHelpingJoin(this)) {
717 <                    while (status >= 0) { // variant of awaitDone
718 <                        try {
719 <                            synchronized(this) {
720 <                                if (status >= 0)
721 <                                    wait();
722 <                                else {
723 <                                    notifyAll();
724 <                                    break;
725 <                                }
726 <                            }
727 <                        } catch (InterruptedException ie) {
728 <                            cancelIfTerminating();
705 >    public final V get(long timeout, TimeUnit unit)
706 >        throws InterruptedException, ExecutionException, TimeoutException {
707 >        long nanos = unit.toNanos(timeout);
708 >        if (status >= 0) {
709 >            Thread t = Thread.currentThread();
710 >            if (t instanceof ForkJoinWorkerThread) {
711 >                ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
712 >                boolean completed = false; // timed variant of quietlyJoin
713 >                if (w.unpushTask(this)) {
714 >                    try {
715 >                        completed = exec();
716 >                    } catch (Throwable rex) {
717 >                        setExceptionalCompletion(rex);
718 >                    }
719 >                }
720 >                if (completed)
721 >                    setCompletion(NORMAL);
722 >                else if (status >= 0)
723 >                    w.joinTask(this, true, nanos);
724 >            }
725 >            else if (Thread.interrupted())
726 >                throw new InterruptedException();
727 >            else {
728 >                long startTime = System.nanoTime();
729 >                int s; long nt;
730 >                while ((s = status) >= 0 &&
731 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
732 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,
733 >                                                 SIGNAL)) {
734 >                        long ms = nt / 1000000;
735 >                        int ns = (int) (nt % 1000000);
736 >                        synchronized (this) {
737 >                            if (status >= 0)
738 >                                wait(ms, ns); // exit on IE throw
739                          }
740                      }
858                    return;
741                  }
742              }
743          }
744 +        int es = status;
745 +        if (es != NORMAL) {
746 +            Throwable ex;
747 +            if (es == CANCELLED)
748 +                throw new CancellationException();
749 +            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
750 +                throw new ExecutionException(ex);
751 +            throw new TimeoutException();
752 +        }
753 +        return getRawResult();
754      }
755  
756      /**
757 <     * Joins this task, without returning its result or throwing an
757 >     * Joins this task, without returning its result or throwing its
758       * exception. This method may be useful when processing
759       * collections of tasks when some have been cancelled or otherwise
760       * known to have aborted.
761       */
762      public final void quietlyJoin() {
763 <        Thread t = Thread.currentThread();
764 <        if (t instanceof ForkJoinWorkerThread) {
763 >        Thread t;
764 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
765              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
766 <            if (!w.unpushTask(this) || !tryExec())
767 <                awaitDone(w);
766 >            if (status >= 0) {
767 >                if (w.unpushTask(this)) {
768 >                    boolean completed;
769 >                    try {
770 >                        completed = exec();
771 >                    } catch (Throwable rex) {
772 >                        setExceptionalCompletion(rex);
773 >                        return;
774 >                    }
775 >                    if (completed) {
776 >                        setCompletion(NORMAL);
777 >                        return;
778 >                    }
779 >                }
780 >                w.joinTask(this, false, 0L);
781 >            }
782          }
783          else
784              externalAwaitDone();
# Line 880 | Line 786 | public abstract class ForkJoinTask<V> im
786  
787      /**
788       * Commences performing this task and awaits its completion if
789 <     * necessary, without returning its result or throwing an
790 <     * exception. This method may be useful when processing
885 <     * collections of tasks when some have been cancelled or otherwise
886 <     * known to have aborted.
789 >     * necessary, without returning its result or throwing its
790 >     * exception.
791       */
792      public final void quietlyInvoke() {
793 <        if (!tryExec())
794 <            quietlyJoin();
793 >        if (status >= 0) {
794 >            boolean completed;
795 >            try {
796 >                completed = exec();
797 >            } catch (Throwable rex) {
798 >                setExceptionalCompletion(rex);
799 >                return;
800 >            }
801 >            if (completed)
802 >                setCompletion(NORMAL);
803 >            else
804 >                quietlyJoin();
805 >        }
806      }
807  
808      /**
# Line 919 | Line 834 | public abstract class ForkJoinTask<V> im
834       * pre-constructed trees of subtasks in loops.
835       */
836      public void reinitialize() {
837 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
837 >        if (status == EXCEPTIONAL)
838              exceptionMap.remove(this);
839          status = 0;
840      }
# Line 1209 | Line 1124 | public abstract class ForkJoinTask<V> im
1124      private static final long serialVersionUID = -7721805057305804111L;
1125  
1126      /**
1127 <     * Saves the state to a stream.
1127 >     * Saves the state to a stream (that is, serializes it).
1128       *
1129       * @serialData the current run status and the exception thrown
1130       * during execution, or {@code null} if none
# Line 1222 | Line 1137 | public abstract class ForkJoinTask<V> im
1137      }
1138  
1139      /**
1140 <     * Reconstitutes the instance from a stream.
1140 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1141       *
1142       * @param s the stream
1143       */
1144      private void readObject(java.io.ObjectInputStream s)
1145          throws java.io.IOException, ClassNotFoundException {
1146          s.defaultReadObject();
1232        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1233        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1147          Object ex = s.readObject();
1148          if (ex != null)
1149 <            setDoneExceptionally((Throwable) ex);
1149 >            setExceptionalCompletion((Throwable) ex);
1150      }
1151  
1152      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines