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.19 by dl, Sat Jul 25 17:49:01 2009 UTC vs.
Revision 1.32 by dl, Mon Aug 3 13:01:15 2009 UTC

# Line 12 | Line 12 | 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 75 | Line 77 | import java.util.WeakHashMap;
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 ForkJoinTask class is not usually directly subclassed.
81   * Instead, you subclass one of the abstract classes that support a
82 < * particular style of fork/join processing.  Normally, a concrete
82 > * particular style of fork/join processing, typically {@link
83 > * RecursiveAction} for computations that do not return results, or
84 > * {@link RecursiveTask} for those that do.  Normally, a concrete
85   * ForkJoinTask subclass declares fields comprising its parameters,
86   * established in a constructor, and then defines a {@code compute}
87   * method that somehow uses the control methods supplied by this base
88   * class. While these methods have {@code public} access (to allow
89 < * instances of different task subclasses to call each others
89 > * instances of different task subclasses to call each other's
90   * methods), some of them may only be called from within other
91   * ForkJoinTasks (as may be determined using method {@link
92   * #inForkJoinPool}).  Attempts to invoke them in other contexts
93   * result in exceptions or errors, possibly including
94   * ClassCastException.
95   *
96 < * <p>Most base support methods are {@code final} because their
97 < * implementations are intrinsically tied to the underlying
98 < * lightweight task scheduling framework, and so cannot be overridden.
99 < * Developers creating new basic styles of fork/join processing should
100 < * minimally implement {@code protected} methods
101 < * {@code exec}, {@code setRawResult}, and
102 < * {@code getRawResult}, while also introducing an abstract
103 < * computational method that can be implemented in its subclasses,
104 < * possibly relying on other {@code protected} methods provided
101 < * by this class.
96 > * <p>Most base support methods are {@code final}, to prevent
97 > * overriding of implementations that are intrinsically tied to the
98 > * underlying lightweight task scheduling framework.  Developers
99 > * creating new basic styles of fork/join processing should minimally
100 > * implement {@code protected} methods {@link #exec}, {@link
101 > * #setRawResult}, and {@link #getRawResult}, while also introducing
102 > * an abstract computational method that can be implemented in its
103 > * subclasses, possibly relying on other {@code protected} methods
104 > * provided by this class.
105   *
106   * <p>ForkJoinTasks should perform relatively small amounts of
107 < * computations, otherwise splitting into smaller tasks. As a very
108 < * rough rule of thumb, a task should perform more than 100 and less
109 < * than 10000 basic computational steps. If tasks are too big, then
110 < * parallelism cannot improve throughput. If too small, then memory
111 < * and internal task maintenance overhead may overwhelm processing.
107 > * computation. Large tasks should be split into smaller subtasks,
108 > * usually via recursive decomposition. As a very rough rule of thumb,
109 > * a task should perform more than 100 and less than 10000 basic
110 > * computational steps. If tasks are too big, then parallelism cannot
111 > * improve throughput. If too small, then memory and internal task
112 > * maintenance overhead may overwhelm processing.
113   *
114 < * <p>ForkJoinTasks are {@code Serializable}, which enables them
115 < * to be used in extensions such as remote execution frameworks. It is
116 < * in general sensible to serialize tasks only before or after, but
117 < * not during execution. Serialization is not relied on during
118 < * execution itself.
114 > * <p>This class provides {@code adapt} methods for {@link
115 > * java.lang.Runnable} and {@link java.util.concurrent.Callable}, that
116 > * may be of use when mixing execution of ForkJoinTasks with other
117 > * kinds of tasks. When all tasks are of this form, consider using a
118 > * pool in {@link ForkJoinPool#setAsyncMode}.
119 > *
120 > * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
121 > * used in extensions such as remote execution frameworks. It is
122 > * sensible to serialize tasks only before or after, but not during,
123 > * execution. Serialization is not relied on during execution itself.
124   *
125   * @since 1.7
126   * @author Doug Lea
# Line 248 | Line 257 | public abstract class ForkJoinTask<V> im
257          synchronized (this) {
258              try {
259                  while (status >= 0) {
260 <                    long nt = nanos - System.nanoTime() - startTime;
260 >                    long nt = nanos - (System.nanoTime() - startTime);
261                      if (nt <= 0)
262                          break;
263                      wait(nt / 1000000, (int) (nt % 1000000));
# Line 487 | Line 496 | public abstract class ForkJoinTask<V> im
496      /**
497       * Arranges to asynchronously execute this task.  While it is not
498       * necessarily enforced, it is a usage error to fork a task more
499 <     * than once unless it has completed and been reinitialized.  This
500 <     * method may be invoked only from within ForkJoinTask
501 <     * computations (as may be determined using method {@link
502 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
503 <     * in exceptions or errors, possibly including ClassCastException.
499 >     * than once unless it has completed and been reinitialized.
500 >     *
501 >     * <p>This method may be invoked only from within {@code
502 >     * ForkJoinTask} computations (as may be determined using method
503 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
504 >     * result in exceptions or errors, possibly including {@code
505 >     * ClassCastException}.
506       *
507 <     * @return <code>this</code>, to simplify usage.
507 >     * @return {@code this}, to simplify usage
508       */
509      public final ForkJoinTask<V> fork() {
510          ((ForkJoinWorkerThread) Thread.currentThread())
# Line 503 | Line 514 | public abstract class ForkJoinTask<V> im
514  
515      /**
516       * Returns the result of the computation when it is ready.
517 <     * This method differs from {@code get} in that abnormal
518 <     * completion results in RuntimeExceptions or Errors, not
519 <     * ExecutionExceptions.
517 >     * This method differs from {@link #get()} in that
518 >     * abnormal completion results in {@code RuntimeException} or
519 >     * {@code Error}, not {@code ExecutionException}.
520       *
521       * @return the computed result
522       */
# Line 532 | Line 543 | public abstract class ForkJoinTask<V> im
543      }
544  
545      /**
546 <     * Forks both tasks, returning when {@code isDone} holds for
547 <     * both of them or an exception is encountered. This method may be
548 <     * invoked only from within ForkJoinTask computations (as may be
549 <     * determined using method {@link #inForkJoinPool}). Attempts to
550 <     * invoke in other contexts result in exceptions or errors,
551 <     * possibly including ClassCastException.
552 <     *
553 <     * @param t1 one task
554 <     * @param t2 the other task
555 <     * @throws NullPointerException if t1 or t2 are null
556 <     * @throws RuntimeException or Error if either task did so
546 >     * Forks the given tasks, returning when {@code isDone} holds
547 >     * for each task or an exception is encountered.
548 >     *
549 >     * <p>This method may be invoked only from within {@code
550 >     * ForkJoinTask} computations (as may be determined using method
551 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
552 >     * result in exceptions or errors, possibly including {@code
553 >     * ClassCastException}.
554 >     *
555 >     * @param t1 the first task
556 >     * @param t2 the second task
557 >     * @throws NullPointerException if any task is null
558 >     * @throws RuntimeException or Error if a task did so
559       */
560 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
560 >    public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
561          t2.fork();
562          t1.invoke();
563          t2.join();
564      }
565  
566      /**
567 <     * Forks the given tasks, returning when {@code isDone} holds
568 <     * for all of them. If any task encounters an exception, others
569 <     * may be cancelled.  This method may be invoked only from within
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
573 <     * ClassCastException.
567 >     * Forks the given tasks, returning when {@code isDone} holds for
568 >     * each task or an exception is encountered. If any task
569 >     * encounters an exception, others may be, but are not guaranteed
570 >     * to be, cancelled.
571 >     *
572 >     * <p>This method may be invoked only from within {@code
573 >     * ForkJoinTask} computations (as may be determined using method
574 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
575 >     * result in exceptions or errors, possibly including {@code
576 >     * ClassCastException}.
577       *
578 <     * @param tasks the array of tasks
578 >     * @param tasks the tasks
579       * @throws NullPointerException if tasks or any element are null
580       * @throws RuntimeException or Error if any task did so
581       */
# Line 597 | Line 613 | public abstract class ForkJoinTask<V> im
613      }
614  
615      /**
616 <     * Forks all tasks in the collection, returning when
617 <     * {@code isDone} holds for all of them. If any task
618 <     * encounters an exception, others may be cancelled.  This method
619 <     * may be invoked only from within ForkJoinTask computations (as
620 <     * may be determined using method {@link
621 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
622 <     * in exceptions or errors, possibly including ClassCastException.
616 >     * Forks all tasks in the specified collection, returning when
617 >     * {@code isDone} holds for each task or an exception is
618 >     * encountered.  If any task encounters an exception, others may
619 >     * be, but are not guaranteed to be, cancelled. The behavior of
620 >     * this operation is undefined if the specified collection is
621 >     * modified while the operation is in progress.
622 >     *
623 >     * <p>This method may be invoked only from within {@code
624 >     * ForkJoinTask} computations (as may be determined using method
625 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
626 >     * result in exceptions or errors, possibly including {@code
627 >     * ClassCastException}.
628       *
629       * @param tasks the collection of tasks
630       * @return the tasks argument, to simplify usage
# Line 611 | Line 632 | public abstract class ForkJoinTask<V> im
632       * @throws RuntimeException or Error if any task did so
633       */
634      public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
635 <        if (!(tasks instanceof List<?>)) {
635 >        if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
636              invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
637              return tasks;
638          }
# Line 652 | Line 673 | public abstract class ForkJoinTask<V> im
673      }
674  
675      /**
676 <     * Returns true if the computation performed by this task has
677 <     * completed (or has been cancelled).
676 >     * Returns {@code true} if the computation performed by this task
677 >     * has completed (or has been cancelled).
678       *
679 <     * @return true if this computation has completed
679 >     * @return {@code true} if this computation has completed
680       */
681      public final boolean isDone() {
682          return status < 0;
683      }
684  
685      /**
686 <     * Returns true if this task was cancelled.
686 >     * Returns {@code true} if this task was cancelled.
687       *
688 <     * @return true if this task was cancelled
688 >     * @return {@code true} if this task was cancelled
689       */
690      public final boolean isCancelled() {
691          return (status & COMPLETION_MASK) == CANCELLED;
# Line 673 | Line 694 | public abstract class ForkJoinTask<V> im
694      /**
695       * Asserts that the results of this task's computation will not be
696       * used. If a cancellation occurs before attempting to execute this
697 <     * task, then execution will be suppressed, {@code isCancelled}
698 <     * will report true, and {@code join} will result in a
697 >     * task, execution will be suppressed, {@link #isCancelled}
698 >     * will report true, and {@link #join} will result in a
699       * {@code CancellationException} being thrown. Otherwise, when
700       * cancellation races with completion, there are no guarantees
701 <     * about whether {@code isCancelled} will report true, whether
702 <     * {@code join} will return normally or via an exception, or
703 <     * whether these behaviors will remain consistent upon repeated
701 >     * about whether {@code isCancelled} will report {@code true},
702 >     * whether {@code join} will return normally or via an exception,
703 >     * or whether these behaviors will remain consistent upon repeated
704       * invocation.
705       *
706       * <p>This method may be overridden in subclasses, but if so, must
707       * still ensure that these minimal properties hold. In particular,
708 <     * the cancel method itself must not throw exceptions.
708 >     * the {@code cancel} method itself must not throw exceptions.
709       *
710 <     * <p> This method is designed to be invoked by <em>other</em>
710 >     * <p>This method is designed to be invoked by <em>other</em>
711       * tasks. To terminate the current task, you can just return or
712       * throw an unchecked exception from its computation method, or
713 <     * invoke {@code completeExceptionally}.
713 >     * invoke {@link #completeExceptionally}.
714       *
715       * @param mayInterruptIfRunning this value is ignored in the
716       * default implementation because tasks are not in general
717       * cancelled via interruption
718       *
719 <     * @return true if this task is now cancelled
719 >     * @return {@code true} if this task is now cancelled
720       */
721      public boolean cancel(boolean mayInterruptIfRunning) {
722          setCompletion(CANCELLED);
# Line 703 | Line 724 | public abstract class ForkJoinTask<V> im
724      }
725  
726      /**
727 <     * Returns true if this task threw an exception or was cancelled.
727 >     * Returns {@code true} if this task threw an exception or was cancelled.
728       *
729 <     * @return true if this task threw an exception or was cancelled
729 >     * @return {@code true} if this task threw an exception or was cancelled
730       */
731      public final boolean isCompletedAbnormally() {
732          return (status & COMPLETION_MASK) < NORMAL;
# Line 713 | Line 734 | public abstract class ForkJoinTask<V> im
734  
735      /**
736       * Returns the exception thrown by the base computation, or a
737 <     * CancellationException if cancelled, or null if none or if the
738 <     * method has not yet completed.
737 >     * {@code CancellationException} if cancelled, or {@code null} if
738 >     * none or if the method has not yet completed.
739       *
740 <     * @return the exception, or null if none
740 >     * @return the exception, or {@code null} if none
741       */
742      public final Throwable getException() {
743          int s = status & COMPLETION_MASK;
# Line 733 | Line 754 | public abstract class ForkJoinTask<V> im
754       * {@code join} and related operations. This method may be used
755       * to induce exceptions in asynchronous tasks, or to force
756       * completion of tasks that would not otherwise complete.  Its use
757 <     * in other situations is likely to be wrong.  This method is
757 >     * in other situations is discouraged.  This method is
758       * overridable, but overridden versions must invoke {@code super}
759       * implementation to maintain guarantees.
760       *
# Line 753 | Line 774 | public abstract class ForkJoinTask<V> im
774       * operations. This method may be used to provide results for
775       * asynchronous tasks, or to provide alternative handling for
776       * tasks that would not otherwise complete normally. Its use in
777 <     * other situations is likely to be wrong. This method is
777 >     * other situations is discouraged. This method is
778       * overridable, but overridden versions must invoke {@code super}
779       * implementation to maintain guarantees.
780       *
# Line 778 | Line 799 | public abstract class ForkJoinTask<V> im
799  
800      public final V get(long timeout, TimeUnit unit)
801          throws InterruptedException, ExecutionException, TimeoutException {
802 +        long nanos = unit.toNanos(timeout);
803          ForkJoinWorkerThread w = getWorker();
804          if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
805 <            awaitDone(w, unit.toNanos(timeout));
805 >            awaitDone(w, nanos);
806          return reportTimedFutureResult();
807      }
808  
# Line 791 | Line 813 | public abstract class ForkJoinTask<V> im
813       * there are no potential dependencies between continuation of the
814       * current task and that of any other task that might be executed
815       * while helping. (This usually holds for pure divide-and-conquer
816 <     * tasks). This method may be invoked only from within
817 <     * ForkJoinTask computations (as may be determined using method
818 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
819 <     * result in exceptions or errors, possibly including
820 <     * ClassCastException.
816 >     * tasks).
817 >     *
818 >     * <p>This method may be invoked only from within {@code
819 >     * ForkJoinTask} computations (as may be determined using method
820 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
821 >     * result in exceptions or errors, possibly including {@code
822 >     * ClassCastException}.
823       *
824       * @return the computed result
825       */
# Line 808 | Line 832 | public abstract class ForkJoinTask<V> im
832  
833      /**
834       * Possibly executes other tasks until this task is ready.  This
835 <     * method may be invoked only from within ForkJoinTask
836 <     * computations (as may be determined using method {@link
837 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
838 <     * in exceptions or errors, possibly including ClassCastException.
835 >     * method may be useful when processing collections of tasks when
836 >     * some have been cancelled or otherwise known to have aborted.
837 >     *
838 >     * <p>This method may be invoked only from within {@code
839 >     * ForkJoinTask} computations (as may be determined using method
840 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
841 >     * result in exceptions or errors, possibly including {@code
842 >     * ClassCastException}.
843       */
844      public final void quietlyHelpJoin() {
845          if (status >= 0) {
# Line 853 | Line 881 | public abstract class ForkJoinTask<V> im
881       * {@link ForkJoinPool#isQuiescent}. This method may be of use in
882       * designs in which many tasks are forked, but none are explicitly
883       * joined, instead executing them until all are processed.
884 +     *
885 +     * <p>This method may be invoked only from within {@code
886 +     * ForkJoinTask} computations (as may be determined using method
887 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
888 +     * result in exceptions or errors, possibly including {@code
889 +     * ClassCastException}.
890       */
891      public static void helpQuiesce() {
892          ((ForkJoinWorkerThread) Thread.currentThread())
# Line 865 | Line 899 | public abstract class ForkJoinTask<V> im
899       * this task, but only if reuse occurs when this task has either
900       * never been forked, or has been forked, then completed and all
901       * outstanding joins of this task have also completed. Effects
902 <     * under any other usage conditions are not guaranteed, and are
903 <     * almost surely wrong. This method may be useful when executing
902 >     * under any other usage conditions are not guaranteed.
903 >     * This method may be useful when executing
904       * pre-constructed trees of subtasks in loops.
905       */
906      public void reinitialize() {
# Line 879 | Line 913 | public abstract class ForkJoinTask<V> im
913       * Returns the pool hosting the current task execution, or null
914       * if this task is executing outside of any ForkJoinPool.
915       *
916 <     * @return the pool, or null if none
916 >     * @see #inForkJoinPool
917 >     * @return the pool, or {@code null} if none
918       */
919      public static ForkJoinPool getPool() {
920          Thread t = Thread.currentThread();
# Line 904 | Line 939 | public abstract class ForkJoinTask<V> im
939       * by the current thread, and has not commenced executing in
940       * another thread.  This method may be useful when arranging
941       * alternative local processing of tasks that could have been, but
942 <     * were not, stolen. This method may be invoked only from within
943 <     * ForkJoinTask computations (as may be determined using method
944 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
945 <     * result in exceptions or errors, possibly including
946 <     * ClassCastException.
942 >     * were not, stolen.
943 >     *
944 >     * <p>This method may be invoked only from within {@code
945 >     * ForkJoinTask} computations (as may be determined using method
946 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
947 >     * result in exceptions or errors, possibly including {@code
948 >     * ClassCastException}.
949       *
950 <     * @return true if unforked
950 >     * @return {@code true} if unforked
951       */
952      public boolean tryUnfork() {
953          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 923 | Line 960 | public abstract class ForkJoinTask<V> im
960       * value may be useful for heuristic decisions about whether to
961       * fork other tasks.
962       *
963 +     * <p>This method may be invoked only from within {@code
964 +     * ForkJoinTask} computations (as may be determined using method
965 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
966 +     * result in exceptions or errors, possibly including {@code
967 +     * ClassCastException}.
968 +     *
969       * @return the number of tasks
970       */
971      public static int getQueuedTaskCount() {
# Line 940 | Line 983 | public abstract class ForkJoinTask<V> im
983       * tasks, and to process computations locally if this threshold is
984       * exceeded.
985       *
986 +     * <p>This method may be invoked only from within {@code
987 +     * ForkJoinTask} computations (as may be determined using method
988 +     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
989 +     * result in exceptions or errors, possibly including {@code
990 +     * ClassCastException}.
991 +     *
992       * @return the surplus number of tasks, which may be negative
993       */
994      public static int getSurplusQueuedTaskCount() {
# Line 950 | Line 999 | public abstract class ForkJoinTask<V> im
999      // Extension methods
1000  
1001      /**
1002 <     * Returns the result that would be returned by {@code join},
1003 <     * even if this task completed abnormally, or null if this task is
1004 <     * not known to have been completed.  This method is designed to
1005 <     * aid debugging, as well as to support extensions. Its use in any
1006 <     * other context is discouraged.
1002 >     * Returns the result that would be returned by {@link #join}, even
1003 >     * if this task completed abnormally, or {@code null} if this task
1004 >     * is not known to have been completed.  This method is designed
1005 >     * to aid debugging, as well as to support extensions. Its use in
1006 >     * any other context is discouraged.
1007       *
1008 <     * @return the result, or null if not completed
1008 >     * @return the result, or {@code null} if not completed
1009       */
1010      public abstract V getRawResult();
1011  
# Line 975 | Line 1024 | public abstract class ForkJoinTask<V> im
1024       * called otherwise. The return value controls whether this task
1025       * is considered to be done normally. It may return false in
1026       * asynchronous actions that require explicit invocations of
1027 <     * {@code complete} to become joinable. It may throw exceptions
1027 >     * {@link #complete} to become joinable. It may throw exceptions
1028       * to indicate abnormal exit.
1029       *
1030 <     * @return true if completed normally
1030 >     * @return {@code true} if completed normally
1031       * @throws Error or RuntimeException if encountered during computation
1032       */
1033      protected abstract boolean exec();
1034  
1035      /**
1036 <     * Returns, but does not unschedule or execute, the task queued by
1037 <     * the current thread but not yet executed, if one is
1036 >     * Returns, but does not unschedule or execute, a task queued by
1037 >     * the current thread but not yet executed, if one is immediately
1038       * available. There is no guarantee that this task will actually
1039 <     * be polled or executed next.  This method is designed primarily
1040 <     * to support extensions, and is unlikely to be useful otherwise.
1041 <     * This method may be invoked only from within ForkJoinTask
1042 <     * computations (as may be determined using method {@link
1043 <     * #inForkJoinPool}). Attempts to invoke in other contexts result
995 <     * in exceptions or errors, possibly including ClassCastException.
1039 >     * be polled or executed next. Conversely, this method may return
1040 >     * null even if a task exists but cannot be accessed without
1041 >     * contention with other threads.  This method is designed
1042 >     * primarily to support extensions, and is unlikely to be useful
1043 >     * otherwise.
1044       *
1045 <     * @return the next task, or null if none are available
1045 >     * <p>This method may be invoked only from within {@code
1046 >     * ForkJoinTask} computations (as may be determined using method
1047 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1048 >     * result in exceptions or errors, possibly including {@code
1049 >     * ClassCastException}.
1050 >     *
1051 >     * @return the next task, or {@code null} if none are available
1052       */
1053      protected static ForkJoinTask<?> peekNextLocalTask() {
1054          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1005 | Line 1059 | public abstract class ForkJoinTask<V> im
1059       * Unschedules and returns, without executing, the next task
1060       * queued by the current thread but not yet executed.  This method
1061       * is designed primarily to support extensions, and is unlikely to
1062 <     * be useful otherwise.  This method may be invoked only from
1063 <     * within ForkJoinTask computations (as may be determined using
1064 <     * method {@link #inForkJoinPool}). Attempts to invoke in other
1065 <     * contexts result in exceptions or errors, possibly including
1066 <     * ClassCastException.
1062 >     * be useful otherwise.
1063 >     *
1064 >     * <p>This method may be invoked only from within {@code
1065 >     * ForkJoinTask} computations (as may be determined using method
1066 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1067 >     * result in exceptions or errors, possibly including {@code
1068 >     * ClassCastException}.
1069       *
1070 <     * @return the next task, or null if none are available
1070 >     * @return the next task, or {@code null} if none are available
1071       */
1072      protected static ForkJoinTask<?> pollNextLocalTask() {
1073          return ((ForkJoinWorkerThread) Thread.currentThread())
# Line 1026 | Line 1082 | public abstract class ForkJoinTask<V> im
1082       * {@code null} result does not necessarily imply quiescence
1083       * of the pool this task is operating in.  This method is designed
1084       * primarily to support extensions, and is unlikely to be useful
1085 <     * otherwise.  This method may be invoked only from within
1086 <     * ForkJoinTask computations (as may be determined using method
1087 <     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1088 <     * result in exceptions or errors, possibly including
1089 <     * ClassCastException.
1085 >     * otherwise.
1086 >     *
1087 >     * <p>This method may be invoked only from within {@code
1088 >     * ForkJoinTask} computations (as may be determined using method
1089 >     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1090 >     * result in exceptions or errors, possibly including {@code
1091 >     * ClassCastException}.
1092       *
1093 <     * @return a task, or null if none are available
1093 >     * @return a task, or {@code null} if none are available
1094       */
1095      protected static ForkJoinTask<?> pollTask() {
1096          return ((ForkJoinWorkerThread) Thread.currentThread())
1097              .pollTask();
1098      }
1099  
1100 <    // adaptors
1100 >    /**
1101 >     * Adaptor for Runnables. This implements RunnableFuture
1102 >     * to be compliant with AbstractExecutorService constraints
1103 >     * when used in ForkJoinPool.
1104 >     */
1105 >    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1106 >        implements RunnableFuture<T> {
1107 >        final Runnable runnable;
1108 >        final T resultOnCompletion;
1109 >        T result;
1110 >        AdaptedRunnable(Runnable runnable, T result) {
1111 >            if (runnable == null) throw new NullPointerException();
1112 >            this.runnable = runnable;
1113 >            this.resultOnCompletion = result;
1114 >        }
1115 >        public T getRawResult() { return result; }
1116 >        public void setRawResult(T v) { result = v; }
1117 >        public boolean exec() {
1118 >            runnable.run();
1119 >            result = resultOnCompletion;
1120 >            return true;
1121 >        }
1122 >        public void run() { invoke(); }
1123 >        private static final long serialVersionUID = 5232453952276885070L;
1124 >    }
1125 >
1126 >    /**
1127 >     * Adaptor for Callables
1128 >     */
1129 >    static final class AdaptedCallable<T> extends ForkJoinTask<T>
1130 >        implements RunnableFuture<T> {
1131 >        final Callable<? extends T> callable;
1132 >        T result;
1133 >        AdaptedCallable(Callable<? extends T> callable) {
1134 >            if (callable == null) throw new NullPointerException();
1135 >            this.callable = callable;
1136 >        }
1137 >        public T getRawResult() { return result; }
1138 >        public void setRawResult(T v) { result = v; }
1139 >        public boolean exec() {
1140 >            try {
1141 >                result = callable.call();
1142 >                return true;
1143 >            } catch (Error err) {
1144 >                throw err;
1145 >            } catch (RuntimeException rex) {
1146 >                throw rex;
1147 >            } catch (Exception ex) {
1148 >                throw new RuntimeException(ex);
1149 >            }
1150 >        }
1151 >        public void run() { invoke(); }
1152 >        private static final long serialVersionUID = 2838392045355241008L;
1153 >    }
1154  
1155      /**
1156 <     * Returns a new ForkJoinTask that performs the <code>run</code>
1157 <     * method of the given Runnable as its action, and returns a null
1158 <     * result upon <code>join</code>.
1156 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1157 >     * method of the given {@code Runnable} as its action, and returns
1158 >     * a null result upon {@link #join}.
1159       *
1160       * @param runnable the runnable action
1161       * @return the task
1162       */
1163 <    public static ForkJoinTask<Void> adapt(Runnable runnable) {
1164 <        return new ForkJoinPool.AdaptedRunnable<Void>(runnable, null);
1163 >    public static ForkJoinTask<?> adapt(Runnable runnable) {
1164 >        return new AdaptedRunnable<Void>(runnable, null);
1165      }
1166  
1167      /**
1168 <     * Returns a new ForkJoinTask that performs the <code>run</code>
1169 <     * method of the given Runnable as its action, and returns the
1170 <     * given result upon <code>join</code>.
1168 >     * Returns a new {@code ForkJoinTask} that performs the {@code run}
1169 >     * method of the given {@code Runnable} as its action, and returns
1170 >     * the given result upon {@link #join}.
1171       *
1172       * @param runnable the runnable action
1173       * @param result the result upon completion
1174       * @return the task
1175       */
1176      public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1177 <        return new ForkJoinPool.AdaptedRunnable<T>(runnable, result);
1177 >        return new AdaptedRunnable<T>(runnable, result);
1178      }
1179  
1180      /**
1181 <     * Returns a new ForkJoinTask that performs the <code>call</code>
1182 <     * method of the given Callable as its action, and returns its
1183 <     * result upon <code>join</code>, translating any checked
1184 <     * exceptions encountered into <code>RuntimeException<code>.
1181 >     * Returns a new {@code ForkJoinTask} that performs the {@code call}
1182 >     * method of the given {@code Callable} as its action, and returns
1183 >     * its result upon {@link #join}, translating any checked exceptions
1184 >     * encountered into {@code RuntimeException}.
1185       *
1186       * @param callable the callable action
1187       * @return the task
1188       */
1189 <    public static <T> ForkJoinTask<T> adapt(Callable<T> callable) {
1190 <        return new ForkJoinPool.AdaptedCallable<T>(callable);
1189 >    public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1190 >        return new AdaptedCallable<T>(callable);
1191      }
1192  
1193      // Serialization support
# Line 1087 | Line 1198 | public abstract class ForkJoinTask<V> im
1198       * Save the state to a stream.
1199       *
1200       * @serialData the current run status and the exception thrown
1201 <     * during execution, or null if none
1201 >     * during execution, or {@code null} if none
1202       * @param s the stream
1203       */
1204      private void writeObject(java.io.ObjectOutputStream s)
# Line 1111 | Line 1222 | public abstract class ForkJoinTask<V> im
1222              setDoneExceptionally((Throwable) ex);
1223      }
1224  
1225 <    // Unsafe mechanics for jsr166y 3rd party package.
1225 >    // Unsafe mechanics
1226 >
1227 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1228 >    private static final long statusOffset =
1229 >        objectFieldOffset("status", ForkJoinTask.class);
1230 >
1231 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1232 >        try {
1233 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1234 >        } catch (NoSuchFieldException e) {
1235 >            // Convert Exception to corresponding Error
1236 >            NoSuchFieldError error = new NoSuchFieldError(field);
1237 >            error.initCause(e);
1238 >            throw error;
1239 >        }
1240 >    }
1241 >
1242 >    /**
1243 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1244 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1245 >     * into a jdk.
1246 >     *
1247 >     * @return a sun.misc.Unsafe
1248 >     */
1249      private static sun.misc.Unsafe getUnsafe() {
1250          try {
1251              return sun.misc.Unsafe.getUnsafe();
1252          } catch (SecurityException se) {
1253              try {
1254                  return java.security.AccessController.doPrivileged
1255 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1255 >                    (new java.security
1256 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1257                          public sun.misc.Unsafe run() throws Exception {
1258 <                            return getUnsafeByReflection();
1258 >                            java.lang.reflect.Field f = sun.misc
1259 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1260 >                            f.setAccessible(true);
1261 >                            return (sun.misc.Unsafe) f.get(null);
1262                          }});
1263              } catch (java.security.PrivilegedActionException e) {
1264                  throw new RuntimeException("Could not initialize intrinsics",
# Line 1128 | Line 1266 | public abstract class ForkJoinTask<V> im
1266              }
1267          }
1268      }
1131
1132    private static sun.misc.Unsafe getUnsafeByReflection()
1133            throws NoSuchFieldException, IllegalAccessException {
1134        java.lang.reflect.Field f =
1135            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1136        f.setAccessible(true);
1137        return (sun.misc.Unsafe) f.get(null);
1138    }
1139
1140    private static long fieldOffset(String fieldName, Class<?> klazz) {
1141        try {
1142            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1143        } catch (NoSuchFieldException e) {
1144            // Convert Exception to Error
1145            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1146            error.initCause(e);
1147            throw error;
1148        }
1149    }
1150
1151    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1152    static final long statusOffset =
1153        fieldOffset("status", ForkJoinTask.class);
1154
1269   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines