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.15 by jsr166, Fri Jul 24 22:05:22 2009 UTC vs.
Revision 1.41 by dl, Wed Aug 5 23:37:32 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.io.Serializable;
9 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import sun.misc.Unsafe;
12 < import java.lang.reflect.*;
10 >
11 > import java.io.Serializable;
12 > import java.util.Collection;
13 > import java.util.Collections;
14 > import java.util.List;
15 > import java.util.RandomAccess;
16 > import java.util.Map;
17 > import java.util.WeakHashMap;
18  
19   /**
20 < * Abstract base class for tasks that run within a {@link
21 < * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
20 > * Abstract base class for tasks that run within a {@link ForkJoinPool}.
21 > * A {@code ForkJoinTask} is a thread-like entity that is much
22   * lighter weight than a normal thread.  Huge numbers of tasks and
23   * subtasks may be hosted by a small number of actual threads in a
24   * ForkJoinPool, at the price of some usage limitations.
25   *
26 < * <p> A "main" ForkJoinTask begins execution when submitted to a
27 < * {@link ForkJoinPool}. Once started, it will usually in turn start
28 < * other subtasks.  As indicated by the name of this class, many
29 < * programs using ForkJoinTasks employ only methods {@code fork}
30 < * and {@code join}, or derivatives such as
31 < * {@code invokeAll}.  However, this class also provides a number
32 < * of other methods that can come into play in advanced usages, as
33 < * well as extension mechanics that allow support of new forms of
34 < * fork/join processing.
26 > * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27 > * to a {@link ForkJoinPool}.  Once started, it will usually in turn
28 > * start other subtasks.  As indicated by the name of this class,
29 > * many programs using {@code ForkJoinTask} employ only methods
30 > * {@link #fork} and {@link #join}, or derivatives such as {@link
31 > * #invokeAll}.  However, this class also provides a number of other
32 > * methods that can come into play in advanced usages, as well as
33 > * extension mechanics that allow support of new forms of fork/join
34 > * processing.
35   *
36 < * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
37 < * efficiency of ForkJoinTasks stems from a set of restrictions (that
38 < * are only partially statically enforceable) reflecting their
39 < * intended use as computational tasks calculating pure functions or
40 < * operating on purely isolated objects.  The primary coordination
41 < * mechanisms are {@link #fork}, that arranges asynchronous execution,
42 < * and {@link #join}, that doesn't proceed until the task's result has
43 < * been computed.  Computations should avoid {@code synchronized}
44 < * methods or blocks, and should minimize other blocking
45 < * synchronization apart from joining other tasks or using
46 < * synchronizers such as Phasers that are advertised to cooperate with
47 < * fork/join scheduling. Tasks should also not perform blocking IO,
48 < * and should ideally access variables that are completely independent
49 < * of those accessed by other running tasks. Minor breaches of these
50 < * restrictions, for example using shared output streams, may be
51 < * tolerable in practice, but frequent use may result in poor
52 < * performance, and the potential to indefinitely stall if the number
53 < * of threads not waiting for IO or other external synchronization
54 < * becomes exhausted. This usage restriction is in part enforced by
55 < * not permitting checked exceptions such as {@code IOExceptions}
56 < * to be thrown. However, computations may still encounter unchecked
57 < * exceptions, that are rethrown to callers attempting join
58 < * them. These exceptions may additionally include
59 < * RejectedExecutionExceptions stemming from internal resource
60 < * exhaustion such as failure to allocate internal task queues.
36 > * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37 > * The efficiency of {@code ForkJoinTask}s stems from a set of
38 > * restrictions (that are only partially statically enforceable)
39 > * reflecting their intended use as computational tasks calculating
40 > * pure functions or operating on purely isolated objects.  The
41 > * primary coordination mechanisms are {@link #fork}, that arranges
42 > * asynchronous execution, and {@link #join}, that doesn't proceed
43 > * until the task's result has been computed.  Computations should
44 > * avoid {@code synchronized} methods or blocks, and should minimize
45 > * other blocking synchronization apart from joining other tasks or
46 > * using synchronizers such as Phasers that are advertised to
47 > * cooperate with fork/join scheduling. Tasks should also not perform
48 > * blocking IO, and should ideally access variables that are
49 > * completely independent of those accessed by other running
50 > * tasks. Minor breaches of these restrictions, for example using
51 > * shared output streams, may be tolerable in practice, but frequent
52 > * use may result in poor performance, and the potential to
53 > * indefinitely stall if the number of threads not waiting for IO or
54 > * other external synchronization becomes exhausted. This usage
55 > * restriction is in part enforced by not permitting checked
56 > * exceptions such as {@code IOExceptions} to be thrown. However,
57 > * computations may still encounter unchecked exceptions, that are
58 > * rethrown to callers attempting to join them. These exceptions may
59 > * additionally include RejectedExecutionExceptions stemming from
60 > * internal resource exhaustion such as failure to allocate internal
61 > * task queues.
62   *
63   * <p>The primary method for awaiting completion and extracting
64   * results of a task is {@link #join}, but there are several variants:
# Line 63 | Line 68 | import java.lang.reflect.*;
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
71 < * equivalent to {@code fork(); join()} but always attempts to
72 < * begin execution in the current thread. The "<em>quiet</em>" forms
73 < * of these methods do not extract results or report exceptions. These
71 > * equivalent to {@code fork(); join()} but always attempts to begin
72 > * execution in the current thread. The "<em>quiet</em>" forms of
73 > * these methods do not extract results or report exceptions. These
74   * may be useful when a set of tasks are being executed, and you need
75   * to delay processing of results or exceptions until all complete.
76   * Method {@code invokeAll} (available in multiple versions)
77   * performs the most common form of parallel invocation: forking a set
78   * of tasks and joining them all.
79   *
80 < * <p> The ForkJoinTask class is not usually directly subclassed.
80 > * <p>The execution status of tasks may be queried at several levels
81 > * of detail: {@link #isDone} is true if a task completed in any way
82 > * (including the case where a task was cancelled without executing);
83 > * {@link #isCancelled} is true if completion was due to cancellation;
84 > * {@link #isCompletedNormally} is true if a task completed without
85 > * cancellation or encountering an exception; {@link
86 > * #isCompletedExceptionally} is true if if the task encountered an
87 > * exception (in which case {@link #getException} returns the
88 > * exception); {@link #isCancelled} is true if the task was cancelled
89 > * (in which case {@link #getException} returns a {@link
90 > * java.util.concurrent.CancellationException}); and {@link
91 > * #isCompletedAbnormally} is true if a task was either cancelled or
92 > * encountered an exception.
93 > *
94 > * <p>The ForkJoinTask class is not usually directly subclassed.
95   * Instead, you subclass one of the abstract classes that support a
96 < * particular style of fork/join processing.  Normally, a concrete
96 > * particular style of fork/join processing, typically {@link
97 > * RecursiveAction} for computations that do not return results, or
98 > * {@link RecursiveTask} for those that do.  Normally, a concrete
99   * ForkJoinTask subclass declares fields comprising its parameters,
100   * established in a constructor, and then defines a {@code compute}
101   * method that somehow uses the control methods supplied by this base
102   * class. While these methods have {@code public} access (to allow
103 < * instances of different task subclasses to call each others
103 > * instances of different task subclasses to call each other's
104   * methods), some of them may only be called from within other
105   * ForkJoinTasks (as may be determined using method {@link
106   * #inForkJoinPool}).  Attempts to invoke them in other contexts
107   * result in exceptions or errors, possibly including
108   * ClassCastException.
109   *
110 < * <p>Most base support methods are {@code final} because their
111 < * implementations are intrinsically tied to the underlying
112 < * lightweight task scheduling framework, and so cannot be overridden.
113 < * Developers creating new basic styles of fork/join processing should
114 < * minimally implement {@code protected} methods
115 < * {@code exec}, {@code setRawResult}, and
116 < * {@code getRawResult}, while also introducing an abstract
117 < * computational method that can be implemented in its subclasses,
118 < * possibly relying on other {@code protected} methods provided
98 < * by this class.
110 > * <p>Most base support methods are {@code final}, to prevent
111 > * overriding of implementations that are intrinsically tied to the
112 > * underlying lightweight task scheduling framework.  Developers
113 > * creating new basic styles of fork/join processing should minimally
114 > * implement {@code protected} methods {@link #exec}, {@link
115 > * #setRawResult}, and {@link #getRawResult}, while also introducing
116 > * an abstract computational method that can be implemented in its
117 > * subclasses, possibly relying on other {@code protected} methods
118 > * provided by this class.
119   *
120   * <p>ForkJoinTasks should perform relatively small amounts of
121 < * computations, otherwise splitting into smaller tasks. As a very
122 < * rough rule of thumb, a task should perform more than 100 and less
123 < * than 10000 basic computational steps. If tasks are too big, then
124 < * parallelism cannot improve throughput. If too small, then memory
125 < * and internal task maintenance overhead may overwhelm processing.
121 > * computation. Large tasks should be split into smaller subtasks,
122 > * usually via recursive decomposition. As a very rough rule of thumb,
123 > * a task should perform more than 100 and less than 10000 basic
124 > * computational steps. If tasks are too big, then parallelism cannot
125 > * improve throughput. If too small, then memory and internal task
126 > * maintenance overhead may overwhelm processing.
127 > *
128 > * <p>This class provides {@code adapt} methods for {@link Runnable}
129 > * and {@link Callable}, that may be of use when mixing execution of
130 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
131 > * are of this form, consider using a pool in
132 > * {@linkplain ForkJoinPool#setAsyncMode async mode}.
133   *
134 < * <p>ForkJoinTasks are {@code Serializable}, which enables them
135 < * to be used in extensions such as remote execution frameworks. It is
136 < * in general sensible to serialize tasks only before or after, but
137 < * not during execution. Serialization is not relied on during
111 < * execution itself.
134 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
135 > * used in extensions such as remote execution frameworks. It is
136 > * sensible to serialize tasks only before or after, but not during,
137 > * execution. Serialization is not relied on during execution itself.
138   *
139   * @since 1.7
140   * @author Doug Lea
# Line 245 | Line 271 | public abstract class ForkJoinTask<V> im
271          synchronized (this) {
272              try {
273                  while (status >= 0) {
274 <                    long nt = nanos - System.nanoTime() - startTime;
274 >                    long nt = nanos - (System.nanoTime() - startTime);
275                      if (nt <= 0)
276                          break;
277                      wait(nt / 1000000, (int) (nt % 1000000));
# Line 366 | Line 392 | public abstract class ForkJoinTask<V> im
392  
393      /**
394       * Returns result or throws exception using j.u.c.Future conventions.
395 <     * Only call when {@code isDone} known to be true.
395 >     * Only call when {@code isDone} known to be true or thread known
396 >     * to be interrupted.
397       */
398      private V reportFutureResult()
399 <        throws ExecutionException, InterruptedException {
399 >        throws InterruptedException, ExecutionException {
400 >        if (Thread.interrupted())
401 >            throw new InterruptedException();
402          int s = status & COMPLETION_MASK;
403          if (s < NORMAL) {
404              Throwable ex;
# Line 377 | Line 406 | public abstract class ForkJoinTask<V> im
406                  throw new CancellationException();
407              if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
408                  throw new ExecutionException(ex);
380            if (Thread.interrupted())
381                throw new InterruptedException();
409          }
410          return getRawResult();
411      }
# Line 389 | Line 416 | public abstract class ForkJoinTask<V> im
416       */
417      private V reportTimedFutureResult()
418          throws InterruptedException, ExecutionException, TimeoutException {
419 +        if (Thread.interrupted())
420 +            throw new InterruptedException();
421          Throwable ex;
422          int s = status & COMPLETION_MASK;
423          if (s == NORMAL)
424              return getRawResult();
425 <        if (s == CANCELLED)
425 >        else if (s == CANCELLED)
426              throw new CancellationException();
427 <        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
427 >        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
428              throw new ExecutionException(ex);
429 <        if (Thread.interrupted())
430 <            throw new InterruptedException();
402 <        throw new TimeoutException();
429 >        else
430 >            throw new TimeoutException();
431      }
432  
433      // internal execution methods
# Line 484 | Line 512 | public abstract class ForkJoinTask<V> im
512      /**
513       * Arranges to asynchronously execute this task.  While it is not
514       * necessarily enforced, it is a usage error to fork a task more
515 <     * than once unless it has completed and been reinitialized.  This
516 <     * method may be invoked only from within ForkJoinTask
517 <     * computations (as may be determined using method {@link
518 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
519 <     * in exceptions or errors, possibly including ClassCastException.
515 >     * than once unless it has completed and been reinitialized.
516 >     *
517 >     * <p>This method may be invoked only from within {@code
518 >     * ForkJoinTask} computations (as may be determined using method
519 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
520 >     * result in exceptions or errors, possibly including {@code
521 >     * ClassCastException}.
522 >     *
523 >     * @return {@code this}, to simplify usage
524       */
525 <    public final void fork() {
525 >    public final ForkJoinTask<V> fork() {
526          ((ForkJoinWorkerThread) Thread.currentThread())
527              .pushTask(this);
528 +        return this;
529      }
530  
531      /**
532 <     * Returns the result of the computation when it is ready.
533 <     * This method differs from {@code get} in that abnormal
534 <     * completion results in RuntimeExceptions or Errors, not
535 <     * ExecutionExceptions.
532 >     * Returns the result of the computation when it {@link #isDone is done}.
533 >     * This method differs from {@link #get()} in that
534 >     * abnormal completion results in {@code RuntimeException} or
535 >     * {@code Error}, not {@code ExecutionException}.
536       *
537       * @return the computed result
538       */
# Line 512 | Line 545 | public abstract class ForkJoinTask<V> im
545  
546      /**
547       * Commences performing this task, awaits its completion if
548 <     * necessary, and return its result.
548 >     * necessary, and return its result, or throws an (unchecked)
549 >     * exception if the underlying computation did so.
550       *
517     * @throws Throwable (a RuntimeException, Error, or unchecked
518     * exception) if the underlying computation did so
551       * @return the computed result
552       */
553      public final V invoke() {
# Line 526 | Line 558 | public abstract class ForkJoinTask<V> im
558      }
559  
560      /**
561 <     * Forks both tasks, returning when {@code isDone} holds for
562 <     * both of them or an exception is encountered. This method may be
563 <     * invoked only from within ForkJoinTask computations (as may be
564 <     * determined using method {@link #inForkJoinPool}). Attempts to
565 <     * invoke in other contexts result in exceptions or errors,
566 <     * possibly including ClassCastException.
567 <     *
568 <     * @param t1 one task
569 <     * @param t2 the other task
570 <     * @throws NullPointerException if t1 or t2 are null
571 <     * @throws RuntimeException or Error if either task did so
561 >     * Forks the given tasks, returning when {@code isDone} holds for
562 >     * each task or an (unchecked) exception is encountered, in which
563 >     * case the exception is rethrown.  If either task encounters an
564 >     * exception, the other one may be, but is not guaranteed to be,
565 >     * cancelled.  If both tasks throw an exception, then this method
566 >     * throws one of them.  The individual status of each task may be
567 >     * checked using {@link #getException()} and related methods.
568 >     *
569 >     * <p>This method may be invoked only from within {@code
570 >     * ForkJoinTask} computations (as may be determined using method
571 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
572 >     * result in exceptions or errors, possibly including {@code
573 >     * ClassCastException}.
574 >     *
575 >     * @param t1 the first task
576 >     * @param t2 the second task
577 >     * @throws NullPointerException if any task is null
578       */
579 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
579 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
580          t2.fork();
581          t1.invoke();
582          t2.join();
583      }
584  
585      /**
586 <     * Forks the given tasks, returning when {@code isDone} holds
587 <     * for all of them. If any task encounters an exception, others
588 <     * may be cancelled.  This method may be invoked only from within
589 <     * ForkJoinTask computations (as may be determined using method
590 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
591 <     * result in exceptions or errors, possibly including
592 <     * ClassCastException.
586 >     * Forks the given tasks, returning when {@code isDone} holds for
587 >     * each task or an (unchecked) exception is encountered, in which
588 >     * case the exception is rethrown. If any task encounters an
589 >     * exception, others may be, but are not guaranteed to be,
590 >     * cancelled.  If more than one task encounters an exception, then
591 >     * this method throws any one of these exceptions.  The individual
592 >     * status of each task may be checked using {@link #getException()}
593 >     * and related methods.
594 >     *
595 >     * <p>This method may be invoked only from within {@code
596 >     * ForkJoinTask} computations (as may be determined using method
597 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
598 >     * result in exceptions or errors, possibly including {@code
599 >     * ClassCastException}.
600       *
601 <     * @param tasks the array of tasks
602 <     * @throws NullPointerException if tasks or any element are null
558 <     * @throws RuntimeException or Error if any task did so
601 >     * @param tasks the tasks
602 >     * @throws NullPointerException if any task is null
603       */
604      public static void invokeAll(ForkJoinTask<?>... tasks) {
605          Throwable ex = null;
# Line 591 | Line 635 | public abstract class ForkJoinTask<V> im
635      }
636  
637      /**
638 <     * Forks all tasks in the collection, returning when
639 <     * {@code isDone} holds for all of them. If any task
640 <     * encounters an exception, others may be cancelled.  This method
641 <     * may be invoked only from within ForkJoinTask computations (as
642 <     * may be determined using method {@link
643 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
644 <     * in exceptions or errors, possibly including ClassCastException.
638 >     * Forks all tasks in the specified collection, returning when
639 >     * {@code isDone} holds for each task or an (unchecked) exception
640 >     * is encountered.  If any task encounters an exception, others
641 >     * may be, but are not guaranteed to be, cancelled.  If more than
642 >     * one task encounters an exception, then this method throws any
643 >     * one of these exceptions.  The individual status of each task
644 >     * may be checked using {@link #getException()} and related
645 >     * methods.  The behavior of this operation is undefined if the
646 >     * specified collection is modified while the operation is in
647 >     * progress.
648 >     *
649 >     * <p>This method may be invoked only from within {@code
650 >     * ForkJoinTask} computations (as may be determined using method
651 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
652 >     * result in exceptions or errors, possibly including {@code
653 >     * ClassCastException}.
654       *
655       * @param tasks the collection of tasks
656 +     * @return the tasks argument, to simplify usage
657       * @throws NullPointerException if tasks or any element are null
604     * @throws RuntimeException or Error if any task did so
658       */
659 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
660 <        if (!(tasks instanceof List<?>)) {
659 >    public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
660 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
661              invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
662 <            return;
662 >            return tasks;
663          }
664          @SuppressWarnings("unchecked")
665          List<? extends ForkJoinTask<?>> ts =
# Line 641 | Line 694 | public abstract class ForkJoinTask<V> im
694          }
695          if (ex != null)
696              rethrowException(ex);
697 +        return tasks;
698      }
699  
700      /**
701 <     * Returns true if the computation performed by this task has
702 <     * completed (or has been cancelled).
703 <     *
704 <     * @return true if this computation has completed
705 <     */
706 <    public final boolean isDone() {
707 <        return status < 0;
654 <    }
655 <
656 <    /**
657 <     * Returns true if this task was cancelled.
658 <     *
659 <     * @return true if this task was cancelled
660 <     */
661 <    public final boolean isCancelled() {
662 <        return (status & COMPLETION_MASK) == CANCELLED;
663 <    }
664 <
665 <    /**
666 <     * Asserts that the results of this task's computation will not be
667 <     * used. If a cancellation occurs before attempting to execute this
668 <     * task, then execution will be suppressed, {@code isCancelled}
669 <     * will report true, and {@code join} will result in a
670 <     * {@code CancellationException} being thrown. Otherwise, when
671 <     * cancellation races with completion, there are no guarantees
672 <     * about whether {@code isCancelled} will report true, whether
673 <     * {@code join} will return normally or via an exception, or
674 <     * whether these behaviors will remain consistent upon repeated
675 <     * invocation.
701 >     * Attempts to cancel execution of this task. This attempt will
702 >     * fail if the task has already completed, has already been
703 >     * cancelled, or could not be cancelled for some other reason. If
704 >     * successful, and this task has not started when cancel is
705 >     * called, execution of this task is suppressed, {@link
706 >     * #isCancelled} will report true, and {@link #join} will result
707 >     * in a {@code CancellationException} being thrown.
708       *
709       * <p>This method may be overridden in subclasses, but if so, must
710       * still ensure that these minimal properties hold. In particular,
711 <     * the cancel method itself must not throw exceptions.
711 >     * the {@code cancel} method itself must not throw exceptions.
712       *
713 <     * <p> This method is designed to be invoked by <em>other</em>
713 >     * <p>This method is designed to be invoked by <em>other</em>
714       * tasks. To terminate the current task, you can just return or
715       * throw an unchecked exception from its computation method, or
716 <     * invoke {@code completeExceptionally}.
716 >     * invoke {@link #completeExceptionally}.
717       *
718       * @param mayInterruptIfRunning this value is ignored in the
719 <     * default implementation because tasks are not in general
719 >     * default implementation because tasks are not
720       * cancelled via interruption
721       *
722 <     * @return true if this task is now cancelled
722 >     * @return {@code true} if this task is now cancelled
723       */
724      public boolean cancel(boolean mayInterruptIfRunning) {
725          setCompletion(CANCELLED);
726          return (status & COMPLETION_MASK) == CANCELLED;
727      }
728  
729 +    public final boolean isDone() {
730 +        return status < 0;
731 +    }
732 +
733 +    public final boolean isCancelled() {
734 +        return (status & COMPLETION_MASK) == CANCELLED;
735 +    }
736 +
737      /**
738 <     * Returns true if this task threw an exception or was cancelled.
738 >     * Returns {@code true} if this task threw an exception or was cancelled.
739       *
740 <     * @return true if this task threw an exception or was cancelled
740 >     * @return {@code true} if this task threw an exception or was cancelled
741       */
742      public final boolean isCompletedAbnormally() {
743          return (status & COMPLETION_MASK) < NORMAL;
744      }
745  
746      /**
747 +     * Returns {@code true} if this task completed without throwing an
748 +     * exception and was not cancelled.
749 +     *
750 +     * @return {@code true} if this task completed without throwing an
751 +     * exception and was not cancelled
752 +     */
753 +    public final boolean isCompletedNormally() {
754 +        return (status & COMPLETION_MASK) == NORMAL;
755 +    }
756 +
757 +    /**
758 +     * Returns {@code true} if this task threw an exception.
759 +     *
760 +     * @return {@code true} if this task threw an exception
761 +     */
762 +    public final boolean isCompletedExceptionally() {
763 +        return (status & COMPLETION_MASK) == EXCEPTIONAL;
764 +    }
765 +
766 +    /**
767       * Returns the exception thrown by the base computation, or a
768 <     * CancellationException if cancelled, or null if none or if the
769 <     * method has not yet completed.
768 >     * {@code CancellationException} if cancelled, or {@code null} if
769 >     * none or if the method has not yet completed.
770       *
771 <     * @return the exception, or null if none
771 >     * @return the exception, or {@code null} if none
772       */
773      public final Throwable getException() {
774          int s = status & COMPLETION_MASK;
775 <        if (s >= NORMAL)
776 <            return null;
777 <        if (s == CANCELLED)
718 <            return new CancellationException();
719 <        return exceptionMap.get(this);
775 >        return ((s >= NORMAL)    ? null :
776 >                (s == CANCELLED) ? new CancellationException() :
777 >                exceptionMap.get(this));
778      }
779  
780      /**
# Line 725 | Line 783 | public abstract class ForkJoinTask<V> im
783       * {@code join} and related operations. This method may be used
784       * to induce exceptions in asynchronous tasks, or to force
785       * completion of tasks that would not otherwise complete.  Its use
786 <     * in other situations is likely to be wrong.  This method is
786 >     * in other situations is discouraged.  This method is
787       * overridable, but overridden versions must invoke {@code super}
788       * implementation to maintain guarantees.
789       *
# Line 745 | Line 803 | public abstract class ForkJoinTask<V> im
803       * operations. This method may be used to provide results for
804       * asynchronous tasks, or to provide alternative handling for
805       * tasks that would not otherwise complete normally. Its use in
806 <     * other situations is likely to be wrong. This method is
806 >     * other situations is discouraged. This method is
807       * overridable, but overridden versions must invoke {@code super}
808       * implementation to maintain guarantees.
809       *
# Line 770 | Line 828 | public abstract class ForkJoinTask<V> im
828  
829      public final V get(long timeout, TimeUnit unit)
830          throws InterruptedException, ExecutionException, TimeoutException {
831 +        long nanos = unit.toNanos(timeout);
832          ForkJoinWorkerThread w = getWorker();
833          if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
834 <            awaitDone(w, unit.toNanos(timeout));
834 >            awaitDone(w, nanos);
835          return reportTimedFutureResult();
836      }
837  
838      /**
839 <     * Possibly executes other tasks until this task is ready, then
840 <     * returns the result of the computation.  This method may be more
841 <     * efficient than {@code join}, but is only applicable when
842 <     * there are no potential dependencies between continuation of the
843 <     * current task and that of any other task that might be executed
844 <     * while helping. (This usually holds for pure divide-and-conquer
845 <     * tasks). This method may be invoked only from within
846 <     * ForkJoinTask computations (as may be determined using method
847 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
848 <     * result in exceptions or errors, possibly including
849 <     * ClassCastException.
839 >     * Possibly executes other tasks until this task {@link #isDone is
840 >     * done}, then returns the result of the computation.  This method
841 >     * may be more efficient than {@code join}, but is only applicable
842 >     * when there are no potential dependencies between continuation
843 >     * of the current task and that of any other task that might be
844 >     * executed while helping. (This usually holds for pure
845 >     * divide-and-conquer tasks).
846 >     *
847 >     * <p>This method may be invoked only from within {@code
848 >     * ForkJoinTask} computations (as may be determined using method
849 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
850 >     * result in exceptions or errors, possibly including {@code
851 >     * ClassCastException}.
852       *
853       * @return the computed result
854       */
# Line 799 | Line 860 | public abstract class ForkJoinTask<V> im
860      }
861  
862      /**
863 <     * Possibly executes other tasks until this task is ready.  This
864 <     * method may be invoked only from within ForkJoinTask
865 <     * computations (as may be determined using method {@link
866 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
867 <     * in exceptions or errors, possibly including ClassCastException.
863 >     * Possibly executes other tasks until this task {@link #isDone is
864 >     * done}.  This method may be useful when processing collections
865 >     * of tasks when some have been cancelled or otherwise known to
866 >     * have aborted.
867 >     *
868 >     * <p>This method may be invoked only from within {@code
869 >     * ForkJoinTask} computations (as may be determined using method
870 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
871 >     * result in exceptions or errors, possibly including {@code
872 >     * ClassCastException}.
873       */
874      public final void quietlyHelpJoin() {
875          if (status >= 0) {
# Line 842 | Line 908 | public abstract class ForkJoinTask<V> im
908  
909      /**
910       * Possibly executes tasks until the pool hosting the current task
911 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
912 <     * designs in which many tasks are forked, but none are explicitly
913 <     * joined, instead executing them until all are processed.
911 >     * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
912 >     * be of use in designs in which many tasks are forked, but none
913 >     * are explicitly joined, instead executing them until all are
914 >     * processed.
915 >     *
916 >     * <p>This method may be invoked only from within {@code
917 >     * ForkJoinTask} computations (as may be determined using method
918 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
919 >     * result in exceptions or errors, possibly including {@code
920 >     * ClassCastException}.
921       */
922      public static void helpQuiesce() {
923          ((ForkJoinWorkerThread) Thread.currentThread())
# Line 857 | Line 930 | public abstract class ForkJoinTask<V> im
930       * this task, but only if reuse occurs when this task has either
931       * never been forked, or has been forked, then completed and all
932       * outstanding joins of this task have also completed. Effects
933 <     * under any other usage conditions are not guaranteed, and are
934 <     * almost surely wrong. This method may be useful when executing
933 >     * under any other usage conditions are not guaranteed.
934 >     * This method may be useful when executing
935       * pre-constructed trees of subtasks in loops.
936       */
937      public void reinitialize() {
# Line 871 | Line 944 | public abstract class ForkJoinTask<V> im
944       * Returns the pool hosting the current task execution, or null
945       * if this task is executing outside of any ForkJoinPool.
946       *
947 <     * @return the pool, or null if none
947 >     * @see #inForkJoinPool
948 >     * @return the pool, or {@code null} if none
949       */
950      public static ForkJoinPool getPool() {
951          Thread t = Thread.currentThread();
# Line 896 | Line 970 | public abstract class ForkJoinTask<V> im
970       * by the current thread, and has not commenced executing in
971       * another thread.  This method may be useful when arranging
972       * alternative local processing of tasks that could have been, but
973 <     * were not, stolen. This method may be invoked only from within
974 <     * ForkJoinTask computations (as may be determined using method
975 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
976 <     * result in exceptions or errors, possibly including
977 <     * ClassCastException.
973 >     * were not, stolen.
974 >     *
975 >     * <p>This method may be invoked only from within {@code
976 >     * ForkJoinTask} 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}.
980       *
981 <     * @return true if unforked
981 >     * @return {@code true} if unforked
982       */
983      public boolean tryUnfork() {
984          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 915 | Line 991 | public abstract class ForkJoinTask<V> im
991       * value may be useful for heuristic decisions about whether to
992       * fork other tasks.
993       *
994 +     * <p>This method may be invoked only from within {@code
995 +     * ForkJoinTask} 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}.
999 +     *
1000       * @return the number of tasks
1001       */
1002      public static int getQueuedTaskCount() {
# Line 932 | Line 1014 | public abstract class ForkJoinTask<V> im
1014       * tasks, and to process computations locally if this threshold is
1015       * exceeded.
1016       *
1017 +     * <p>This method may be invoked only from within {@code
1018 +     * ForkJoinTask} 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}.
1022 +     *
1023       * @return the surplus number of tasks, which may be negative
1024       */
1025      public static int getSurplusQueuedTaskCount() {
# Line 942 | Line 1030 | public abstract class ForkJoinTask<V> im
1030      // Extension methods
1031  
1032      /**
1033 <     * Returns the result that would be returned by {@code join},
1034 <     * even if this task completed abnormally, or null if this task is
1035 <     * not known to have been completed.  This method is designed to
1036 <     * aid debugging, as well as to support extensions. Its use in any
1037 <     * other context is discouraged.
1033 >     * Returns the result that would be returned by {@link #join}, even
1034 >     * if this task completed abnormally, or {@code null} if this task
1035 >     * is not known to have been completed.  This method is designed
1036 >     * to aid debugging, as well as to support extensions. Its use in
1037 >     * any other context is discouraged.
1038       *
1039 <     * @return the result, or null if not completed
1039 >     * @return the result, or {@code null} if not completed
1040       */
1041      public abstract V getRawResult();
1042  
# Line 967 | Line 1055 | public abstract class ForkJoinTask<V> im
1055       * called otherwise. The return value controls whether this task
1056       * is considered to be done normally. It may return false in
1057       * asynchronous actions that require explicit invocations of
1058 <     * {@code complete} to become joinable. It may throw exceptions
1059 <     * to indicate abnormal exit.
1058 >     * {@link #complete} to become joinable. It may also throw an
1059 >     * (unchecked) exception to indicate abnormal exit.
1060       *
1061 <     * @return true if completed normally
974 <     * @throws Error or RuntimeException if encountered during computation
1061 >     * @return {@code true} if completed normally
1062       */
1063      protected abstract boolean exec();
1064  
1065      /**
1066 <     * Returns, but does not unschedule or execute, the task queued by
1067 <     * the current thread but not yet executed, if one is
1066 >     * Returns, but does not unschedule or execute, a task queued by
1067 >     * the current thread but not yet executed, if one is immediately
1068       * available. There is no guarantee that this task will actually
1069 <     * be polled or executed next.  This method is designed primarily
1070 <     * to support extensions, and is unlikely to be useful otherwise.
1071 <     * This method may be invoked only from within ForkJoinTask
1072 <     * computations (as may be determined using method {@link
1073 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
987 <     * in exceptions or errors, possibly including ClassCastException.
1069 >     * be polled or executed next. Conversely, this method may return
1070 >     * null even if a task exists but cannot be accessed without
1071 >     * contention with other threads.  This method is designed
1072 >     * primarily to support extensions, and is unlikely to be useful
1073 >     * otherwise.
1074       *
1075 <     * @return the next task, or null if none are available
1075 >     * <p>This method may be invoked only from within {@code
1076 >     * ForkJoinTask} computations (as may be determined using method
1077 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1078 >     * result in exceptions or errors, possibly including {@code
1079 >     * ClassCastException}.
1080 >     *
1081 >     * @return the next task, or {@code null} if none are available
1082       */
1083      protected static ForkJoinTask<?> peekNextLocalTask() {
1084          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 997 | Line 1089 | public abstract class ForkJoinTask<V> im
1089       * Unschedules and returns, without executing, the next task
1090       * queued by the current thread but not yet executed.  This method
1091       * is designed primarily to support extensions, and is unlikely to
1092 <     * be useful otherwise.  This method may be invoked only from
1093 <     * within ForkJoinTask computations (as may be determined using
1094 <     * method {@link #inForkJoinPool}). Attempts to invoke in other
1095 <     * contexts result in exceptions or errors, possibly including
1096 <     * ClassCastException.
1092 >     * be useful otherwise.
1093 >     *
1094 >     * <p>This method may be invoked only from within {@code
1095 >     * ForkJoinTask} computations (as may be determined using method
1096 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1097 >     * result in exceptions or errors, possibly including {@code
1098 >     * ClassCastException}.
1099       *
1100 <     * @return the next task, or null if none are available
1100 >     * @return the next task, or {@code null} if none are available
1101       */
1102      protected static ForkJoinTask<?> pollNextLocalTask() {
1103          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1018 | Line 1112 | public abstract class ForkJoinTask<V> im
1112       * {@code null} result does not necessarily imply quiescence
1113       * of the pool this task is operating in.  This method is designed
1114       * primarily to support extensions, and is unlikely to be useful
1115 <     * otherwise.  This method may be invoked only from within
1116 <     * ForkJoinTask computations (as may be determined using method
1117 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1118 <     * result in exceptions or errors, possibly including
1119 <     * ClassCastException.
1115 >     * otherwise.
1116 >     *
1117 >     * <p>This method may be invoked only from within {@code
1118 >     * ForkJoinTask} computations (as may be determined using method
1119 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1120 >     * result in exceptions or errors, possibly including {@code
1121 >     * ClassCastException}.
1122       *
1123 <     * @return a task, or null if none are available
1123 >     * @return a task, or {@code null} if none are available
1124       */
1125      protected static ForkJoinTask<?> pollTask() {
1126          return ((ForkJoinWorkerThread) Thread.currentThread())
1127              .pollTask();
1128      }
1129  
1130 +    /**
1131 +     * Adaptor for Runnables. This implements RunnableFuture
1132 +     * to be compliant with AbstractExecutorService constraints
1133 +     * when used in ForkJoinPool.
1134 +     */
1135 +    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1136 +        implements RunnableFuture<T> {
1137 +        final Runnable runnable;
1138 +        final T resultOnCompletion;
1139 +        T result;
1140 +        AdaptedRunnable(Runnable runnable, T result) {
1141 +            if (runnable == null) throw new NullPointerException();
1142 +            this.runnable = runnable;
1143 +            this.resultOnCompletion = result;
1144 +        }
1145 +        public T getRawResult() { return result; }
1146 +        public void setRawResult(T v) { result = v; }
1147 +        public boolean exec() {
1148 +            runnable.run();
1149 +            result = resultOnCompletion;
1150 +            return true;
1151 +        }
1152 +        public void run() { invoke(); }
1153 +        private static final long serialVersionUID = 5232453952276885070L;
1154 +    }
1155 +
1156 +    /**
1157 +     * Adaptor for Callables
1158 +     */
1159 +    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1160 +        implements RunnableFuture<T> {
1161 +        final Callable<? extends T> callable;
1162 +        T result;
1163 +        AdaptedCallable(Callable<? extends T> callable) {
1164 +            if (callable == null) throw new NullPointerException();
1165 +            this.callable = callable;
1166 +        }
1167 +        public T getRawResult() { return result; }
1168 +        public void setRawResult(T v) { result = v; }
1169 +        public boolean exec() {
1170 +            try {
1171 +                result = callable.call();
1172 +                return true;
1173 +            } catch (Error err) {
1174 +                throw err;
1175 +            } catch (RuntimeException rex) {
1176 +                throw rex;
1177 +            } catch (Exception ex) {
1178 +                throw new RuntimeException(ex);
1179 +            }
1180 +        }
1181 +        public void run() { invoke(); }
1182 +        private static final long serialVersionUID = 2838392045355241008L;
1183 +    }
1184 +
1185 +    /**
1186 +     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1187 +     * method of the given {@code Runnable} as its action, and returns
1188 +     * a null result upon {@link #join}.
1189 +     *
1190 +     * @param runnable the runnable action
1191 +     * @return the task
1192 +     */
1193 +    public static ForkJoinTask<?> adapt(Runnable runnable) {
1194 +        return new AdaptedRunnable<Void>(runnable, null);
1195 +    }
1196 +
1197 +    /**
1198 +     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1199 +     * method of the given {@code Runnable} as its action, and returns
1200 +     * the given result upon {@link #join}.
1201 +     *
1202 +     * @param runnable the runnable action
1203 +     * @param result the result upon completion
1204 +     * @return the task
1205 +     */
1206 +    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1207 +        return new AdaptedRunnable<T>(runnable, result);
1208 +    }
1209 +
1210 +    /**
1211 +     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1212 +     * method of the given {@code Callable} as its action, and returns
1213 +     * its result upon {@link #join}, translating any checked exceptions
1214 +     * encountered into {@code RuntimeException}.
1215 +     *
1216 +     * @param callable the callable action
1217 +     * @return the task
1218 +     */
1219 +    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1220 +        return new AdaptedCallable<T>(callable);
1221 +    }
1222 +
1223      // Serialization support
1224  
1225      private static final long serialVersionUID = -7721805057305804111L;
# Line 1039 | Line 1228 | public abstract class ForkJoinTask<V> im
1228       * Save the state to a stream.
1229       *
1230       * @serialData the current run status and the exception thrown
1231 <     * during execution, or null if none
1231 >     * during execution, or {@code null} if none
1232       * @param s the stream
1233       */
1234      private void writeObject(java.io.ObjectOutputStream s)
# Line 1063 | Line 1252 | public abstract class ForkJoinTask<V> im
1252              setDoneExceptionally((Throwable) ex);
1253      }
1254  
1255 <    // Temporary Unsafe mechanics for preliminary release
1256 <    private static Unsafe getUnsafe() throws Throwable {
1255 >    // Unsafe mechanics
1256 >
1257 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1258 >    private static final long statusOffset =
1259 >        objectFieldOffset("status", ForkJoinTask.class);
1260 >
1261 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1262          try {
1263 <            return Unsafe.getUnsafe();
1263 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1264 >        } catch (NoSuchFieldException e) {
1265 >            // Convert Exception to corresponding Error
1266 >            NoSuchFieldError error = new NoSuchFieldError(field);
1267 >            error.initCause(e);
1268 >            throw error;
1269 >        }
1270 >    }
1271 >
1272 >    /**
1273 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1274 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1275 >     * into a jdk.
1276 >     *
1277 >     * @return a sun.misc.Unsafe
1278 >     */
1279 >    private static sun.misc.Unsafe getUnsafe() {
1280 >        try {
1281 >            return sun.misc.Unsafe.getUnsafe();
1282          } catch (SecurityException se) {
1283              try {
1284                  return java.security.AccessController.doPrivileged
1285 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1286 <                        public Unsafe run() throws Exception {
1287 <                            return getUnsafePrivileged();
1285 >                    (new java.security
1286 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1287 >                        public sun.misc.Unsafe run() throws Exception {
1288 >                            java.lang.reflect.Field f = sun.misc
1289 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1290 >                            f.setAccessible(true);
1291 >                            return (sun.misc.Unsafe) f.get(null);
1292                          }});
1293              } catch (java.security.PrivilegedActionException e) {
1294 <                throw e.getCause();
1294 >                throw new RuntimeException("Could not initialize intrinsics",
1295 >                                           e.getCause());
1296              }
1297          }
1298      }
1082
1083    private static Unsafe getUnsafePrivileged()
1084            throws NoSuchFieldException, IllegalAccessException {
1085        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1086        f.setAccessible(true);
1087        return (Unsafe) f.get(null);
1088    }
1089
1090    private static long fieldOffset(String fieldName)
1091            throws NoSuchFieldException {
1092        return UNSAFE.objectFieldOffset
1093            (ForkJoinTask.class.getDeclaredField(fieldName));
1094    }
1095
1096    static final Unsafe UNSAFE;
1097    static final long statusOffset;
1098
1099    static {
1100        try {
1101            UNSAFE = getUnsafe();
1102            statusOffset = fieldOffset("status");
1103        } catch (Throwable e) {
1104            throw new RuntimeException("Could not initialize intrinsics", e);
1105        }
1106    }
1107
1299   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines