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.49 by dl, Wed Jul 7 19:52:31 2010 UTC vs.
Revision 1.79 by jsr166, Fri Jun 10 18:10:53 2011 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
10
9   import java.io.Serializable;
10   import java.util.Collection;
13 import java.util.Collections;
11   import java.util.List;
12   import java.util.RandomAccess;
13 < import java.util.Map;
14 < import java.util.WeakHashMap;
13 > import java.lang.ref.WeakReference;
14 > import java.lang.ref.ReferenceQueue;
15 > import java.util.concurrent.Callable;
16 > import java.util.concurrent.CancellationException;
17 > import java.util.concurrent.ExecutionException;
18 > import java.util.concurrent.Future;
19 > import java.util.concurrent.RejectedExecutionException;
20 > import java.util.concurrent.RunnableFuture;
21 > import java.util.concurrent.TimeUnit;
22 > import java.util.concurrent.TimeoutException;
23 > import java.util.concurrent.locks.ReentrantLock;
24 > import java.lang.reflect.Constructor;
25  
26   /**
27   * Abstract base class for tasks that run within a {@link ForkJoinPool}.
# Line 28 | Line 35 | import java.util.WeakHashMap;
35   * start other subtasks.  As indicated by the name of this class,
36   * many programs using {@code ForkJoinTask} employ only methods
37   * {@link #fork} and {@link #join}, or derivatives such as {@link
38 < * #invokeAll}.  However, this class also provides a number of other
39 < * methods that can come into play in advanced usages, as well as
40 < * extension mechanics that allow support of new forms of fork/join
41 < * processing.
38 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
39 > * provides a number of other methods that can come into play in
40 > * advanced usages, as well as extension mechanics that allow
41 > * support of new forms of fork/join processing.
42   *
43   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
44   * The efficiency of {@code ForkJoinTask}s stems from a set of
# Line 58 | Line 65 | import java.util.WeakHashMap;
65   * rethrown to callers attempting to join them. These exceptions may
66   * additionally include {@link RejectedExecutionException} stemming
67   * from internal resource exhaustion, such as failure to allocate
68 < * internal task queues.
68 > * internal task queues. Rethrown exceptions behave in the same way as
69 > * regular exceptions, but, when possible, contain stack traces (as
70 > * displayed for example using {@code ex.printStackTrace()}) of both
71 > * the thread that initiated the computation as well as the thread
72 > * actually encountering the exception; minimally only the latter.
73   *
74   * <p>The primary method for awaiting completion and extracting
75   * results of a task is {@link #join}, but there are several variants:
# Line 100 | Line 111 | import java.util.WeakHashMap;
111   * ForkJoinTasks (as may be determined using method {@link
112   * #inForkJoinPool}).  Attempts to invoke them in other contexts
113   * result in exceptions or errors, possibly including
114 < * ClassCastException.
114 > * {@code ClassCastException}.
115 > *
116 > * <p>Method {@link #join} and its variants are appropriate for use
117 > * only when completion dependencies are acyclic; that is, the
118 > * parallel computation can be described as a directed acyclic graph
119 > * (DAG). Otherwise, executions may encounter a form of deadlock as
120 > * tasks cyclically wait for each other.  However, this framework
121 > * supports other methods and techniques (for example the use of
122 > * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
123 > * may be of use in constructing custom subclasses for problems that
124 > * are not statically structured as DAGs.
125   *
126   * <p>Most base support methods are {@code final}, to prevent
127   * overriding of implementations that are intrinsically tied to the
# Line 116 | Line 137 | import java.util.WeakHashMap;
137   * computation. Large tasks should be split into smaller subtasks,
138   * usually via recursive decomposition. As a very rough rule of thumb,
139   * a task should perform more than 100 and less than 10000 basic
140 < * computational steps. If tasks are too big, then parallelism cannot
141 < * improve throughput. If too small, then memory and internal task
142 < * maintenance overhead may overwhelm processing.
140 > * computational steps, and should avoid indefinite looping. If tasks
141 > * are too big, then parallelism cannot improve throughput. If too
142 > * small, then memory and internal task maintenance overhead may
143 > * overwhelm processing.
144   *
145   * <p>This class provides {@code adapt} methods for {@link Runnable}
146   * and {@link Callable}, that may be of use when mixing execution of
# Line 147 | Line 169 | public abstract class ForkJoinTask<V> im
169       * in a way that flows well in javadocs.
170       */
171  
172 <    /**
173 <     * Run control status bits packed into a single int to minimize
174 <     * footprint and to ensure atomicity (via CAS).  Status is
175 <     * initially zero, and takes on nonnegative values until
176 <     * completed, upon which status holds value COMPLETED. CANCELLED,
177 <     * or EXCEPTIONAL. Tasks undergoing blocking waits by other
178 <     * threads have the SIGNAL bit set.  Completion of a stolen task
179 <     * with SIGNAL set awakens any waiters via notifyAll. Even though
180 <     * suboptimal for some purposes, we use basic builtin wait/notify
181 <     * to take advantage of "monitor inflation" in JVMs that we would
182 <     * otherwise need to emulate to avoid adding further per-task
183 <     * bookkeeping overhead.  We want these monitors to be "fat",
184 <     * i.e., not use biasing or thin-lock techniques, so use some odd
185 <     * coding idioms that tend to avoid them.
172 >    /*
173 >     * The status field holds run control status bits packed into a
174 >     * single int to minimize footprint and to ensure atomicity (via
175 >     * CAS).  Status is initially zero, and takes on nonnegative
176 >     * values until completed, upon which status holds value
177 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
178 >     * waits by other threads have the SIGNAL bit set.  Completion of
179 >     * a stolen task with SIGNAL set awakens any waiters via
180 >     * notifyAll. Even though suboptimal for some purposes, we use
181 >     * basic builtin wait/notify to take advantage of "monitor
182 >     * inflation" in JVMs that we would otherwise need to emulate to
183 >     * avoid adding further per-task bookkeeping overhead.  We want
184 >     * these monitors to be "fat", i.e., not use biasing or thin-lock
185 >     * techniques, so use some odd coding idioms that tend to avoid
186 >     * them.
187       */
165    volatile int status; // accessed directly by pool and workers
188  
189 +    /** The run status of this task */
190 +    volatile int status; // accessed directly by pool and workers
191      private static final int NORMAL      = -1;
192      private static final int CANCELLED   = -2;
193      private static final int EXCEPTIONAL = -3;
194      private static final int SIGNAL      =  1;
195  
196      /**
173     * Table of exceptions thrown by tasks, to enable reporting by
174     * callers. Because exceptions are rare, we don't directly keep
175     * them with task objects, but instead use a weak ref table.  Note
176     * that cancellation exceptions don't appear in the table, but are
177     * instead recorded as status values.
178     * TODO: Use ConcurrentReferenceHashMap
179     */
180    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
181        Collections.synchronizedMap
182        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
183
184    // Maintaining completion status
185
186    /**
197       * Marks completion and wakes up threads waiting to join this task,
198       * also clearing signal request bits.
199       *
200       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
201 <     * @return status on exit
201 >     * @return completion status on exit
202       */
203      private int setCompletion(int completion) {
204 <        int s;
205 <        while ((s = status) >= 0) {
204 >        for (int s;;) {
205 >            if ((s = status) < 0)
206 >                return s;
207              if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
208 <                if (s == SIGNAL)
208 >                if (s != 0)
209                      synchronized (this) { notifyAll(); }
210                  return completion;
211              }
212          }
202        return s;
213      }
214  
215      /**
216 <     * Record exception and set exceptional completion
217 <     * @return status on exit
216 >     * Tries to block a worker thread until completed or timed out.
217 >     * Uses Object.wait time argument conventions.
218 >     * May fail on contention or interrupt.
219 >     *
220 >     * @param millis if > 0, wait time.
221       */
222 <    private int setExceptionalCompletion(Throwable rex) {
223 <        exceptionMap.put(this, rex);
224 <        return setCompletion(EXCEPTIONAL);
222 >    final void tryAwaitDone(long millis) {
223 >        int s;
224 >        try {
225 >            if (((s = status) > 0 ||
226 >                 (s == 0 &&
227 >                  UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
228 >                status > 0) {
229 >                synchronized (this) {
230 >                    if (status > 0)
231 >                        wait(millis);
232 >                }
233 >            }
234 >        } catch (InterruptedException ie) {
235 >            // caller must check termination
236 >        }
237      }
238  
239      /**
240 <     * Blocks a worker thread until completion. Called only by pool.
240 >     * Blocks a non-worker-thread until completion.
241 >     * @return status upon completion
242       */
243 <    final int internalAwaitDone() {
243 >    private int externalAwaitDone() {
244          int s;
245 <        while ((s = status) >= 0) {
246 <            synchronized(this) {
247 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
248 <                    do {
245 >        if ((s = status) >= 0) {
246 >            boolean interrupted = false;
247 >            synchronized (this) {
248 >                while ((s = status) >= 0) {
249 >                    if (s == 0)
250 >                        UNSAFE.compareAndSwapInt(this, statusOffset,
251 >                                                 0, SIGNAL);
252 >                    else {
253                          try {
254                              wait();
255                          } catch (InterruptedException ie) {
256 <                            cancelIfTerminating();
256 >                            interrupted = true;
257                          }
258 <                    } while ((s = status) >= 0);
229 <                    break;
258 >                    }
259                  }
260              }
261 +            if (interrupted)
262 +                Thread.currentThread().interrupt();
263          }
264          return s;
265      }
266  
267      /**
268 <     * Blocks a non-worker-thread until completion.
238 <     * @return status on exit
268 >     * Blocks a non-worker-thread until completion or interruption or timeout.
269       */
270 <    private int externalAwaitDone() {
270 >    private int externalInterruptibleAwaitDone(long millis)
271 >        throws InterruptedException {
272          int s;
273 <        while ((s = status) >= 0) {
274 <            synchronized(this) {
275 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
276 <                    boolean interrupted = false;
277 <                    do {
278 <                        try {
279 <                            wait();
280 <                        } catch (InterruptedException ie) {
281 <                            interrupted = true;
282 <                        }
283 <                    } while ((s = status) >= 0);
284 <                    if (interrupted)
285 <                        Thread.currentThread().interrupt();
255 <                    break;
273 >        if (Thread.interrupted())
274 >            throw new InterruptedException();
275 >        if ((s = status) >= 0) {
276 >            synchronized (this) {
277 >                while ((s = status) >= 0) {
278 >                    if (s == 0)
279 >                        UNSAFE.compareAndSwapInt(this, statusOffset,
280 >                                                 0, SIGNAL);
281 >                    else {
282 >                        wait(millis);
283 >                        if (millis > 0L)
284 >                            break;
285 >                    }
286                  }
287              }
288          }
# Line 260 | Line 290 | public abstract class ForkJoinTask<V> im
290      }
291  
292      /**
293 <     * Unless done, calls exec and records status if completed, but
294 <     * doesn't wait for completion otherwise. Primary execution method
295 <     * for ForkJoinWorkerThread.
293 >     * Primary execution method for stolen tasks. Unless done, calls
294 >     * exec and records status if completed, but doesn't wait for
295 >     * completion otherwise.
296       */
297 <    final void tryExec() {
298 <        try {
299 <            if (status < 0 || !exec())
297 >    final void doExec() {
298 >        if (status >= 0) {
299 >            boolean completed;
300 >            try {
301 >                completed = exec();
302 >            } catch (Throwable rex) {
303 >                setExceptionalCompletion(rex);
304                  return;
305 <        } catch (Throwable rex) {
306 <            setExceptionalCompletion(rex);
307 <            return;
305 >            }
306 >            if (completed)
307 >                setCompletion(NORMAL); // must be outside try block
308          }
275        setCompletion(NORMAL); // must be outside try block
309      }
310  
311      /**
312 <     * If not done and this task is next in worker queue, runs it,
313 <     * else waits for it.
281 <     * @return status on exit
312 >     * Primary mechanics for join, get, quietlyJoin.
313 >     * @return status upon completion
314       */
315      private int doJoin() {
316 <        int stat;
317 <        if ((stat = status) < 0)
318 <            return stat;
319 <        Thread t = Thread.currentThread();
320 <        ForkJoinWorkerThread w;
289 <        if (t instanceof ForkJoinWorkerThread) {
290 <            if ((w = (ForkJoinWorkerThread) t).unpushTask(this)) {
291 <                boolean completed;
316 >        Thread t; ForkJoinWorkerThread w; int s; boolean completed;
317 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
318 >            if ((s = status) < 0)
319 >                return s;
320 >            if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
321                  try {
322                      completed = exec();
323                  } catch (Throwable rex) {
# Line 297 | Line 326 | public abstract class ForkJoinTask<V> im
326                  if (completed)
327                      return setCompletion(NORMAL);
328              }
329 <            w.joinTask(this);
301 <            return status;
329 >            return w.joinTask(this);
330          }
331 <        return externalAwaitDone();
331 >        else
332 >            return externalAwaitDone();
333      }
334  
335      /**
336 <     * Unless done, calls exec and records status if completed, or
337 <     * waits for completion otherwise.
309 <     * @return status on exit
336 >     * Primary mechanics for invoke, quietlyInvoke.
337 >     * @return status upon completion
338       */
339      private int doInvoke() {
340 <        int stat;
341 <        if ((stat = status) >= 0) {
342 <            boolean completed;
343 <            try {
344 <                completed = exec();
345 <            } catch (Throwable rex) {
346 <                return setExceptionalCompletion(rex);
340 >        int s; boolean completed;
341 >        if ((s = status) < 0)
342 >            return s;
343 >        try {
344 >            completed = exec();
345 >        } catch (Throwable rex) {
346 >            return setExceptionalCompletion(rex);
347 >        }
348 >        if (completed)
349 >            return setCompletion(NORMAL);
350 >        else
351 >            return doJoin();
352 >    }
353 >
354 >    // Exception table support
355 >
356 >    /**
357 >     * Table of exceptions thrown by tasks, to enable reporting by
358 >     * callers. Because exceptions are rare, we don't directly keep
359 >     * them with task objects, but instead use a weak ref table.  Note
360 >     * that cancellation exceptions don't appear in the table, but are
361 >     * instead recorded as status values.
362 >     *
363 >     * Note: These statics are initialized below in static block.
364 >     */
365 >    private static final ExceptionNode[] exceptionTable;
366 >    private static final ReentrantLock exceptionTableLock;
367 >    private static final ReferenceQueue<Object> exceptionTableRefQueue;
368 >
369 >    /**
370 >     * Fixed capacity for exceptionTable.
371 >     */
372 >    private static final int EXCEPTION_MAP_CAPACITY = 32;
373 >
374 >    /**
375 >     * Key-value nodes for exception table.  The chained hash table
376 >     * uses identity comparisons, full locking, and weak references
377 >     * for keys. The table has a fixed capacity because it only
378 >     * maintains task exceptions long enough for joiners to access
379 >     * them, so should never become very large for sustained
380 >     * periods. However, since we do not know when the last joiner
381 >     * completes, we must use weak references and expunge them. We do
382 >     * so on each operation (hence full locking). Also, some thread in
383 >     * any ForkJoinPool will call helpExpungeStaleExceptions when its
384 >     * pool becomes isQuiescent.
385 >     */
386 >    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
387 >        final Throwable ex;
388 >        ExceptionNode next;
389 >        final long thrower;  // use id not ref to avoid weak cycles
390 >        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
391 >            super(task, exceptionTableRefQueue);
392 >            this.ex = ex;
393 >            this.next = next;
394 >            this.thrower = Thread.currentThread().getId();
395 >        }
396 >    }
397 >
398 >    /**
399 >     * Records exception and sets exceptional completion.
400 >     *
401 >     * @return status on exit
402 >     */
403 >    private int setExceptionalCompletion(Throwable ex) {
404 >        int h = System.identityHashCode(this);
405 >        final ReentrantLock lock = exceptionTableLock;
406 >        lock.lock();
407 >        try {
408 >            expungeStaleExceptions();
409 >            ExceptionNode[] t = exceptionTable;
410 >            int i = h & (t.length - 1);
411 >            for (ExceptionNode e = t[i]; ; e = e.next) {
412 >                if (e == null) {
413 >                    t[i] = new ExceptionNode(this, ex, t[i]);
414 >                    break;
415 >                }
416 >                if (e.get() == this) // already present
417 >                    break;
418              }
419 <            if (completed)
420 <                stat = setCompletion(NORMAL);
322 <            else
323 <                stat = doJoin();
419 >        } finally {
420 >            lock.unlock();
421          }
422 <        return stat;
422 >        return setCompletion(EXCEPTIONAL);
423      }
424  
425      /**
426 <     * Returns result or throws exception associated with given status.
330 <     * @param s the status
426 >     * Removes exception node and clears status
427       */
428 <    private V reportResult(int s) {
428 >    private void clearExceptionalCompletion() {
429 >        int h = System.identityHashCode(this);
430 >        final ReentrantLock lock = exceptionTableLock;
431 >        lock.lock();
432 >        try {
433 >            ExceptionNode[] t = exceptionTable;
434 >            int i = h & (t.length - 1);
435 >            ExceptionNode e = t[i];
436 >            ExceptionNode pred = null;
437 >            while (e != null) {
438 >                ExceptionNode next = e.next;
439 >                if (e.get() == this) {
440 >                    if (pred == null)
441 >                        t[i] = next;
442 >                    else
443 >                        pred.next = next;
444 >                    break;
445 >                }
446 >                pred = e;
447 >                e = next;
448 >            }
449 >            expungeStaleExceptions();
450 >            status = 0;
451 >        } finally {
452 >            lock.unlock();
453 >        }
454 >    }
455 >
456 >    /**
457 >     * Returns a rethrowable exception for the given task, if
458 >     * available. To provide accurate stack traces, if the exception
459 >     * was not thrown by the current thread, we try to create a new
460 >     * exception of the same type as the one thrown, but with the
461 >     * recorded exception as its cause. If there is no such
462 >     * constructor, we instead try to use a no-arg constructor,
463 >     * followed by initCause, to the same effect. If none of these
464 >     * apply, or any fail due to other exceptions, we return the
465 >     * recorded exception, which is still correct, although it may
466 >     * contain a misleading stack trace.
467 >     *
468 >     * @return the exception, or null if none
469 >     */
470 >    private Throwable getThrowableException() {
471 >        if (status != EXCEPTIONAL)
472 >            return null;
473 >        int h = System.identityHashCode(this);
474 >        ExceptionNode e;
475 >        final ReentrantLock lock = exceptionTableLock;
476 >        lock.lock();
477 >        try {
478 >            expungeStaleExceptions();
479 >            ExceptionNode[] t = exceptionTable;
480 >            e = t[h & (t.length - 1)];
481 >            while (e != null && e.get() != this)
482 >                e = e.next;
483 >        } finally {
484 >            lock.unlock();
485 >        }
486          Throwable ex;
487 <        if (s < NORMAL && (ex = getException()) != null)
487 >        if (e == null || (ex = e.ex) == null)
488 >            return null;
489 >        if (e.thrower != Thread.currentThread().getId()) {
490 >            Class<? extends Throwable> ec = ex.getClass();
491 >            try {
492 >                Constructor<?> noArgCtor = null;
493 >                Constructor<?>[] cs = ec.getConstructors();// public ctors only
494 >                for (int i = 0; i < cs.length; ++i) {
495 >                    Constructor<?> c = cs[i];
496 >                    Class<?>[] ps = c.getParameterTypes();
497 >                    if (ps.length == 0)
498 >                        noArgCtor = c;
499 >                    else if (ps.length == 1 && ps[0] == Throwable.class)
500 >                        return (Throwable)(c.newInstance(ex));
501 >                }
502 >                if (noArgCtor != null) {
503 >                    Throwable wx = (Throwable)(noArgCtor.newInstance());
504 >                    wx.initCause(ex);
505 >                    return wx;
506 >                }
507 >            } catch (Exception ignore) {
508 >            }
509 >        }
510 >        return ex;
511 >    }
512 >
513 >    /**
514 >     * Poll stale refs and remove them. Call only while holding lock.
515 >     */
516 >    private static void expungeStaleExceptions() {
517 >        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
518 >            if (x instanceof ExceptionNode) {
519 >                ForkJoinTask<?> key = ((ExceptionNode)x).get();
520 >                ExceptionNode[] t = exceptionTable;
521 >                int i = System.identityHashCode(key) & (t.length - 1);
522 >                ExceptionNode e = t[i];
523 >                ExceptionNode pred = null;
524 >                while (e != null) {
525 >                    ExceptionNode next = e.next;
526 >                    if (e == x) {
527 >                        if (pred == null)
528 >                            t[i] = next;
529 >                        else
530 >                            pred.next = next;
531 >                        break;
532 >                    }
533 >                    pred = e;
534 >                    e = next;
535 >                }
536 >            }
537 >        }
538 >    }
539 >
540 >    /**
541 >     * If lock is available, poll stale refs and remove them.
542 >     * Called from ForkJoinPool when pools become quiescent.
543 >     */
544 >    static final void helpExpungeStaleExceptions() {
545 >        final ReentrantLock lock = exceptionTableLock;
546 >        if (lock.tryLock()) {
547 >            try {
548 >                expungeStaleExceptions();
549 >            } finally {
550 >                lock.unlock();
551 >            }
552 >        }
553 >    }
554 >
555 >    /**
556 >     * Report the result of invoke or join; called only upon
557 >     * non-normal return of internal versions.
558 >     */
559 >    private V reportResult() {
560 >        int s; Throwable ex;
561 >        if ((s = status) == CANCELLED)
562 >            throw new CancellationException();
563 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
564              UNSAFE.throwException(ex);
565          return getRawResult();
566      }
# Line 349 | Line 578 | public abstract class ForkJoinTask<V> im
578       * #isDone} returning {@code true}.
579       *
580       * <p>This method may be invoked only from within {@code
581 <     * ForkJoinTask} computations (as may be determined using method
581 >     * ForkJoinPool} computations (as may be determined using method
582       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
583       * result in exceptions or errors, possibly including {@code
584       * ClassCastException}.
# Line 363 | Line 592 | public abstract class ForkJoinTask<V> im
592      }
593  
594      /**
595 <     * Returns the result of the computation when it {@link #isDone is done}.
596 <     * This method differs from {@link #get()} in that
595 >     * Returns the result of the computation when it {@link #isDone is
596 >     * done}.  This method differs from {@link #get()} in that
597       * abnormal completion results in {@code RuntimeException} or
598 <     * {@code Error}, not {@code ExecutionException}.
598 >     * {@code Error}, not {@code ExecutionException}, and that
599 >     * interrupts of the calling thread do <em>not</em> cause the
600 >     * method to abruptly return by throwing {@code
601 >     * InterruptedException}.
602       *
603       * @return the computed result
604       */
605      public final V join() {
606 <        return reportResult(doJoin());
606 >        if (doJoin() != NORMAL)
607 >            return reportResult();
608 >        else
609 >            return getRawResult();
610      }
611  
612      /**
613       * Commences performing this task, awaits its completion if
614 <     * necessary, and return its result, or throws an (unchecked)
615 <     * exception if the underlying computation did so.
614 >     * necessary, and returns its result, or throws an (unchecked)
615 >     * {@code RuntimeException} or {@code Error} if the underlying
616 >     * computation did so.
617       *
618       * @return the computed result
619       */
620      public final V invoke() {
621 <        return reportResult(doInvoke());
621 >        if (doInvoke() != NORMAL)
622 >            return reportResult();
623 >        else
624 >            return getRawResult();
625      }
626  
627      /**
628       * Forks the given tasks, returning when {@code isDone} holds for
629       * each task or an (unchecked) exception is encountered, in which
630 <     * case the exception is rethrown.  If either task encounters an
631 <     * exception, the other one may be, but is not guaranteed to be,
632 <     * cancelled.  If both tasks throw an exception, then this method
633 <     * throws one of them.  The individual status of each task may be
634 <     * checked using {@link #getException()} and related methods.
630 >     * case the exception is rethrown. If more than one task
631 >     * encounters an exception, then this method throws any one of
632 >     * these exceptions. If any task encounters an exception, the
633 >     * other may be cancelled. However, the execution status of
634 >     * individual tasks is not guaranteed upon exceptional return. The
635 >     * status of each task may be obtained using {@link
636 >     * #getException()} and related methods to check if they have been
637 >     * cancelled, completed normally or exceptionally, or left
638 >     * unprocessed.
639       *
640       * <p>This method may be invoked only from within {@code
641 <     * ForkJoinTask} computations (as may be determined using method
641 >     * ForkJoinPool} computations (as may be determined using method
642       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
643       * result in exceptions or errors, possibly including {@code
644       * ClassCastException}.
# Line 413 | Line 656 | public abstract class ForkJoinTask<V> im
656      /**
657       * Forks the given tasks, returning when {@code isDone} holds for
658       * each task or an (unchecked) exception is encountered, in which
659 <     * case the exception is rethrown. If any task encounters an
660 <     * exception, others may be, but are not guaranteed to be,
661 <     * cancelled.  If more than one task encounters an exception, then
662 <     * this method throws any one of these exceptions.  The individual
663 <     * status of each task may be checked using {@link #getException()}
664 <     * and related methods.
659 >     * case the exception is rethrown. If more than one task
660 >     * encounters an exception, then this method throws any one of
661 >     * these exceptions. If any task encounters an exception, others
662 >     * may be cancelled. However, the execution status of individual
663 >     * tasks is not guaranteed upon exceptional return. The status of
664 >     * each task may be obtained using {@link #getException()} and
665 >     * related methods to check if they have been cancelled, completed
666 >     * normally or exceptionally, or left unprocessed.
667       *
668       * <p>This method may be invoked only from within {@code
669 <     * ForkJoinTask} computations (as may be determined using method
669 >     * ForkJoinPool} computations (as may be determined using method
670       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
671       * result in exceptions or errors, possibly including {@code
672       * ClassCastException}.
# Line 459 | Line 704 | public abstract class ForkJoinTask<V> im
704      /**
705       * Forks all tasks in the specified collection, returning when
706       * {@code isDone} holds for each task or an (unchecked) exception
707 <     * is encountered.  If any task encounters an exception, others
708 <     * may be, but are not guaranteed to be, cancelled.  If more than
709 <     * one task encounters an exception, then this method throws any
710 <     * one of these exceptions.  The individual status of each task
711 <     * may be checked using {@link #getException()} and related
712 <     * methods.  The behavior of this operation is undefined if the
713 <     * specified collection is modified while the operation is in
714 <     * progress.
707 >     * is encountered, in which case the exception is rethrown. If
708 >     * more than one task encounters an exception, then this method
709 >     * throws any one of these exceptions. If any task encounters an
710 >     * exception, others may be cancelled. However, the execution
711 >     * status of individual tasks is not guaranteed upon exceptional
712 >     * return. The status of each task may be obtained using {@link
713 >     * #getException()} and related methods to check if they have been
714 >     * cancelled, completed normally or exceptionally, or left
715 >     * unprocessed.
716       *
717       * <p>This method may be invoked only from within {@code
718 <     * ForkJoinTask} computations (as may be determined using method
718 >     * ForkJoinPool} computations (as may be determined using method
719       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
720       * result in exceptions or errors, possibly including {@code
721       * ClassCastException}.
# Line 515 | Line 761 | public abstract class ForkJoinTask<V> im
761  
762      /**
763       * Attempts to cancel execution of this task. This attempt will
764 <     * fail if the task has already completed, has already been
765 <     * cancelled, or could not be cancelled for some other reason. If
766 <     * successful, and this task has not started when cancel is
767 <     * called, execution of this task is suppressed, {@link
768 <     * #isCancelled} will report true, and {@link #join} will result
769 <     * in a {@code CancellationException} being thrown.
764 >     * fail if the task has already completed or could not be
765 >     * cancelled for some other reason. If successful, and this task
766 >     * has not started when {@code cancel} is called, execution of
767 >     * this task is suppressed. After this method returns
768 >     * successfully, unless there is an intervening call to {@link
769 >     * #reinitialize}, subsequent calls to {@link #isCancelled},
770 >     * {@link #isDone}, and {@code cancel} will return {@code true}
771 >     * and calls to {@link #join} and related methods will result in
772 >     * {@code CancellationException}.
773       *
774       * <p>This method may be overridden in subclasses, but if so, must
775 <     * still ensure that these minimal properties hold. In particular,
776 <     * the {@code cancel} method itself must not throw exceptions.
775 >     * still ensure that these properties hold. In particular, the
776 >     * {@code cancel} method itself must not throw exceptions.
777       *
778       * <p>This method is designed to be invoked by <em>other</em>
779       * tasks. To terminate the current task, you can just return or
780       * throw an unchecked exception from its computation method, or
781       * invoke {@link #completeExceptionally}.
782       *
783 <     * @param mayInterruptIfRunning this value is ignored in the
784 <     * default implementation because tasks are not
785 <     * cancelled via interruption
783 >     * @param mayInterruptIfRunning this value has no effect in the
784 >     * default implementation because interrupts are not used to
785 >     * control cancellation.
786       *
787       * @return {@code true} if this task is now cancelled
788       */
789      public boolean cancel(boolean mayInterruptIfRunning) {
790 <        setCompletion(CANCELLED);
542 <        return status == CANCELLED;
790 >        return setCompletion(CANCELLED) == CANCELLED;
791      }
792  
793      /**
794 <     * Cancels, ignoring any exceptions it throws. Used during worker
795 <     * and pool shutdown.
794 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
795 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
796 >     * exceptions, but if it does anyway, we have no recourse during
797 >     * shutdown, so guard against this case.
798       */
799      final void cancelIgnoringExceptions() {
800          try {
# Line 553 | Line 803 | public abstract class ForkJoinTask<V> im
803          }
804      }
805  
556    /**
557     * Cancels ignoring exceptions if worker is terminating
558     */
559    private void cancelIfTerminating() {
560        Thread t = Thread.currentThread();
561        if ((t instanceof ForkJoinWorkerThread) &&
562            ((ForkJoinWorkerThread) t).isTerminating()) {
563            try {
564                cancel(false);
565            } catch (Throwable ignore) {
566            }
567        }
568    }
569
806      public final boolean isDone() {
807          return status < 0;
808      }
# Line 606 | Line 842 | public abstract class ForkJoinTask<V> im
842          int s = status;
843          return ((s >= NORMAL)    ? null :
844                  (s == CANCELLED) ? new CancellationException() :
845 <                exceptionMap.get(this));
845 >                getThrowableException());
846      }
847  
848      /**
# Line 631 | Line 867 | public abstract class ForkJoinTask<V> im
867  
868      /**
869       * Completes this task, and if not already aborted or cancelled,
870 <     * returning a {@code null} result upon {@code join} and related
871 <     * operations. This method may be used to provide results for
872 <     * asynchronous tasks, or to provide alternative handling for
873 <     * tasks that would not otherwise complete normally. Its use in
874 <     * other situations is discouraged. This method is
875 <     * overridable, but overridden versions must invoke {@code super}
876 <     * implementation to maintain guarantees.
870 >     * returning the given value as the result of subsequent
871 >     * invocations of {@code join} and related operations. This method
872 >     * may be used to provide results for asynchronous tasks, or to
873 >     * provide alternative handling for tasks that would not otherwise
874 >     * complete normally. Its use in other situations is
875 >     * discouraged. This method is overridable, but overridden
876 >     * versions must invoke {@code super} implementation to maintain
877 >     * guarantees.
878       *
879       * @param value the result value for this task
880       */
# Line 651 | Line 888 | public abstract class ForkJoinTask<V> im
888          setCompletion(NORMAL);
889      }
890  
891 +    /**
892 +     * Waits if necessary for the computation to complete, and then
893 +     * retrieves its result.
894 +     *
895 +     * @return the computed result
896 +     * @throws CancellationException if the computation was cancelled
897 +     * @throws ExecutionException if the computation threw an
898 +     * exception
899 +     * @throws InterruptedException if the current thread is not a
900 +     * member of a ForkJoinPool and was interrupted while waiting
901 +     */
902      public final V get() throws InterruptedException, ExecutionException {
903 <        int s = doJoin();
904 <        if (Thread.interrupted())
905 <            throw new InterruptedException();
906 <        if (s < NORMAL) {
907 <            Throwable ex;
908 <            if (s == CANCELLED)
909 <                throw new CancellationException();
662 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
663 <                throw new ExecutionException(ex);
664 <        }
903 >        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
904 >            doJoin() : externalInterruptibleAwaitDone(0L);
905 >        Throwable ex;
906 >        if (s == CANCELLED)
907 >            throw new CancellationException();
908 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
909 >            throw new ExecutionException(ex);
910          return getRawResult();
911      }
912  
913 +    /**
914 +     * Waits if necessary for at most the given time for the computation
915 +     * to complete, and then retrieves its result, if available.
916 +     *
917 +     * @param timeout the maximum time to wait
918 +     * @param unit the time unit of the timeout argument
919 +     * @return the computed result
920 +     * @throws CancellationException if the computation was cancelled
921 +     * @throws ExecutionException if the computation threw an
922 +     * exception
923 +     * @throws InterruptedException if the current thread is not a
924 +     * member of a ForkJoinPool and was interrupted while waiting
925 +     * @throws TimeoutException if the wait timed out
926 +     */
927      public final V get(long timeout, TimeUnit unit)
928          throws InterruptedException, ExecutionException, TimeoutException {
929          Thread t = Thread.currentThread();
671        ForkJoinPool pool;
930          if (t instanceof ForkJoinWorkerThread) {
931              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
932 <            if (status >= 0 && w.unpushTask(this))
933 <                tryExec();
934 <            pool = w.pool;
935 <        }
936 <        else
937 <            pool = null;
938 <        /*
939 <         * Timed wait loop intermixes cases for fj (pool != null) and
682 <         * non FJ threads. For FJ, decrement pool count but don't try
683 <         * for replacement; increment count on completion. For non-FJ,
684 <         * deal with interrupts. This is messy, but a little less so
685 <         * than is splitting the FJ and nonFJ cases.
686 <         */
687 <        boolean interrupted = false;
688 <        boolean dec = false; // true if pool count decremented
689 <        for (;;) {
690 <            if (Thread.interrupted() && pool == null) {
691 <                interrupted = true;
692 <                break;
693 <            }
694 <            int s = status;
695 <            if (s < 0)
696 <                break;
697 <            if (UNSAFE.compareAndSwapInt(this, statusOffset,
698 <                                         s, s | SIGNAL)) {
699 <                long startTime = System.nanoTime();
700 <                long nanos = unit.toNanos(timeout);
701 <                long nt; // wait time
702 <                while (status >= 0 &&
703 <                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
704 <                    if (pool != null && !dec)
705 <                        dec = pool.tryDecrementRunningCount();
706 <                    else {
707 <                        long ms = nt / 1000000;
708 <                        int ns = (int) (nt % 1000000);
709 <                        try {
710 <                            synchronized(this) {
711 <                                if (status >= 0)
712 <                                    wait(ms, ns);
713 <                            }
714 <                        } catch (InterruptedException ie) {
715 <                            if (pool != null)
716 <                                cancelIfTerminating();
717 <                            else {
718 <                                interrupted = true;
719 <                                break;
720 <                            }
721 <                        }
932 >            long nanos = unit.toNanos(timeout);
933 >            if (status >= 0) {
934 >                boolean completed = false;
935 >                if (w.unpushTask(this)) {
936 >                    try {
937 >                        completed = exec();
938 >                    } catch (Throwable rex) {
939 >                        setExceptionalCompletion(rex);
940                      }
941                  }
942 <                break;
942 >                if (completed)
943 >                    setCompletion(NORMAL);
944 >                else if (status >= 0 && nanos > 0)
945 >                    w.pool.timedAwaitJoin(this, nanos);
946              }
947          }
948 <        if (pool != null && dec)
949 <            pool.incrementRunningCount();
950 <        if (interrupted)
951 <            throw new InterruptedException();
952 <        int es = status;
953 <        if (es != NORMAL) {
948 >        else {
949 >            long millis = unit.toMillis(timeout);
950 >            if (millis > 0)
951 >                externalInterruptibleAwaitDone(millis);
952 >        }
953 >        int s = status;
954 >        if (s != NORMAL) {
955              Throwable ex;
956 <            if (es == CANCELLED)
956 >            if (s == CANCELLED)
957                  throw new CancellationException();
958 <            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
958 >            if (s != EXCEPTIONAL)
959 >                throw new TimeoutException();
960 >            if ((ex = getThrowableException()) != null)
961                  throw new ExecutionException(ex);
738            throw new TimeoutException();
962          }
963          return getRawResult();
964      }
965  
966      /**
967 <     * Joins this task, without returning its result or throwing an
967 >     * Joins this task, without returning its result or throwing its
968       * exception. This method may be useful when processing
969       * collections of tasks when some have been cancelled or otherwise
970       * known to have aborted.
# Line 752 | Line 975 | public abstract class ForkJoinTask<V> im
975  
976      /**
977       * Commences performing this task and awaits its completion if
978 <     * necessary, without returning its result or throwing an
979 <     * exception. This method may be useful when processing
757 <     * collections of tasks when some have been cancelled or otherwise
758 <     * known to have aborted.
978 >     * necessary, without returning its result or throwing its
979 >     * exception.
980       */
981      public final void quietlyInvoke() {
982          doInvoke();
# Line 769 | Line 990 | public abstract class ForkJoinTask<V> im
990       * processed.
991       *
992       * <p>This method may be invoked only from within {@code
993 <     * ForkJoinTask} computations (as may be determined using method
993 >     * ForkJoinPool} computations (as may be determined using method
994       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
995       * result in exceptions or errors, possibly including {@code
996       * ClassCastException}.
# Line 788 | Line 1009 | public abstract class ForkJoinTask<V> im
1009       * under any other usage conditions are not guaranteed.
1010       * This method may be useful when executing
1011       * pre-constructed trees of subtasks in loops.
1012 +     *
1013 +     * <p>Upon completion of this method, {@code isDone()} reports
1014 +     * {@code false}, and {@code getException()} reports {@code
1015 +     * null}. However, the value returned by {@code getRawResult} is
1016 +     * unaffected. To clear this value, you can invoke {@code
1017 +     * setRawResult(null)}.
1018       */
1019      public void reinitialize() {
1020          if (status == EXCEPTIONAL)
1021 <            exceptionMap.remove(this);
1022 <        status = 0;
1021 >            clearExceptionalCompletion();
1022 >        else
1023 >            status = 0;
1024      }
1025  
1026      /**
# Line 809 | Line 1037 | public abstract class ForkJoinTask<V> im
1037      }
1038  
1039      /**
1040 <     * Returns {@code true} if the current thread is executing as a
1041 <     * ForkJoinPool computation.
1040 >     * Returns {@code true} if the current thread is a {@link
1041 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1042       *
1043 <     * @return {@code true} if the current thread is executing as a
1044 <     * ForkJoinPool computation, or false otherwise
1043 >     * @return {@code true} if the current thread is a {@link
1044 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1045 >     * or {@code false} otherwise
1046       */
1047      public static boolean inForkJoinPool() {
1048          return Thread.currentThread() instanceof ForkJoinWorkerThread;
# Line 828 | Line 1057 | public abstract class ForkJoinTask<V> im
1057       * were not, stolen.
1058       *
1059       * <p>This method may be invoked only from within {@code
1060 <     * ForkJoinTask} computations (as may be determined using method
1060 >     * ForkJoinPool} computations (as may be determined using method
1061       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1062       * result in exceptions or errors, possibly including {@code
1063       * ClassCastException}.
# Line 847 | Line 1076 | public abstract class ForkJoinTask<V> im
1076       * fork other tasks.
1077       *
1078       * <p>This method may be invoked only from within {@code
1079 <     * ForkJoinTask} computations (as may be determined using method
1079 >     * ForkJoinPool} computations (as may be determined using method
1080       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1081       * result in exceptions or errors, possibly including {@code
1082       * ClassCastException}.
# Line 870 | Line 1099 | public abstract class ForkJoinTask<V> im
1099       * exceeded.
1100       *
1101       * <p>This method may be invoked only from within {@code
1102 <     * ForkJoinTask} computations (as may be determined using method
1102 >     * ForkJoinPool} computations (as may be determined using method
1103       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1104       * result in exceptions or errors, possibly including {@code
1105       * ClassCastException}.
# Line 928 | Line 1157 | public abstract class ForkJoinTask<V> im
1157       * otherwise.
1158       *
1159       * <p>This method may be invoked only from within {@code
1160 <     * ForkJoinTask} computations (as may be determined using method
1160 >     * ForkJoinPool} computations (as may be determined using method
1161       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1162       * result in exceptions or errors, possibly including {@code
1163       * ClassCastException}.
# Line 947 | Line 1176 | public abstract class ForkJoinTask<V> im
1176       * be useful otherwise.
1177       *
1178       * <p>This method may be invoked only from within {@code
1179 <     * ForkJoinTask} computations (as may be determined using method
1179 >     * ForkJoinPool} computations (as may be determined using method
1180       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1181       * result in exceptions or errors, possibly including {@code
1182       * ClassCastException}.
# Line 970 | Line 1199 | public abstract class ForkJoinTask<V> im
1199       * otherwise.
1200       *
1201       * <p>This method may be invoked only from within {@code
1202 <     * ForkJoinTask} computations (as may be determined using method
1202 >     * ForkJoinPool} computations (as may be determined using method
1203       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1204       * result in exceptions or errors, possibly including {@code
1205       * ClassCastException}.
# Line 1080 | Line 1309 | public abstract class ForkJoinTask<V> im
1309      private static final long serialVersionUID = -7721805057305804111L;
1310  
1311      /**
1312 <     * Saves the state to a stream.
1312 >     * Saves the state to a stream (that is, serializes it).
1313       *
1314       * @serialData the current run status and the exception thrown
1315       * during execution, or {@code null} if none
# Line 1093 | Line 1322 | public abstract class ForkJoinTask<V> im
1322      }
1323  
1324      /**
1325 <     * Reconstitutes the instance from a stream.
1325 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1326       *
1327       * @param s the stream
1328       */
# Line 1102 | Line 1331 | public abstract class ForkJoinTask<V> im
1331          s.defaultReadObject();
1332          Object ex = s.readObject();
1333          if (ex != null)
1334 <            setExceptionalCompletion((Throwable) ex);
1106 <        if (status < 0)
1107 <            synchronized (this) { notifyAll(); }
1334 >            setExceptionalCompletion((Throwable)ex);
1335      }
1336  
1337      // Unsafe mechanics
1338 <
1339 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1340 <    private static final long statusOffset =
1341 <        objectFieldOffset("status", ForkJoinTask.class);
1342 <
1343 <    private static long objectFieldOffset(String field, Class<?> klazz) {
1338 >    private static final sun.misc.Unsafe UNSAFE;
1339 >    private static final long statusOffset;
1340 >    static {
1341 >        exceptionTableLock = new ReentrantLock();
1342 >        exceptionTableRefQueue = new ReferenceQueue<Object>();
1343 >        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1344          try {
1345 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1346 <        } catch (NoSuchFieldException e) {
1347 <            // Convert Exception to corresponding Error
1348 <            NoSuchFieldError error = new NoSuchFieldError(field);
1349 <            error.initCause(e);
1123 <            throw error;
1345 >            UNSAFE = getUnsafe();
1346 >            statusOffset = UNSAFE.objectFieldOffset
1347 >                (ForkJoinTask.class.getDeclaredField("status"));
1348 >        } catch (Exception e) {
1349 >            throw new Error(e);
1350          }
1351      }
1352  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines