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.46 by dl, Mon Apr 5 15:52:26 2010 UTC vs.
Revision 1.72 by dl, Wed Nov 24 10:50:38 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>Method {@link #join} and its variants are appropriate for use
114 > * only when completion dependencies are acyclic; that is, the
115 > * parallel computation can be described as a directed acyclic graph
116 > * (DAG). Otherwise, executions may encounter a form of deadlock as
117 > * tasks cyclically wait for each other.  However, this framework
118 > * supports other methods and techniques (for example the use of
119 > * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
120 > * may be of use in constructing custom subclasses for problems that
121 > * are not statically structured as DAGs.
122   *
123   * <p>Most base support methods are {@code final}, to prevent
124   * overriding of implementations that are intrinsically tied to the
# Line 119 | Line 134 | import java.util.WeakHashMap;
134   * computation. Large tasks should be split into smaller subtasks,
135   * usually via recursive decomposition. As a very rough rule of thumb,
136   * a task should perform more than 100 and less than 10000 basic
137 < * computational steps. If tasks are too big, then parallelism cannot
138 < * improve throughput. If too small, then memory and internal task
139 < * maintenance overhead may overwhelm processing.
137 > * computational steps, and should avoid indefinite looping. If tasks
138 > * are too big, then parallelism cannot improve throughput. If too
139 > * small, then memory and internal task maintenance overhead may
140 > * overwhelm processing.
141   *
142   * <p>This class provides {@code adapt} methods for {@link Runnable}
143   * and {@link Callable}, that may be of use when mixing execution of
144 < * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
145 < * are of this form, consider using a pool in
130 < * {@linkplain ForkJoinPool#setAsyncMode async mode}.
144 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
145 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
146   *
147   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
148   * used in extensions such as remote execution frameworks. It is
# Line 148 | Line 163 | public abstract class ForkJoinTask<V> im
163       * status maintenance (2) execution and awaiting completion (3)
164       * user-level methods that additionally report results. This is
165       * sometimes hard to see because this file orders exported methods
166 <     * in a way that flows well in javadocs.
166 >     * in a way that flows well in javadocs. In particular, most
167 >     * join mechanics are in method quietlyJoin, below.
168       */
169  
170 <    /**
171 <     * Run control status bits packed into a single int to minimize
172 <     * footprint and to ensure atomicity (via CAS).  Status is
173 <     * initially zero, and takes on nonnegative values until
174 <     * completed, upon which status holds COMPLETED. CANCELLED, or
175 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
176 <     * blocking waits by other threads have SIGNAL_MASK bits set --
177 <     * bit 15 for external (nonFJ) waits, and the rest a count of
178 <     * waiting FJ threads.  (This representation relies on
179 <     * ForkJoinPool max thread limits). Signal counts are not directly
180 <     * incremented by ForkJoinTask methods, but instead via a call to
181 <     * requestSignal within ForkJoinPool.preJoin, once their need is
182 <     * established.
183 <     *
184 <     * 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.
170 >    /*
171 >     * The status field holds run control status bits packed into a
172 >     * single int to minimize footprint and to ensure atomicity (via
173 >     * CAS).  Status is initially zero, and takes on nonnegative
174 >     * values until completed, upon which status holds value
175 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
176 >     * waits by other threads have the SIGNAL bit set.  Completion of
177 >     * a stolen task with SIGNAL set awakens any waiters via
178 >     * notifyAll. Even though suboptimal for some purposes, we use
179 >     * basic builtin wait/notify to take advantage of "monitor
180 >     * inflation" in JVMs that we would otherwise need to emulate to
181 >     * avoid adding further per-task bookkeeping overhead.  We want
182 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
183 >     * techniques, so use some odd coding idioms that tend to avoid
184 >     * them.
185       */
186 +
187 +    /** The run status of this task */
188      volatile int status; // accessed directly by pool and workers
189  
190 <    private static final int COMPLETION_MASK      = 0xe0000000;
191 <    private static final int NORMAL               = 0xe0000000; // == mask
192 <    private static final int CANCELLED            = 0xc0000000;
193 <    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;
190 >    private static final int NORMAL      = -1;
191 >    private static final int CANCELLED   = -2;
192 >    private static final int EXCEPTIONAL = -3;
193 >    private static final int SIGNAL      =  1;
194  
195      /**
196       * Table of exceptions thrown by tasks, to enable reporting by
# Line 211 | Line 216 | public abstract class ForkJoinTask<V> im
216          int s;
217          while ((s = status) >= 0) {
218              if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
219 <                if ((s & SIGNAL_MASK) != 0) {
215 <                    Thread t = Thread.currentThread();
216 <                    if (t instanceof ForkJoinWorkerThread)
217 <                        ((ForkJoinWorkerThread) t).pool.updateRunningCount
218 <                            (s & INTERNAL_SIGNAL_MASK);
219 >                if (s != 0)
220                      synchronized (this) { notifyAll(); }
221 <                }
221 <                return;
221 >                break;
222              }
223          }
224      }
225  
226      /**
227 <     * Record exception and set exceptional completion
227 >     * Records exception and sets exceptional completion.
228 >     *
229 >     * @return status on exit
230       */
231 <    private void setDoneExceptionally(Throwable rex) {
231 >    private void setExceptionalCompletion(Throwable rex) {
232          exceptionMap.put(this, rex);
233          setCompletion(EXCEPTIONAL);
234      }
235  
236      /**
237 <     * Main internal execution method: Unless done, calls exec and
238 <     * records completion.
237 <     *
238 <     * @return true if ran and completed normally
239 <     */
240 <    final boolean tryExec() {
241 <        try {
242 <            if (status < 0 || !exec())
243 <                return false;
244 <        } catch (Throwable rex) {
245 <            setDoneExceptionally(rex);
246 <            return false;
247 <        }
248 <        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;
264 <    }
265 <    
266 <    /**
267 <     * Sets external signal request unless already done.
268 <     *
269 <     * @return status
270 <     */
271 <    private int requestExternalSignal() {
272 <        int s;
273 <        do {} while ((s = status) >= 0 &&
274 <                     !UNSAFE.compareAndSwapInt(this, statusOffset,
275 <                                               s, s | EXTERNAL_SIGNAL));
276 <        return s;
277 <    }
278 <
279 <    /*
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
237 >     * Blocks a worker thread until completed or timed out.  Called
238 >     * only by pool.
239       */
240 <    private void awaitDone(ForkJoinWorkerThread w) {
241 <        if (status >= 0) {
242 <            w.pool.preJoin(this);
243 <            while (status >= 0) {
244 <                try { // minimize lock scope
245 <                    synchronized(this) {
246 <                        if (status >= 0)
247 <                            wait();
248 <                        else { // help release; also helps avoid lock-biasing
249 <                            notifyAll();
250 <                            break;
300 <                        }
301 <                    }
302 <                } catch (InterruptedException ie) {
303 <                    cancelIfTerminating();
240 >    final void internalAwaitDone(long millis, int nanos) {
241 >        int s = status;
242 >        if ((s == 0 &&
243 >             UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL)) ||
244 >            s > 0)  {
245 >            try {     // the odd construction reduces lock bias effects
246 >                synchronized (this) {
247 >                    if (status > 0)
248 >                        wait(millis, nanos);
249 >                    else
250 >                        notifyAll();
251                  }
252 +            } catch (InterruptedException ie) {
253 +                cancelIfTerminating();
254              }
255          }
256      }
257  
258      /**
259 <     * Blocks a non-ForkJoin thread until this task is done.
259 >     * Blocks a non-worker-thread until completion.
260       */
261      private void externalAwaitDone() {
262 <        if (requestExternalSignal() >= 0) {
262 >        if (status >= 0) {
263              boolean interrupted = false;
264 <            while (status >= 0) {
265 <                try {
266 <                    synchronized(this) {
267 <                        if (status >= 0)
268 <                            wait();
269 <                        else {
270 <                            notifyAll();
271 <                            break;
264 >            synchronized(this) {
265 >                for (;;) {
266 >                    int s = status;
267 >                    if (s == 0)
268 >                        UNSAFE.compareAndSwapInt(this, statusOffset,
269 >                                                 0, SIGNAL);
270 >                    else if (s < 0) {
271 >                        notifyAll();
272 >                        break;
273 >                    }
274 >                    else {
275 >                        try {
276 >                            wait();
277 >                        } catch (InterruptedException ie) {
278 >                            interrupted = true;
279                          }
280                      }
325                } catch (InterruptedException ie) {
326                    interrupted = true;
281                  }
282              }
283              if (interrupted)
# Line 332 | Line 286 | public abstract class ForkJoinTask<V> im
286      }
287  
288      /**
289 <     * Blocks a worker until this task is done or timeout elapses
289 >     * Blocks a non-worker-thread until completion or interruption or timeout.
290       */
291 <    private void timedAwaitDone(ForkJoinWorkerThread w, long nanos) {
291 >    private void externalInterruptibleAwaitDone(boolean timed, long nanos)
292 >        throws InterruptedException {
293 >        if (Thread.interrupted())
294 >            throw new InterruptedException();
295          if (status >= 0) {
296 <            long startTime = System.nanoTime();
297 <            ForkJoinPool pool = w.pool;
298 <            pool.preJoin(this);
299 <            while (status >= 0) {
300 <                long nt = nanos - (System.nanoTime() - startTime);
301 <                if (nt > 0) {
302 <                    long ms = nt / 1000000;
303 <                    int ns = (int) (nt % 1000000);
304 <                    try {
305 <                        synchronized(this) { if (status >= 0) wait(ms, ns); }
306 <                    } catch (InterruptedException ie) {
350 <                        cancelIfTerminating();
351 <                    }
352 <                }
353 <                else {
354 <                    int s; // adjust running count on timeout
355 <                    while ((s = status) >= 0 &&
356 <                           (s & INTERNAL_SIGNAL_MASK) != 0) {
357 <                        if (UNSAFE.compareAndSwapInt(this, statusOffset,
358 <                                                     s, s - 1)) {
359 <                            pool.updateRunningCount(1);
360 <                            break;
361 <                        }
296 >            long startTime = timed ? System.nanoTime() : 0L;
297 >            synchronized(this) {
298 >                for (;;) {
299 >                    long nt;
300 >                    int s = status;
301 >                    if (s == 0)
302 >                        UNSAFE.compareAndSwapInt(this, statusOffset,
303 >                                                 0, SIGNAL);
304 >                    else if (s < 0) {
305 >                        notifyAll();
306 >                        break;
307                      }
308 <                    break;
309 <                }
310 <            }
311 <        }
312 <    }
313 <
369 <    /**
370 <     * Blocks a non-ForkJoin thread until this task is done or timeout elapses
371 <     */
372 <    private void externalTimedAwaitDone(long nanos) {
373 <        if (requestExternalSignal() >= 0) {
374 <            long startTime = System.nanoTime();
375 <            boolean interrupted = false;
376 <            while (status >= 0) {
377 <                long nt = nanos - (System.nanoTime() - startTime);
378 <                if (nt <= 0)
379 <                    break;
380 <                long ms = nt / 1000000;
381 <                int ns = (int) (nt % 1000000);
382 <                try {
383 <                    synchronized(this) { if (status >= 0) wait(ms, ns); }
384 <                } catch (InterruptedException ie) {
385 <                    interrupted = true;
308 >                    else if (!timed)
309 >                        wait();
310 >                    else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
311 >                        wait(nt / 1000000, (int)(nt % 1000000));
312 >                    else
313 >                        break;
314                  }
315              }
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);
316          }
406        return getRawResult();
317      }
318  
319      /**
320 <     * Returns result or throws exception using j.u.c.Future conventions.
321 <     * Only call when {@code isDone} known to be true or thread known
322 <     * to be interrupted.
320 >     * Unless done, calls exec and records status if completed, but
321 >     * doesn't wait for completion otherwise. Primary execution method
322 >     * for ForkJoinWorkerThread.
323       */
324 <    private V reportFutureResult()
325 <        throws InterruptedException, ExecutionException {
326 <        if (Thread.interrupted())
327 <            throw new InterruptedException();
328 <        int s = status & COMPLETION_MASK;
329 <        if (s < NORMAL) {
330 <            Throwable ex;
421 <            if (s == CANCELLED)
422 <                throw new CancellationException();
423 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
424 <                throw new ExecutionException(ex);
324 >    final void quietlyExec() {
325 >        try {
326 >            if (status < 0 || !exec())
327 >                return;
328 >        } catch (Throwable rex) {
329 >            setExceptionalCompletion(rex);
330 >            return;
331          }
332 <        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();
332 >        setCompletion(NORMAL); // must be outside try block
333      }
334  
335      // public methods
# Line 459 | Line 345 | public abstract class ForkJoinTask<V> im
345       * #isDone} returning {@code true}.
346       *
347       * <p>This method may be invoked only from within {@code
348 <     * ForkJoinTask} computations (as may be determined using method
348 >     * ForkJoinPool} computations (as may be determined using method
349       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
350       * result in exceptions or errors, possibly including {@code
351       * ClassCastException}.
# Line 473 | Line 359 | public abstract class ForkJoinTask<V> im
359      }
360  
361      /**
362 <     * Returns the result of the computation when it {@link #isDone is done}.
363 <     * This method differs from {@link #get()} in that
362 >     * Returns the result of the computation when it {@link #isDone is
363 >     * done}.  This method differs from {@link #get()} in that
364       * abnormal completion results in {@code RuntimeException} or
365 <     * {@code Error}, not {@code ExecutionException}.
365 >     * {@code Error}, not {@code ExecutionException}, and that
366 >     * interrupts of the calling thread do <em>not</em> cause the
367 >     * method to abruptly return by throwing {@code
368 >     * InterruptedException}.
369       *
370       * @return the computed result
371       */
372      public final V join() {
373          quietlyJoin();
374 <        return reportResult();
374 >        Throwable ex;
375 >        if (status < NORMAL && (ex = getException()) != null)
376 >            UNSAFE.throwException(ex);
377 >        return getRawResult();
378      }
379  
380      /**
381       * Commences performing this task, awaits its completion if
382 <     * necessary, and return its result, or throws an (unchecked)
383 <     * exception if the underlying computation did so.
382 >     * necessary, and returns its result, or throws an (unchecked)
383 >     * {@code RuntimeException} or {@code Error} if the underlying
384 >     * computation did so.
385       *
386       * @return the computed result
387       */
388      public final V invoke() {
389 <        if (!tryExec())
390 <            quietlyJoin();
391 <        return reportResult();
389 >        quietlyInvoke();
390 >        Throwable ex;
391 >        if (status < NORMAL && (ex = getException()) != null)
392 >            UNSAFE.throwException(ex);
393 >        return getRawResult();
394      }
395  
396      /**
397       * Forks the given tasks, returning when {@code isDone} holds for
398       * each task or an (unchecked) exception is encountered, in which
399 <     * case the exception is rethrown.  If either task encounters an
400 <     * exception, the other one may be, but is not guaranteed to be,
401 <     * cancelled.  If both tasks throw an exception, then this method
402 <     * throws one of them.  The individual status of each task may be
403 <     * checked using {@link #getException()} and related methods.
399 >     * case the exception is rethrown. If more than one task
400 >     * encounters an exception, then this method throws any one of
401 >     * these exceptions. If any task encounters an exception, the
402 >     * other may be cancelled. However, the execution status of
403 >     * individual tasks is not guaranteed upon exceptional return. The
404 >     * status of each task may be obtained using {@link
405 >     * #getException()} and related methods to check if they have been
406 >     * cancelled, completed normally or exceptionally, or left
407 >     * unprocessed.
408       *
409       * <p>This method may be invoked only from within {@code
410 <     * ForkJoinTask} computations (as may be determined using method
410 >     * ForkJoinPool} computations (as may be determined using method
411       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
412       * result in exceptions or errors, possibly including {@code
413       * ClassCastException}.
# Line 526 | Line 425 | public abstract class ForkJoinTask<V> im
425      /**
426       * Forks the given tasks, returning when {@code isDone} holds for
427       * each task or an (unchecked) exception is encountered, in which
428 <     * case the exception is rethrown. If any task encounters an
429 <     * exception, others may be, but are not guaranteed to be,
430 <     * cancelled.  If more than one task encounters an exception, then
431 <     * this method throws any one of these exceptions.  The individual
432 <     * status of each task may be checked using {@link #getException()}
433 <     * and related methods.
428 >     * case the exception is rethrown. If more than one task
429 >     * encounters an exception, then this method throws any one of
430 >     * these exceptions. If any task encounters an exception, others
431 >     * may be cancelled. However, the execution status of individual
432 >     * tasks is not guaranteed upon exceptional return. The status of
433 >     * each task may be obtained using {@link #getException()} and
434 >     * related methods to check if they have been cancelled, completed
435 >     * normally or exceptionally, or left unprocessed.
436       *
437       * <p>This method may be invoked only from within {@code
438 <     * ForkJoinTask} computations (as may be determined using method
438 >     * ForkJoinPool} computations (as may be determined using method
439       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
440       * result in exceptions or errors, possibly including {@code
441       * ClassCastException}.
# Line 555 | Line 456 | public abstract class ForkJoinTask<V> im
456                  t.fork();
457              else {
458                  t.quietlyInvoke();
459 <                if (ex == null)
459 >                if (ex == null && t.status < NORMAL)
460                      ex = t.getException();
461              }
462          }
# Line 566 | Line 467 | public abstract class ForkJoinTask<V> im
467                      t.cancel(false);
468                  else {
469                      t.quietlyJoin();
470 <                    if (ex == null)
470 >                    if (ex == null && t.status < NORMAL)
471                          ex = t.getException();
472                  }
473              }
# Line 578 | Line 479 | public abstract class ForkJoinTask<V> im
479      /**
480       * Forks all tasks in the specified collection, returning when
481       * {@code isDone} holds for each task or an (unchecked) exception
482 <     * is encountered.  If any task encounters an exception, others
483 <     * may be, but are not guaranteed to be, cancelled.  If more than
484 <     * one task encounters an exception, then this method throws any
485 <     * one of these exceptions.  The individual status of each task
486 <     * may be checked using {@link #getException()} and related
487 <     * methods.  The behavior of this operation is undefined if the
488 <     * specified collection is modified while the operation is in
489 <     * progress.
482 >     * is encountered, in which case the exception is rethrown. If
483 >     * more than one task encounters an exception, then this method
484 >     * throws any one of these exceptions. If any task encounters an
485 >     * exception, others may be cancelled. However, the execution
486 >     * status of individual tasks is not guaranteed upon exceptional
487 >     * return. The status of each task may be obtained using {@link
488 >     * #getException()} and related methods to check if they have been
489 >     * cancelled, completed normally or exceptionally, or left
490 >     * unprocessed.
491       *
492       * <p>This method may be invoked only from within {@code
493 <     * ForkJoinTask} computations (as may be determined using method
493 >     * ForkJoinPool} computations (as may be determined using method
494       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
495       * result in exceptions or errors, possibly including {@code
496       * ClassCastException}.
# Line 617 | Line 519 | public abstract class ForkJoinTask<V> im
519                  t.fork();
520              else {
521                  t.quietlyInvoke();
522 <                if (ex == null)
522 >                if (ex == null && t.status < NORMAL)
523                      ex = t.getException();
524              }
525          }
# Line 628 | Line 530 | public abstract class ForkJoinTask<V> im
530                      t.cancel(false);
531                  else {
532                      t.quietlyJoin();
533 <                    if (ex == null)
533 >                    if (ex == null && t.status < NORMAL)
534                          ex = t.getException();
535                  }
536              }
# Line 640 | Line 542 | public abstract class ForkJoinTask<V> im
542  
543      /**
544       * Attempts to cancel execution of this task. This attempt will
545 <     * fail if the task has already completed, has already been
546 <     * cancelled, or could not be cancelled for some other reason. If
547 <     * successful, and this task has not started when cancel is
548 <     * called, execution of this task is suppressed, {@link
549 <     * #isCancelled} will report true, and {@link #join} will result
550 <     * in a {@code CancellationException} being thrown.
545 >     * fail if the task has already completed or could not be
546 >     * cancelled for some other reason. If successful, and this task
547 >     * has not started when {@code cancel} is called, execution of
548 >     * this task is suppressed. After this method returns
549 >     * successfully, unless there is an intervening call to {@link
550 >     * #reinitialize}, subsequent calls to {@link #isCancelled},
551 >     * {@link #isDone}, and {@code cancel} will return {@code true}
552 >     * and calls to {@link #join} and related methods will result in
553 >     * {@code CancellationException}.
554       *
555       * <p>This method may be overridden in subclasses, but if so, must
556 <     * still ensure that these minimal properties hold. In particular,
557 <     * the {@code cancel} method itself must not throw exceptions.
556 >     * still ensure that these properties hold. In particular, the
557 >     * {@code cancel} method itself must not throw exceptions.
558       *
559       * <p>This method is designed to be invoked by <em>other</em>
560       * tasks. To terminate the current task, you can just return or
561       * throw an unchecked exception from its computation method, or
562       * invoke {@link #completeExceptionally}.
563       *
564 <     * @param mayInterruptIfRunning this value is ignored in the
565 <     * default implementation because tasks are not
566 <     * cancelled via interruption
564 >     * @param mayInterruptIfRunning this value has no effect in the
565 >     * default implementation because interrupts are not used to
566 >     * control cancellation.
567       *
568       * @return {@code true} if this task is now cancelled
569       */
570      public boolean cancel(boolean mayInterruptIfRunning) {
571          setCompletion(CANCELLED);
572 <        return (status & COMPLETION_MASK) == CANCELLED;
572 >        return status == CANCELLED;
573      }
574  
575      /**
576 <     * Cancels, ignoring any exceptions it throws. Used during worker
577 <     * and pool shutdown.
576 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
577 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
578 >     * exceptions, but if it does anyway, we have no recourse during
579 >     * shutdown, so guard against this case.
580       */
581      final void cancelIgnoringExceptions() {
582          try {
# Line 679 | Line 586 | public abstract class ForkJoinTask<V> im
586      }
587  
588      /**
589 <     * Cancels ignoring exceptions if worker is terminating
589 >     * Cancels if current thread is a terminating worker thread,
590 >     * ignoring any exceptions thrown by cancel.
591       */
592 <    private void cancelIfTerminating() {
592 >    final void cancelIfTerminating() {
593          Thread t = Thread.currentThread();
594          if ((t instanceof ForkJoinWorkerThread) &&
595 <            ((ForkJoinWorkerThread) t).isTerminating()) {
595 >            ((ForkJoinWorkerThread) t).isTerminating()) {
596              try {
597                  cancel(false);
598              } catch (Throwable ignore) {
# Line 697 | Line 605 | public abstract class ForkJoinTask<V> im
605      }
606  
607      public final boolean isCancelled() {
608 <        return (status & COMPLETION_MASK) == CANCELLED;
608 >        return status == CANCELLED;
609      }
610  
611      /**
# Line 706 | Line 614 | public abstract class ForkJoinTask<V> im
614       * @return {@code true} if this task threw an exception or was cancelled
615       */
616      public final boolean isCompletedAbnormally() {
617 <        return (status & COMPLETION_MASK) < NORMAL;
617 >        return status < NORMAL;
618      }
619  
620      /**
# Line 717 | Line 625 | public abstract class ForkJoinTask<V> im
625       * exception and was not cancelled
626       */
627      public final boolean isCompletedNormally() {
628 <        return (status & COMPLETION_MASK) == NORMAL;
628 >        return status == NORMAL;
629      }
630  
631      /**
# Line 728 | Line 636 | public abstract class ForkJoinTask<V> im
636       * @return the exception, or {@code null} if none
637       */
638      public final Throwable getException() {
639 <        int s = status & COMPLETION_MASK;
639 >        int s = status;
640          return ((s >= NORMAL)    ? null :
641                  (s == CANCELLED) ? new CancellationException() :
642                  exceptionMap.get(this));
# Line 749 | Line 657 | public abstract class ForkJoinTask<V> im
657       * thrown will be a {@code RuntimeException} with cause {@code ex}.
658       */
659      public void completeExceptionally(Throwable ex) {
660 <        setDoneExceptionally((ex instanceof RuntimeException) ||
661 <                             (ex instanceof Error) ? ex :
662 <                             new RuntimeException(ex));
660 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
661 >                                 (ex instanceof Error) ? ex :
662 >                                 new RuntimeException(ex));
663      }
664  
665      /**
666       * Completes this task, and if not already aborted or cancelled,
667 <     * returning a {@code null} result upon {@code join} and related
668 <     * operations. This method may be used to provide results for
669 <     * asynchronous tasks, or to provide alternative handling for
670 <     * tasks that would not otherwise complete normally. Its use in
671 <     * other situations is discouraged. This method is
672 <     * overridable, but overridden versions must invoke {@code super}
673 <     * implementation to maintain guarantees.
667 >     * returning the given value as the result of subsequent
668 >     * invocations of {@code join} and related operations. This method
669 >     * may be used to provide results for asynchronous tasks, or to
670 >     * provide alternative handling for tasks that would not otherwise
671 >     * complete normally. Its use in other situations is
672 >     * discouraged. This method is overridable, but overridden
673 >     * versions must invoke {@code super} implementation to maintain
674 >     * guarantees.
675       *
676       * @param value the result value for this task
677       */
# Line 770 | Line 679 | public abstract class ForkJoinTask<V> im
679          try {
680              setRawResult(value);
681          } catch (Throwable rex) {
682 <            setDoneExceptionally(rex);
682 >            setExceptionalCompletion(rex);
683              return;
684          }
685          setCompletion(NORMAL);
686      }
687  
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
688      /**
689 <     * Possibly executes other tasks until this task {@link #isDone is
690 <     * 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}.
689 >     * Waits if necessary for the computation to complete, and then
690 >     * retrieves its result.
691       *
692       * @return the computed result
693 +     * @throws CancellationException if the computation was cancelled
694 +     * @throws ExecutionException if the computation threw an
695 +     * exception
696 +     * @throws InterruptedException if the current thread is not a
697 +     * member of a ForkJoinPool and was interrupted while waiting
698       */
699 <    public final V helpJoin() {
700 <        quietlyHelpJoin();
701 <        return reportResult();
699 >    public final V get() throws InterruptedException, ExecutionException {
700 >        Thread t = Thread.currentThread();
701 >        if (t instanceof ForkJoinWorkerThread)
702 >            quietlyJoin();
703 >        else
704 >            externalInterruptibleAwaitDone(false, 0L);
705 >        int s = status;
706 >        if (s != NORMAL) {
707 >            Throwable ex;
708 >            if (s == CANCELLED)
709 >                throw new CancellationException();
710 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
711 >                throw new ExecutionException(ex);
712 >        }
713 >        return getRawResult();
714      }
715  
716      /**
717 <     * Possibly executes other tasks until this task {@link #isDone is
718 <     * done}.  This method may be useful when processing collections
823 <     * of tasks when some have been cancelled or otherwise known to
824 <     * have aborted.
717 >     * Waits if necessary for at most the given time for the computation
718 >     * to complete, and then retrieves its result, if available.
719       *
720 <     * <p>This method may be invoked only from within {@code
721 <     * ForkJoinTask} computations (as may be determined using method
722 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
723 <     * result in exceptions or errors, possibly including {@code
724 <     * ClassCastException}.
720 >     * @param timeout the maximum time to wait
721 >     * @param unit the time unit of the timeout argument
722 >     * @return the computed result
723 >     * @throws CancellationException if the computation was cancelled
724 >     * @throws ExecutionException if the computation threw an
725 >     * exception
726 >     * @throws InterruptedException if the current thread is not a
727 >     * member of a ForkJoinPool and was interrupted while waiting
728 >     * @throws TimeoutException if the wait timed out
729       */
730 <    public final void quietlyHelpJoin() {
731 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
732 <        if (!w.unpushTask(this) || !tryExec()) {
733 <            while (status >= 0) {
734 <                ForkJoinTask<?> t = w.scanWhileJoining(this);
735 <                if (t == null) {
736 <                    if (status >= 0)
737 <                        awaitDone(w);
738 <                    break;
739 <                }
740 <                t.tryExec();
741 <            }
730 >    public final V get(long timeout, TimeUnit unit)
731 >        throws InterruptedException, ExecutionException, TimeoutException {
732 >        long nanos = unit.toNanos(timeout);
733 >        Thread t = Thread.currentThread();
734 >        if (t instanceof ForkJoinWorkerThread)
735 >            ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
736 >        else
737 >            externalInterruptibleAwaitDone(true, nanos);
738 >        int s = status;
739 >        if (s != NORMAL) {
740 >            Throwable ex;
741 >            if (s == CANCELLED)
742 >                throw new CancellationException();
743 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
744 >                throw new ExecutionException(ex);
745 >            throw new TimeoutException();
746          }
747 +        return getRawResult();
748      }
749  
750      /**
751 <     * Joins this task, without returning its result or throwing an
751 >     * Joins this task, without returning its result or throwing its
752       * exception. This method may be useful when processing
753       * collections of tasks when some have been cancelled or otherwise
754       * known to have aborted.
755       */
756      public final void quietlyJoin() {
757 <        Thread t = Thread.currentThread();
758 <        if (t instanceof ForkJoinWorkerThread) {
757 >        Thread t;
758 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
759              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
760 <            if (!w.unpushTask(this) || !tryExec())
761 <                awaitDone(w);
760 >            if (status >= 0) {
761 >                if (w.unpushTask(this)) {
762 >                    boolean completed;
763 >                    try {
764 >                        completed = exec();
765 >                    } catch (Throwable rex) {
766 >                        setExceptionalCompletion(rex);
767 >                        return;
768 >                    }
769 >                    if (completed) {
770 >                        setCompletion(NORMAL);
771 >                        return;
772 >                    }
773 >                }
774 >                w.joinTask(this, false, 0L);
775 >            }
776          }
777          else
778              externalAwaitDone();
# Line 863 | Line 780 | public abstract class ForkJoinTask<V> im
780  
781      /**
782       * Commences performing this task and awaits its completion if
783 <     * necessary, without returning its result or throwing an
784 <     * exception. This method may be useful when processing
868 <     * collections of tasks when some have been cancelled or otherwise
869 <     * known to have aborted.
783 >     * necessary, without returning its result or throwing its
784 >     * exception.
785       */
786      public final void quietlyInvoke() {
787 <        if (!tryExec())
788 <            quietlyJoin();
787 >        if (status >= 0) {
788 >            boolean completed;
789 >            try {
790 >                completed = exec();
791 >            } catch (Throwable rex) {
792 >                setExceptionalCompletion(rex);
793 >                return;
794 >            }
795 >            if (completed)
796 >                setCompletion(NORMAL);
797 >            else
798 >                quietlyJoin();
799 >        }
800      }
801  
802      /**
# Line 881 | Line 807 | public abstract class ForkJoinTask<V> im
807       * processed.
808       *
809       * <p>This method may be invoked only from within {@code
810 <     * ForkJoinTask} computations (as may be determined using method
810 >     * ForkJoinPool} computations (as may be determined using method
811       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
812       * result in exceptions or errors, possibly including {@code
813       * ClassCastException}.
# Line 900 | Line 826 | public abstract class ForkJoinTask<V> im
826       * under any other usage conditions are not guaranteed.
827       * This method may be useful when executing
828       * pre-constructed trees of subtasks in loops.
829 +     *
830 +     * <p>Upon completion of this method, {@code isDone()} reports
831 +     * {@code false}, and {@code getException()} reports {@code
832 +     * null}. However, the value returned by {@code getRawResult} is
833 +     * unaffected. To clear this value, you can invoke {@code
834 +     * setRawResult(null)}.
835       */
836      public void reinitialize() {
837 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
837 >        if (status == EXCEPTIONAL)
838              exceptionMap.remove(this);
839          status = 0;
840      }
# Line 921 | Line 853 | public abstract class ForkJoinTask<V> im
853      }
854  
855      /**
856 <     * Returns {@code true} if the current thread is executing as a
857 <     * ForkJoinPool computation.
856 >     * Returns {@code true} if the current thread is a {@link
857 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
858       *
859 <     * @return {@code true} if the current thread is executing as a
860 <     * ForkJoinPool computation, or false otherwise
859 >     * @return {@code true} if the current thread is a {@link
860 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
861 >     * or {@code false} otherwise
862       */
863      public static boolean inForkJoinPool() {
864          return Thread.currentThread() instanceof ForkJoinWorkerThread;
# Line 940 | Line 873 | public abstract class ForkJoinTask<V> im
873       * were not, stolen.
874       *
875       * <p>This method may be invoked only from within {@code
876 <     * ForkJoinTask} computations (as may be determined using method
876 >     * ForkJoinPool} computations (as may be determined using method
877       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
878       * result in exceptions or errors, possibly including {@code
879       * ClassCastException}.
# Line 959 | Line 892 | public abstract class ForkJoinTask<V> im
892       * fork other tasks.
893       *
894       * <p>This method may be invoked only from within {@code
895 <     * ForkJoinTask} computations (as may be determined using method
895 >     * ForkJoinPool} computations (as may be determined using method
896       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
897       * result in exceptions or errors, possibly including {@code
898       * ClassCastException}.
# Line 982 | Line 915 | public abstract class ForkJoinTask<V> im
915       * exceeded.
916       *
917       * <p>This method may be invoked only from within {@code
918 <     * ForkJoinTask} computations (as may be determined using method
918 >     * ForkJoinPool} computations (as may be determined using method
919       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
920       * result in exceptions or errors, possibly including {@code
921       * ClassCastException}.
# Line 1040 | Line 973 | public abstract class ForkJoinTask<V> im
973       * otherwise.
974       *
975       * <p>This method may be invoked only from within {@code
976 <     * ForkJoinTask} computations (as may be determined using method
976 >     * ForkJoinPool} computations (as may be determined using method
977       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
978       * result in exceptions or errors, possibly including {@code
979       * ClassCastException}.
# Line 1059 | Line 992 | public abstract class ForkJoinTask<V> im
992       * be useful otherwise.
993       *
994       * <p>This method may be invoked only from within {@code
995 <     * ForkJoinTask} computations (as may be determined using method
995 >     * ForkJoinPool} computations (as may be determined using method
996       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
997       * result in exceptions or errors, possibly including {@code
998       * ClassCastException}.
# Line 1082 | Line 1015 | public abstract class ForkJoinTask<V> im
1015       * otherwise.
1016       *
1017       * <p>This method may be invoked only from within {@code
1018 <     * ForkJoinTask} computations (as may be determined using method
1018 >     * ForkJoinPool} computations (as may be determined using method
1019       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1020       * result in exceptions or errors, possibly including {@code
1021       * ClassCastException}.
# Line 1192 | Line 1125 | public abstract class ForkJoinTask<V> im
1125      private static final long serialVersionUID = -7721805057305804111L;
1126  
1127      /**
1128 <     * Saves the state to a stream.
1128 >     * Saves the state to a stream (that is, serializes it).
1129       *
1130       * @serialData the current run status and the exception thrown
1131       * during execution, or {@code null} if none
# Line 1205 | Line 1138 | public abstract class ForkJoinTask<V> im
1138      }
1139  
1140      /**
1141 <     * Reconstitutes the instance from a stream.
1141 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1142       *
1143       * @param s the stream
1144       */
1145      private void readObject(java.io.ObjectInputStream s)
1146          throws java.io.IOException, ClassNotFoundException {
1147          s.defaultReadObject();
1215        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1216        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1148          Object ex = s.readObject();
1149          if (ex != null)
1150 <            setDoneExceptionally((Throwable) ex);
1150 >            setExceptionalCompletion((Throwable) ex);
1151      }
1152  
1153      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines