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.7 by jsr166, Mon Jul 20 21:45:06 2009 UTC vs.
Revision 1.18 by dl, Sat Jul 25 15:50:57 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.Map;
16 > import java.util.WeakHashMap;
17  
18   /**
19   * Abstract base class for tasks that run within a {@link
# Line 22 | Line 25 | import java.lang.reflect.*;
25   * <p> A "main" ForkJoinTask begins execution when submitted to a
26   * {@link ForkJoinPool}. Once started, it will usually in turn start
27   * other subtasks.  As indicated by the name of this class, many
28 < * programs using ForkJoinTasks employ only methods <code>fork</code>
29 < * and <code>join</code>, or derivatives such as
30 < * <code>invokeAll</code>.  However, this class also provides a number
28 > * programs using ForkJoinTasks employ only methods {@code fork}
29 > * and {@code join}, or derivatives such as
30 > * {@code invokeAll}.  However, this class also provides a number
31   * of other methods that can come into play in advanced usages, as
32   * well as extension mechanics that allow support of new forms of
33   * fork/join processing.
# Line 36 | Line 39 | import java.lang.reflect.*;
39   * operating on purely isolated objects.  The primary coordination
40   * mechanisms are {@link #fork}, that arranges asynchronous execution,
41   * and {@link #join}, that doesn't proceed until the task's result has
42 < * been computed.  Computations should avoid <code>synchronized</code>
42 > * been computed.  Computations should avoid {@code synchronized}
43   * methods or blocks, and should minimize other blocking
44   * synchronization apart from joining other tasks or using
45   * synchronizers such as Phasers that are advertised to cooperate with
# Line 48 | Line 51 | import java.lang.reflect.*;
51   * performance, and the potential to indefinitely stall if the number
52   * of threads not waiting for IO or other external synchronization
53   * becomes exhausted. This usage restriction is in part enforced by
54 < * not permitting checked exceptions such as <code>IOExceptions</code>
54 > * not permitting checked exceptions such as {@code IOExceptions}
55   * to be thrown. However, computations may still encounter unchecked
56   * exceptions, that are rethrown to callers attempting join
57   * them. These exceptions may additionally include
# Line 58 | Line 61 | import java.lang.reflect.*;
61   * <p>The primary method for awaiting completion and extracting
62   * results of a task is {@link #join}, but there are several variants:
63   * The {@link Future#get} methods support interruptible and/or timed
64 < * waits for completion and report results using <code>Future</code>
64 > * waits for completion and report results using {@code Future}
65   * conventions. Method {@link #helpJoin} enables callers to actively
66   * execute other tasks while awaiting joins, which is sometimes more
67   * efficient but only applies when all subtasks are known to be
68   * strictly tree-structured. Method {@link #invoke} is semantically
69 < * equivalent to <code>fork(); join()</code> but always attempts to
69 > * equivalent to {@code fork(); join()} but always attempts to
70   * begin execution in the current thread. The "<em>quiet</em>" forms
71   * of these methods do not extract results or report exceptions. These
72   * may be useful when a set of tasks are being executed, and you need
73   * to delay processing of results or exceptions until all complete.
74 < * Method <code>invokeAll</code> (available in multiple versions)
74 > * Method {@code invokeAll} (available in multiple versions)
75   * performs the most common form of parallel invocation: forking a set
76   * of tasks and joining them all.
77   *
# Line 76 | Line 79 | import java.lang.reflect.*;
79   * Instead, you subclass one of the abstract classes that support a
80   * particular style of fork/join processing.  Normally, a concrete
81   * ForkJoinTask subclass declares fields comprising its parameters,
82 < * established in a constructor, and then defines a <code>compute</code>
82 > * established in a constructor, and then defines a {@code compute}
83   * method that somehow uses the control methods supplied by this base
84 < * class. While these methods have <code>public</code> access (to allow
84 > * class. While these methods have {@code public} access (to allow
85   * instances of different task subclasses to call each others
86   * methods), some of them may only be called from within other
87 < * ForkJoinTasks. Attempts to invoke them in other contexts result in
88 < * exceptions or errors possibly including ClassCastException.
87 > * ForkJoinTasks (as may be determined using method {@link
88 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
89 > * result in exceptions or errors, possibly including
90 > * ClassCastException.
91   *
92 < * <p>Most base support methods are <code>final</code> because their
92 > * <p>Most base support methods are {@code final} because their
93   * implementations are intrinsically tied to the underlying
94   * lightweight task scheduling framework, and so cannot be overridden.
95   * Developers creating new basic styles of fork/join processing should
96 < * minimally implement <code>protected</code> methods
97 < * <code>exec</code>, <code>setRawResult</code>, and
98 < * <code>getRawResult</code>, while also introducing an abstract
96 > * minimally implement {@code protected} methods
97 > * {@code exec}, {@code setRawResult}, and
98 > * {@code getRawResult}, while also introducing an abstract
99   * computational method that can be implemented in its subclasses,
100 < * possibly relying on other <code>protected</code> methods provided
100 > * possibly relying on other {@code protected} methods provided
101   * by this class.
102   *
103   * <p>ForkJoinTasks should perform relatively small amounts of
104 < * computations, othewise splitting into smaller tasks. As a very
104 > * computations, otherwise splitting into smaller tasks. As a very
105   * rough rule of thumb, a task should perform more than 100 and less
106   * than 10000 basic computational steps. If tasks are too big, then
107 < * parellelism cannot improve throughput. If too small, then memory
107 > * parallelism cannot improve throughput. If too small, then memory
108   * and internal task maintenance overhead may overwhelm processing.
109   *
110 < * <p>ForkJoinTasks are <code>Serializable</code>, which enables them
110 > * <p>ForkJoinTasks are {@code Serializable}, which enables them
111   * to be used in extensions such as remote execution frameworks. It is
112   * in general sensible to serialize tasks only before or after, but
113   * not during execution. Serialization is not relied on during
114   * execution itself.
115 + *
116 + * @since 1.7
117 + * @author Doug Lea
118   */
119   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
120  
# Line 128 | Line 136 | public abstract class ForkJoinTask<V> im
136       * currently unused. Also value 0x80000000 is available as spare
137       * completion value.
138       */
139 <    volatile int status; // accessed directy by pool and workers
139 >    volatile int status; // accessed directly by pool and workers
140  
141      static final int COMPLETION_MASK      = 0xe0000000;
142      static final int NORMAL               = 0xe0000000; // == mask
# Line 141 | Line 149 | public abstract class ForkJoinTask<V> im
149      /**
150       * Table of exceptions thrown by tasks, to enable reporting by
151       * callers. Because exceptions are rare, we don't directly keep
152 <     * them with task objects, but instead us a weak ref table.  Note
152 >     * them with task objects, but instead use a weak ref table.  Note
153       * that cancellation exceptions don't appear in the table, but are
154       * instead recorded as status values.
155 <     * Todo: Use ConcurrentReferenceHashMap
155 >     * TODO: Use ConcurrentReferenceHashMap
156       */
157      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
158          Collections.synchronizedMap
# Line 153 | Line 161 | public abstract class ForkJoinTask<V> im
161      // within-package utilities
162  
163      /**
164 <     * Get current worker thread, or null if not a worker thread
164 >     * Gets current worker thread, or null if not a worker thread.
165       */
166      static ForkJoinWorkerThread getWorker() {
167          Thread t = Thread.currentThread();
168 <        return ((t instanceof ForkJoinWorkerThread)?
169 <                (ForkJoinWorkerThread)t : null);
168 >        return ((t instanceof ForkJoinWorkerThread) ?
169 >                (ForkJoinWorkerThread) t : null);
170      }
171  
172      final boolean casStatus(int cmp, int val) {
173 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
173 >        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
174      }
175  
176      /**
# Line 170 | Line 178 | public abstract class ForkJoinTask<V> im
178       */
179      static void rethrowException(Throwable ex) {
180          if (ex != null)
181 <            _unsafe.throwException(ex);
181 >            UNSAFE.throwException(ex);
182      }
183  
184      // Setting completion status
185  
186      /**
187 <     * Mark completion and wake up threads waiting to join this task.
187 >     * Marks completion and wakes up threads waiting to join this task.
188 >     *
189       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
190       */
191      final void setCompletion(int completion) {
192          ForkJoinPool pool = getPool();
193          if (pool != null) {
194              int s; // Clear signal bits while setting completion status
195 <            do;while ((s = status) >= 0 && !casStatus(s, completion));
195 >            do {} while ((s = status) >= 0 && !casStatus(s, completion));
196  
197              if ((s & SIGNAL_MASK) != 0) {
198                  if ((s &= INTERNAL_SIGNAL_MASK) != 0)
199                      pool.updateRunningCount(s);
200 <                synchronized(this) { notifyAll(); }
200 >                synchronized (this) { notifyAll(); }
201              }
202          }
203          else
# Line 201 | Line 210 | public abstract class ForkJoinTask<V> im
210       */
211      private void externallySetCompletion(int completion) {
212          int s;
213 <        do;while ((s = status) >= 0 &&
214 <                  !casStatus(s, (s & SIGNAL_MASK) | completion));
215 <        synchronized(this) { notifyAll(); }
213 >        do {} while ((s = status) >= 0 &&
214 >                     !casStatus(s, (s & SIGNAL_MASK) | completion));
215 >        synchronized (this) { notifyAll(); }
216      }
217  
218      /**
219 <     * Sets status to indicate normal completion
219 >     * Sets status to indicate normal completion.
220       */
221      final void setNormalCompletion() {
222          // Try typical fast case -- single CAS, no signal, not already done.
223          // Manually expand casStatus to improve chances of inlining it
224 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
224 >        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
225              setCompletion(NORMAL);
226      }
227  
228      // internal waiting and notification
229  
230      /**
231 <     * Performs the actual monitor wait for awaitDone
231 >     * Performs the actual monitor wait for awaitDone.
232       */
233      private void doAwaitDone() {
234          // Minimize lock bias and in/de-flation effects by maximizing
235          // chances of waiting inside sync
236          try {
237              while (status >= 0)
238 <                synchronized(this) { if (status >= 0) wait(); }
238 >                synchronized (this) { if (status >= 0) wait(); }
239          } catch (InterruptedException ie) {
240              onInterruptedWait();
241          }
242      }
243  
244      /**
245 <     * Performs the actual monitor wait for awaitDone
245 >     * Performs the actual timed monitor wait for awaitDone.
246       */
247      private void doAwaitDone(long startTime, long nanos) {
248 <        synchronized(this) {
248 >        synchronized (this) {
249              try {
250                  while (status >= 0) {
251                      long nt = nanos - System.nanoTime() - startTime;
252                      if (nt <= 0)
253                          break;
254 <                    wait(nt / 1000000, (int)(nt % 1000000));
254 >                    wait(nt / 1000000, (int) (nt % 1000000));
255                  }
256              } catch (InterruptedException ie) {
257                  onInterruptedWait();
# Line 255 | Line 264 | public abstract class ForkJoinTask<V> im
264      /**
265       * Sets status to indicate there is joiner, then waits for join,
266       * surrounded with pool notifications.
267 +     *
268       * @return status upon exit
269       */
270 <    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
271 <        ForkJoinPool pool = w == null? null : w.pool;
270 >    private int awaitDone(ForkJoinWorkerThread w,
271 >                          boolean maintainParallelism) {
272 >        ForkJoinPool pool = (w == null) ? null : w.pool;
273          int s;
274          while ((s = status) >= 0) {
275 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
275 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
276                  if (pool == null || !pool.preJoin(this, maintainParallelism))
277                      doAwaitDone();
278                  if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
# Line 274 | Line 285 | public abstract class ForkJoinTask<V> im
285  
286      /**
287       * Timed version of awaitDone
288 +     *
289       * @return status upon exit
290       */
291      private int awaitDone(ForkJoinWorkerThread w, long nanos) {
292 <        ForkJoinPool pool = w == null? null : w.pool;
292 >        ForkJoinPool pool = (w == null) ? null : w.pool;
293          int s;
294          while ((s = status) >= 0) {
295 <            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
295 >            if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) {
296                  long startTime = System.nanoTime();
297                  if (pool == null || !pool.preJoin(this, false))
298                      doAwaitDone(startTime, nanos);
# Line 297 | Line 309 | public abstract class ForkJoinTask<V> im
309      }
310  
311      /**
312 <     * Notify pool that thread is unblocked. Called by signalled
312 >     * Notifies pool that thread is unblocked. Called by signalled
313       * threads when woken by non-FJ threads (which is atypical).
314       */
315      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
316          int s;
317 <        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
317 >        do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
318          if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
319              pool.updateRunningCount(s);
320      }
321  
322      /**
323 <     * Notify pool to adjust counts on cancelled or timed out wait
323 >     * Notifies pool to adjust counts on cancelled or timed out wait.
324       */
325      private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
326          if (pool != null) {
# Line 323 | Line 335 | public abstract class ForkJoinTask<V> im
335      }
336  
337      /**
338 <     * Handle interruptions during waits.
338 >     * Handles interruptions during waits.
339       */
340      private void onInterruptedWait() {
341          ForkJoinWorkerThread w = getWorker();
# Line 342 | Line 354 | public abstract class ForkJoinTask<V> im
354      }
355  
356      /**
357 <     * Throws the exception associated with status s;
357 >     * Throws the exception associated with status s.
358 >     *
359       * @throws the exception
360       */
361      private void reportException(int s) {
# Line 355 | Line 368 | public abstract class ForkJoinTask<V> im
368      }
369  
370      /**
371 <     * Returns result or throws exception using j.u.c.Future conventions
372 <     * Only call when isDone known to be true.
371 >     * Returns result or throws exception using j.u.c.Future conventions.
372 >     * Only call when {@code isDone} known to be true.
373       */
374      private V reportFutureResult()
375          throws ExecutionException, InterruptedException {
# Line 375 | Line 388 | public abstract class ForkJoinTask<V> im
388  
389      /**
390       * Returns result or throws exception using j.u.c.Future conventions
391 <     * with timeouts
391 >     * with timeouts.
392       */
393      private V reportTimedFutureResult()
394          throws InterruptedException, ExecutionException, TimeoutException {
# Line 396 | Line 409 | public abstract class ForkJoinTask<V> im
409  
410      /**
411       * Calls exec, recording completion, and rethrowing exception if
412 <     * encountered. Caller should normally check status before calling
412 >     * encountered. Caller should normally check status before calling.
413 >     *
414       * @return true if completed normally
415       */
416      private boolean tryExec() {
# Line 414 | Line 428 | public abstract class ForkJoinTask<V> im
428  
429      /**
430       * Main execution method used by worker threads. Invokes
431 <     * base computation unless already complete
431 >     * base computation unless already complete.
432       */
433      final void quietlyExec() {
434          if (status >= 0) {
435              try {
436                  if (!exec())
437                      return;
438 <            } catch(Throwable rex) {
438 >            } catch (Throwable rex) {
439                  setDoneExceptionally(rex);
440                  return;
441              }
# Line 430 | Line 444 | public abstract class ForkJoinTask<V> im
444      }
445  
446      /**
447 <     * Calls exec, recording but not rethrowing exception
448 <     * Caller should normally check status before calling
447 >     * Calls exec(), recording but not rethrowing exception.
448 >     * Caller should normally check status before calling.
449 >     *
450       * @return true if completed normally
451       */
452      private boolean tryQuietlyInvoke() {
# Line 447 | Line 462 | public abstract class ForkJoinTask<V> im
462      }
463  
464      /**
465 <     * Cancel, ignoring any exceptions it throws
465 >     * Cancels, ignoring any exceptions it throws.
466       */
467      final void cancelIgnoringExceptions() {
468          try {
469              cancel(false);
470 <        } catch(Throwable ignore) {
470 >        } catch (Throwable ignore) {
471          }
472      }
473  
# Line 464 | Line 479 | public abstract class ForkJoinTask<V> im
479          ForkJoinTask<?> t;
480          while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
481              t.quietlyExec();
482 <        return (s >= 0)? awaitDone(w, false) : s; // block if no work
482 >        return (s >= 0) ? awaitDone(w, false) : s; // block if no work
483      }
484  
485      // public methods
# Line 474 | Line 489 | public abstract class ForkJoinTask<V> im
489       * necessarily enforced, it is a usage error to fork a task more
490       * than once unless it has completed and been reinitialized.  This
491       * method may be invoked only from within ForkJoinTask
492 <     * computations. Attempts to invoke in other contexts result in
493 <     * exceptions or errors possibly including ClassCastException.
492 >     * computations (as may be determined using method {@link
493 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
494 >     * in exceptions or errors, possibly including ClassCastException.
495 >     *
496 >     * @return <code>this</code>, to simplify usage.
497       */
498 <    public final void fork() {
499 <        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
498 >    public final ForkJoinTask<V> fork() {
499 >        ((ForkJoinWorkerThread) Thread.currentThread())
500 >            .pushTask(this);
501 >        return this;
502      }
503  
504      /**
505       * Returns the result of the computation when it is ready.
506 <     * This method differs from <code>get</code> in that abnormal
506 >     * This method differs from {@code get} in that abnormal
507       * completion results in RuntimeExceptions or Errors, not
508       * ExecutionExceptions.
509       *
# Line 499 | Line 519 | public abstract class ForkJoinTask<V> im
519      /**
520       * Commences performing this task, awaits its completion if
521       * necessary, and return its result.
522 +     *
523       * @throws Throwable (a RuntimeException, Error, or unchecked
524 <     * exception) if the underlying computation did so.
524 >     * exception) if the underlying computation did so
525       * @return the computed result
526       */
527      public final V invoke() {
# Line 511 | Line 532 | public abstract class ForkJoinTask<V> im
532      }
533  
534      /**
535 <     * Forks both tasks, returning when <code>isDone</code> holds for
535 >     * Forks both tasks, returning when {@code isDone} holds for
536       * both of them or an exception is encountered. This method may be
537 <     * invoked only from within ForkJoinTask computations. Attempts to
538 <     * invoke in other contexts result in exceptions or errors
537 >     * invoked only from within ForkJoinTask computations (as may be
538 >     * determined using method {@link #inForkJoinPool}). Attempts to
539 >     * invoke in other contexts result in exceptions or errors,
540       * possibly including ClassCastException.
541 +     *
542       * @param t1 one task
543       * @param t2 the other task
544       * @throws NullPointerException if t1 or t2 are null
545 <     * @throws RuntimeException or Error if either task did so.
545 >     * @throws RuntimeException or Error if either task did so
546       */
547      public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
548          t2.fork();
# Line 528 | Line 551 | public abstract class ForkJoinTask<V> im
551      }
552  
553      /**
554 <     * Forks the given tasks, returning when <code>isDone</code> holds
554 >     * Forks the given tasks, returning when {@code isDone} holds
555       * for all of them. If any task encounters an exception, others
556       * may be cancelled.  This method may be invoked only from within
557 <     * ForkJoinTask computations. Attempts to invoke in other contexts
558 <     * result in exceptions or errors possibly including ClassCastException.
557 >     * ForkJoinTask computations (as may be determined using method
558 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
559 >     * result in exceptions or errors, possibly including
560 >     * ClassCastException.
561 >     *
562       * @param tasks the array of tasks
563 <     * @throws NullPointerException if tasks or any element are null.
564 <     * @throws RuntimeException or Error if any task did so.
563 >     * @throws NullPointerException if tasks or any element are null
564 >     * @throws RuntimeException or Error if any task did so
565       */
566      public static void invokeAll(ForkJoinTask<?>... tasks) {
567          Throwable ex = null;
# Line 572 | Line 598 | public abstract class ForkJoinTask<V> im
598  
599      /**
600       * Forks all tasks in the collection, returning when
601 <     * <code>isDone</code> holds for all of them. If any task
601 >     * {@code isDone} holds for all of them. If any task
602       * encounters an exception, others may be cancelled.  This method
603 <     * may be invoked only from within ForkJoinTask
604 <     * computations. Attempts to invoke in other contexts resul!t in
605 <     * exceptions or errors possibly including ClassCastException.
603 >     * may be invoked only from within ForkJoinTask computations (as
604 >     * may be determined using method {@link
605 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
606 >     * in exceptions or errors, possibly including ClassCastException.
607 >     *
608       * @param tasks the collection of tasks
609 <     * @throws NullPointerException if tasks or any element are null.
610 <     * @throws RuntimeException or Error if any task did so.
609 >     * @throws NullPointerException if tasks or any element are null
610 >     * @throws RuntimeException or Error if any task did so
611       */
612      public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
613 <        if (!(tasks instanceof List)) {
614 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
613 >        if (!(tasks instanceof List<?>)) {
614 >            invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
615              return;
616          }
617 +        @SuppressWarnings("unchecked")
618          List<? extends ForkJoinTask<?>> ts =
619 <            (List<? extends ForkJoinTask<?>>)tasks;
619 >            (List<? extends ForkJoinTask<?>>) tasks;
620          Throwable ex = null;
621          int last = ts.size() - 1;
622          for (int i = last; i >= 0; --i) {
# Line 623 | Line 652 | public abstract class ForkJoinTask<V> im
652      /**
653       * Returns true if the computation performed by this task has
654       * completed (or has been cancelled).
655 +     *
656       * @return true if this computation has completed
657       */
658      public final boolean isDone() {
# Line 631 | Line 661 | public abstract class ForkJoinTask<V> im
661  
662      /**
663       * Returns true if this task was cancelled.
664 +     *
665       * @return true if this task was cancelled
666       */
667      public final boolean isCancelled() {
# Line 639 | Line 670 | public abstract class ForkJoinTask<V> im
670  
671      /**
672       * Asserts that the results of this task's computation will not be
673 <     * used. If a cancellation occurs before atempting to execute this
674 <     * task, then execution will be suppressed, <code>isCancelled</code>
675 <     * will report true, and <code>join</code> will result in a
676 <     * <code>CancellationException</code> being thrown. Otherwise, when
673 >     * used. If a cancellation occurs before attempting to execute this
674 >     * task, then execution will be suppressed, {@code isCancelled}
675 >     * will report true, and {@code join} will result in a
676 >     * {@code CancellationException} being thrown. Otherwise, when
677       * cancellation races with completion, there are no guarantees
678 <     * about whether <code>isCancelled</code> will report true, whether
679 <     * <code>join</code> will return normally or via an exception, or
678 >     * about whether {@code isCancelled} will report true, whether
679 >     * {@code join} will return normally or via an exception, or
680       * whether these behaviors will remain consistent upon repeated
681       * invocation.
682       *
# Line 656 | Line 687 | public abstract class ForkJoinTask<V> im
687       * <p> This method is designed to be invoked by <em>other</em>
688       * tasks. To terminate the current task, you can just return or
689       * throw an unchecked exception from its computation method, or
690 <     * invoke <code>completeExceptionally</code>.
690 >     * invoke {@code completeExceptionally}.
691       *
692       * @param mayInterruptIfRunning this value is ignored in the
693       * default implementation because tasks are not in general
694 <     * cancelled via interruption.
694 >     * cancelled via interruption
695       *
696       * @return true if this task is now cancelled
697       */
# Line 670 | Line 701 | public abstract class ForkJoinTask<V> im
701      }
702  
703      /**
704 <     * Returns true if this task threw an exception or was cancelled
704 >     * Returns true if this task threw an exception or was cancelled.
705 >     *
706       * @return true if this task threw an exception or was cancelled
707       */
708      public final boolean isCompletedAbnormally() {
# Line 681 | Line 713 | public abstract class ForkJoinTask<V> im
713       * Returns the exception thrown by the base computation, or a
714       * CancellationException if cancelled, or null if none or if the
715       * method has not yet completed.
716 +     *
717       * @return the exception, or null if none
718       */
719      public final Throwable getException() {
# Line 695 | Line 728 | public abstract class ForkJoinTask<V> im
728      /**
729       * Completes this task abnormally, and if not already aborted or
730       * cancelled, causes it to throw the given exception upon
731 <     * <code>join</code> and related operations. This method may be used
731 >     * {@code join} and related operations. This method may be used
732       * to induce exceptions in asynchronous tasks, or to force
733       * completion of tasks that would not otherwise complete.  Its use
734       * in other situations is likely to be wrong.  This method is
735 <     * overridable, but overridden versions must invoke <code>super</code>
735 >     * overridable, but overridden versions must invoke {@code super}
736       * implementation to maintain guarantees.
737       *
738       * @param ex the exception to throw. If this exception is
# Line 708 | Line 741 | public abstract class ForkJoinTask<V> im
741       */
742      public void completeExceptionally(Throwable ex) {
743          setDoneExceptionally((ex instanceof RuntimeException) ||
744 <                             (ex instanceof Error)? ex :
744 >                             (ex instanceof Error) ? ex :
745                               new RuntimeException(ex));
746      }
747  
748      /**
749       * Completes this task, and if not already aborted or cancelled,
750 <     * returning a <code>null</code> result upon <code>join</code> and related
750 >     * returning a {@code null} result upon {@code join} and related
751       * operations. This method may be used to provide results for
752       * asynchronous tasks, or to provide alternative handling for
753       * tasks that would not otherwise complete normally. Its use in
754       * other situations is likely to be wrong. This method is
755 <     * overridable, but overridden versions must invoke <code>super</code>
755 >     * overridable, but overridden versions must invoke {@code super}
756       * implementation to maintain guarantees.
757       *
758 <     * @param value the result value for this task.
758 >     * @param value the result value for this task
759       */
760      public void complete(V value) {
761          try {
762              setRawResult(value);
763 <        } catch(Throwable rex) {
763 >        } catch (Throwable rex) {
764              setDoneExceptionally(rex);
765              return;
766          }
# Line 752 | Line 785 | public abstract class ForkJoinTask<V> im
785      /**
786       * Possibly executes other tasks until this task is ready, then
787       * returns the result of the computation.  This method may be more
788 <     * efficient than <code>join</code>, but is only applicable when
789 <     * there are no potemtial dependencies between continuation of the
788 >     * efficient than {@code join}, but is only applicable when
789 >     * there are no potential dependencies between continuation of the
790       * current task and that of any other task that might be executed
791       * while helping. (This usually holds for pure divide-and-conquer
792       * tasks). This method may be invoked only from within
793 <     * ForkJoinTask computations. Attempts to invoke in other contexts
794 <     * resul!t in exceptions or errors possibly including ClassCastException.
793 >     * ForkJoinTask computations (as may be determined using method
794 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
795 >     * result in exceptions or errors, possibly including
796 >     * ClassCastException.
797 >     *
798       * @return the computed result
799       */
800      public final V helpJoin() {
801 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
801 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
802          if (status < 0 || !w.unpushTask(this) || !tryExec())
803              reportException(busyJoin(w));
804          return getRawResult();
# Line 771 | Line 807 | public abstract class ForkJoinTask<V> im
807      /**
808       * Possibly executes other tasks until this task is ready.  This
809       * method may be invoked only from within ForkJoinTask
810 <     * computations. Attempts to invoke in other contexts resul!t in
811 <     * exceptions or errors possibly including ClassCastException.
810 >     * computations (as may be determined using method {@link
811 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
812 >     * in exceptions or errors, possibly including ClassCastException.
813       */
814      public final void quietlyHelpJoin() {
815          if (status >= 0) {
816              ForkJoinWorkerThread w =
817 <                (ForkJoinWorkerThread)(Thread.currentThread());
817 >                (ForkJoinWorkerThread) Thread.currentThread();
818              if (!w.unpushTask(this) || !tryQuietlyInvoke())
819                  busyJoin(w);
820          }
# Line 816 | Line 853 | public abstract class ForkJoinTask<V> im
853       * joined, instead executing them until all are processed.
854       */
855      public static void helpQuiesce() {
856 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
857 <            helpQuiescePool();
856 >        ((ForkJoinWorkerThread) Thread.currentThread())
857 >            .helpQuiescePool();
858      }
859  
860      /**
861       * Resets the internal bookkeeping state of this task, allowing a
862 <     * subsequent <code>fork</code>. This method allows repeated reuse of
862 >     * subsequent {@code fork}. This method allows repeated reuse of
863       * this task, but only if reuse occurs when this task has either
864       * never been forked, or has been forked, then completed and all
865       * outstanding joins of this task have also completed. Effects
# Line 838 | Line 875 | public abstract class ForkJoinTask<V> im
875  
876      /**
877       * Returns the pool hosting the current task execution, or null
878 <     * if this task is executing outside of any pool.
879 <     * @return the pool, or null if none.
878 >     * if this task is executing outside of any ForkJoinPool.
879 >     *
880 >     * @return the pool, or null if none
881       */
882      public static ForkJoinPool getPool() {
883          Thread t = Thread.currentThread();
884 <        return ((t instanceof ForkJoinWorkerThread)?
885 <                ((ForkJoinWorkerThread)t).pool : null);
884 >        return (t instanceof ForkJoinWorkerThread) ?
885 >            ((ForkJoinWorkerThread) t).pool : null;
886 >    }
887 >
888 >    /**
889 >     * Returns {@code true} if the current thread is executing as a
890 >     * ForkJoinPool computation.
891 >     *
892 >     * @return {@code true} if the current thread is executing as a
893 >     * ForkJoinPool computation, or false otherwise
894 >     */
895 >    public static boolean inForkJoinPool() {
896 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
897      }
898  
899      /**
# Line 854 | Line 903 | public abstract class ForkJoinTask<V> im
903       * another thread.  This method may be useful when arranging
904       * alternative local processing of tasks that could have been, but
905       * were not, stolen. This method may be invoked only from within
906 <     * ForkJoinTask computations. Attempts to invoke in other contexts
907 <     * result in exceptions or errors possibly including ClassCastException.
906 >     * ForkJoinTask computations (as may be determined using method
907 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
908 >     * result in exceptions or errors, possibly including
909 >     * ClassCastException.
910 >     *
911       * @return true if unforked
912       */
913      public boolean tryUnfork() {
914 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
914 >        return ((ForkJoinWorkerThread) Thread.currentThread())
915 >            .unpushTask(this);
916      }
917  
918      /**
# Line 867 | Line 920 | public abstract class ForkJoinTask<V> im
920       * forked by the current worker thread but not yet executed. This
921       * value may be useful for heuristic decisions about whether to
922       * fork other tasks.
923 +     *
924       * @return the number of tasks
925       */
926      public static int getQueuedTaskCount() {
927 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
928 <            getQueueSize();
927 >        return ((ForkJoinWorkerThread) Thread.currentThread())
928 >            .getQueueSize();
929      }
930  
931      /**
932 <     * Returns a estimate of how many more locally queued tasks are
932 >     * Returns an estimate of how many more locally queued tasks are
933       * held by the current worker thread than there are other worker
934       * threads that might steal them.  This value may be useful for
935       * heuristic decisions about whether to fork other tasks. In many
# Line 883 | Line 937 | public abstract class ForkJoinTask<V> im
937       * aim to maintain a small constant surplus (for example, 3) of
938       * tasks, and to process computations locally if this threshold is
939       * exceeded.
940 +     *
941       * @return the surplus number of tasks, which may be negative
942       */
943      public static int getSurplusQueuedTaskCount() {
944 <        return ((ForkJoinWorkerThread)(Thread.currentThread()))
944 >        return ((ForkJoinWorkerThread) Thread.currentThread())
945              .getEstimatedSurplusTaskCount();
946      }
947  
948      // Extension methods
949  
950      /**
951 <     * Returns the result that would be returned by <code>join</code>,
951 >     * Returns the result that would be returned by {@code join},
952       * even if this task completed abnormally, or null if this task is
953       * not known to have been completed.  This method is designed to
954       * aid debugging, as well as to support extensions. Its use in any
955       * other context is discouraged.
956       *
957 <     * @return the result, or null if not completed.
957 >     * @return the result, or null if not completed
958       */
959      public abstract V getRawResult();
960  
# Line 918 | Line 973 | public abstract class ForkJoinTask<V> im
973       * called otherwise. The return value controls whether this task
974       * is considered to be done normally. It may return false in
975       * asynchronous actions that require explicit invocations of
976 <     * <code>complete</code> to become joinable. It may throw exceptions
976 >     * {@code complete} to become joinable. It may throw exceptions
977       * to indicate abnormal exit.
978 +     *
979       * @return true if completed normally
980       * @throws Error or RuntimeException if encountered during computation
981       */
# Line 932 | Line 988 | public abstract class ForkJoinTask<V> im
988       * be polled or executed next.  This method is designed primarily
989       * to support extensions, and is unlikely to be useful otherwise.
990       * This method may be invoked only from within ForkJoinTask
991 <     * computations. Attempts to invoke in other contexts result in
992 <     * exceptions or errors possibly including ClassCastException.
991 >     * computations (as may be determined using method {@link
992 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
993 >     * in exceptions or errors, possibly including ClassCastException.
994       *
995       * @return the next task, or null if none are available
996       */
997      protected static ForkJoinTask<?> peekNextLocalTask() {
998 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
998 >        return ((ForkJoinWorkerThread) Thread.currentThread())
999 >            .peekTask();
1000      }
1001  
1002      /**
# Line 946 | Line 1004 | public abstract class ForkJoinTask<V> im
1004       * queued by the current thread but not yet executed.  This method
1005       * is designed primarily to support extensions, and is unlikely to
1006       * be useful otherwise.  This method may be invoked only from
1007 <     * within ForkJoinTask computations. Attempts to invoke in other
1008 <     * contexts result in exceptions or errors possibly including
1007 >     * within ForkJoinTask computations (as may be determined using
1008 >     * method {@link #inForkJoinPool}). Attempts to invoke in other
1009 >     * contexts result in exceptions or errors, possibly including
1010       * ClassCastException.
1011       *
1012       * @return the next task, or null if none are available
1013       */
1014      protected static ForkJoinTask<?> pollNextLocalTask() {
1015 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
1015 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1016 >            .pollLocalTask();
1017      }
1018  
1019      /**
# Line 961 | Line 1021 | public abstract class ForkJoinTask<V> im
1021       * queued by the current thread but not yet executed, if one is
1022       * available, or if not available, a task that was forked by some
1023       * other thread, if available. Availability may be transient, so a
1024 <     * <code>null</code> result does not necessarily imply quiecence
1024 >     * {@code null} result does not necessarily imply quiescence
1025       * of the pool this task is operating in.  This method is designed
1026       * primarily to support extensions, and is unlikely to be useful
1027       * otherwise.  This method may be invoked only from within
1028 <     * ForkJoinTask computations. Attempts to invoke in other contexts
1029 <     * result in exceptions or errors possibly including
1028 >     * ForkJoinTask computations (as may be determined using method
1029 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1030 >     * result in exceptions or errors, possibly including
1031       * ClassCastException.
1032       *
1033       * @return a task, or null if none are available
1034       */
1035      protected static ForkJoinTask<?> pollTask() {
1036 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1037 <            pollTask();
1036 >        return ((ForkJoinWorkerThread) Thread.currentThread())
1037 >            .pollTask();
1038 >    }
1039 >
1040 >    // adaptors
1041 >
1042 >    /**
1043 >     * Returns a new ForkJoinTask that performs the <code>run</code>
1044 >     * method of the given Runnable as its action, and returns a null
1045 >     * result upon <code>join</code>.
1046 >     *
1047 >     * @param runnable the runnable action
1048 >     * @return the task
1049 >     */
1050 >    public static ForkJoinTask<Void> adapt(Runnable runnable) {
1051 >        return new ForkJoinPool.AdaptedRunnable<Void>(runnable, null);
1052 >    }
1053 >
1054 >    /**
1055 >     * Returns a new ForkJoinTask that performs the <code>run</code>
1056 >     * method of the given Runnable as its action, and returns the
1057 >     * given result upon <code>join</code>.
1058 >     *
1059 >     * @param runnable the runnable action
1060 >     * @param result the result upon completion
1061 >     * @return the task
1062 >     */
1063 >    public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1064 >        return new ForkJoinPool.AdaptedRunnable<T>(runnable, result);
1065 >    }
1066 >
1067 >    /**
1068 >     * Returns a new ForkJoinTask that performs the <code>call</code>
1069 >     * method of the given Callable as its action, and returns its
1070 >     * result upon <code>join</code>, translating any checked
1071 >     * exceptions encountered into <code>RuntimeException<code>.
1072 >     *
1073 >     * @param callable the callable action
1074 >     * @return the task
1075 >     */
1076 >    public static <T> ForkJoinTask<T> adapt(Callable<T> callable) {
1077 >        return new ForkJoinPool.AdaptedCallable<T>(callable);
1078      }
1079  
1080      // Serialization support
# Line 984 | Line 1085 | public abstract class ForkJoinTask<V> im
1085       * Save the state to a stream.
1086       *
1087       * @serialData the current run status and the exception thrown
1088 <     * during execution, or null if none.
1088 >     * during execution, or null if none
1089       * @param s the stream
1090       */
1091      private void writeObject(java.io.ObjectOutputStream s)
# Line 995 | Line 1096 | public abstract class ForkJoinTask<V> im
1096  
1097      /**
1098       * Reconstitute the instance from a stream.
1099 +     *
1100       * @param s the stream
1101       */
1102      private void readObject(java.io.ObjectInputStream s)
# Line 1004 | Line 1106 | public abstract class ForkJoinTask<V> im
1106          status |= EXTERNAL_SIGNAL; // conservatively set external signal
1107          Object ex = s.readObject();
1108          if (ex != null)
1109 <            setDoneExceptionally((Throwable)ex);
1109 >            setDoneExceptionally((Throwable) ex);
1110      }
1111  
1112 <    // Temporary Unsafe mechanics for preliminary release
1113 <    private static Unsafe getUnsafe() throws Throwable {
1112 >    // Unsafe mechanics for jsr166y 3rd party package.
1113 >    private static sun.misc.Unsafe getUnsafe() {
1114          try {
1115 <            return Unsafe.getUnsafe();
1115 >            return sun.misc.Unsafe.getUnsafe();
1116          } catch (SecurityException se) {
1117              try {
1118                  return java.security.AccessController.doPrivileged
1119 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1120 <                        public Unsafe run() throws Exception {
1121 <                            return getUnsafePrivileged();
1119 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1120 >                        public sun.misc.Unsafe run() throws Exception {
1121 >                            return getUnsafeByReflection();
1122                          }});
1123              } catch (java.security.PrivilegedActionException e) {
1124 <                throw e.getCause();
1124 >                throw new RuntimeException("Could not initialize intrinsics",
1125 >                                           e.getCause());
1126              }
1127          }
1128      }
1129  
1130 <    private static Unsafe getUnsafePrivileged()
1130 >    private static sun.misc.Unsafe getUnsafeByReflection()
1131              throws NoSuchFieldException, IllegalAccessException {
1132 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1132 >        java.lang.reflect.Field f =
1133 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1134          f.setAccessible(true);
1135 <        return (Unsafe) f.get(null);
1135 >        return (sun.misc.Unsafe) f.get(null);
1136      }
1137  
1138 <    private static long fieldOffset(String fieldName)
1035 <            throws NoSuchFieldException {
1036 <        return _unsafe.objectFieldOffset
1037 <            (ForkJoinTask.class.getDeclaredField(fieldName));
1038 <    }
1039 <
1040 <    static final Unsafe _unsafe;
1041 <    static final long statusOffset;
1042 <
1043 <    static {
1138 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
1139          try {
1140 <            _unsafe = getUnsafe();
1141 <            statusOffset = fieldOffset("status");
1142 <        } catch (Throwable e) {
1143 <            throw new RuntimeException("Could not initialize intrinsics", e);
1140 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1141 >        } catch (NoSuchFieldException e) {
1142 >            // Convert Exception to Error
1143 >            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1144 >            error.initCause(e);
1145 >            throw error;
1146          }
1147      }
1148  
1149 +    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1150 +    static final long statusOffset =
1151 +        fieldOffset("status", ForkJoinTask.class);
1152 +
1153   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines