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.57 by dl, Sat Sep 4 11:33:53 2010 UTC vs.
Revision 1.71 by dl, Tue Nov 23 10:51:18 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
10
9   import java.io.Serializable;
10   import java.util.Collection;
11   import java.util.Collections;
# Line 15 | Line 13 | import java.util.List;
13   import java.util.RandomAccess;
14   import java.util.Map;
15   import java.util.WeakHashMap;
16 + import java.util.concurrent.Callable;
17 + import java.util.concurrent.CancellationException;
18 + import java.util.concurrent.ExecutionException;
19 + import java.util.concurrent.Executor;
20 + import java.util.concurrent.ExecutorService;
21 + import java.util.concurrent.Future;
22 + import java.util.concurrent.RejectedExecutionException;
23 + import java.util.concurrent.RunnableFuture;
24 + import java.util.concurrent.TimeUnit;
25 + import java.util.concurrent.TimeoutException;
26  
27   /**
28   * Abstract base class for tasks that run within a {@link ForkJoinPool}.
# Line 28 | Line 36 | import java.util.WeakHashMap;
36   * start other subtasks.  As indicated by the name of this class,
37   * many programs using {@code ForkJoinTask} employ only methods
38   * {@link #fork} and {@link #join}, or derivatives such as {@link
39 < * #invokeAll}.  However, this class also provides a number of other
40 < * methods that can come into play in advanced usages, as well as
41 < * extension mechanics that allow support of new forms of fork/join
42 < * processing.
39 > * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
40 > * provides a number of other methods that can come into play in
41 > * advanced usages, as well as extension mechanics that allow
42 > * support of new forms of fork/join processing.
43   *
44   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
45   * The efficiency of {@code ForkJoinTask}s stems from a set of
# Line 102 | Line 110 | import java.util.WeakHashMap;
110   * result in exceptions or errors, possibly including
111   * {@code ClassCastException}.
112   *
113 + * <p>Method {@link #join} and its variants are appropriate for use
114 + * only when completion dependencies are acyclic; that is, the
115 + * parallel computation can be described as a directed acyclic graph
116 + * (DAG). Otherwise, executions may encounter a form of deadlock as
117 + * tasks cyclically wait for each other.  However, this framework
118 + * supports other methods and techniques (for example the use of
119 + * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
120 + * may be of use in constructing custom subclasses for problems that
121 + * are not statically structured as DAGs.
122 + *
123   * <p>Most base support methods are {@code final}, to prevent
124   * overriding of implementations that are intrinsically tied to the
125   * underlying lightweight task scheduling framework.  Developers
# Line 116 | Line 134 | import java.util.WeakHashMap;
134   * computation. Large tasks should be split into smaller subtasks,
135   * usually via recursive decomposition. As a very rough rule of thumb,
136   * a task should perform more than 100 and less than 10000 basic
137 < * computational steps. If tasks are too big, then parallelism cannot
138 < * improve throughput. If too small, then memory and internal task
139 < * maintenance overhead may overwhelm processing.
137 > * computational steps, and should avoid indefinite looping. If tasks
138 > * are too big, then parallelism cannot improve throughput. If too
139 > * small, then memory and internal task maintenance overhead may
140 > * overwhelm processing.
141   *
142   * <p>This class provides {@code adapt} methods for {@link Runnable}
143   * and {@link Callable}, that may be of use when mixing execution of
# Line 153 | Line 172 | public abstract class ForkJoinTask<V> im
172       * single int to minimize footprint and to ensure atomicity (via
173       * CAS).  Status is initially zero, and takes on nonnegative
174       * values until completed, upon which status holds value
175 <     * NORMAL. CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
175 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
176       * waits by other threads have the SIGNAL bit set.  Completion of
177       * a stolen task with SIGNAL set awakens any waiters via
178       * notifyAll. Even though suboptimal for some purposes, we use
# Line 206 | Line 225 | public abstract class ForkJoinTask<V> im
225  
226      /**
227       * Records exception and sets exceptional completion.
228 <     *
228 >     *
229       * @return status on exit
230       */
231      private void setExceptionalCompletion(Throwable rex) {
# Line 215 | Line 234 | public abstract class ForkJoinTask<V> im
234      }
235  
236      /**
237 <     * Blocks a worker thread until completion. Called only by
238 <     * pool. Currently unused -- pool-based waits use timeout
220 <     * version below.
237 >     * Blocks a worker thread until completed or timed out.  Called
238 >     * only by pool.
239       */
240 <    final void internalAwaitDone() {
241 <        int s;         // the odd construction reduces lock bias effects
242 <        while ((s = status) >= 0) {
243 <            try {
244 <                synchronized(this) {
245 <                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
246 <                        wait();
240 >    final void internalAwaitDone(long millis, int nanos) {
241 >        if (status >= 0) {
242 >            try {     // the odd construction reduces lock bias effects
243 >                synchronized (this) {
244 >                    if (status > 0 ||
245 >                        UNSAFE.compareAndSwapInt(this, statusOffset,
246 >                                                 0, SIGNAL))
247 >                        wait(millis, nanos);
248                  }
249              } catch (InterruptedException ie) {
250                  cancelIfTerminating();
# Line 234 | Line 253 | public abstract class ForkJoinTask<V> im
253      }
254  
255      /**
256 <     * Blocks a worker thread until completed or timed out.  Called
238 <     * only by pool.
239 <     *
240 <     * @return status on exit
256 >     * Blocks a non-worker-thread until completion.
257       */
258 <    final int internalAwaitDone(long millis) {
259 <        int s;
260 <        if ((s = status) >= 0) {
261 <            try {
262 <                synchronized(this) {
263 <                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
264 <                        wait(millis, 0);
258 >    private void externalAwaitDone() {
259 >        if (status >= 0) {
260 >            boolean interrupted = false;
261 >            synchronized(this) {
262 >                int s;
263 >                while ((s = status) >= 0) {
264 >                    if (s == 0 &&
265 >                        !UNSAFE.compareAndSwapInt(this, statusOffset,
266 >                                                  0, SIGNAL))
267 >                        continue;
268 >                    try {
269 >                        wait();
270 >                    } catch (InterruptedException ie) {
271 >                        interrupted = true;
272 >                    }
273                  }
250            } catch (InterruptedException ie) {
251                cancelIfTerminating();
274              }
275 <            s = status;
275 >            if (interrupted)
276 >                Thread.currentThread().interrupt();
277          }
255        return s;
278      }
279  
280      /**
281 <     * Blocks a non-worker-thread until completion.
281 >     * Blocks a non-worker-thread until completion or interruption or timeout.
282       */
283 <    private void externalAwaitDone() {
284 <        int s;
285 <        while ((s = status) >= 0) {
283 >    private void externalInterruptibleAwaitDone(boolean timed, long nanos)
284 >        throws InterruptedException {
285 >        if (Thread.interrupted())
286 >            throw new InterruptedException();
287 >        if (status >= 0) {
288 >            long startTime = timed ? System.nanoTime() : 0L;
289              synchronized(this) {
290 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
291 <                    boolean interrupted = false;
292 <                    while (status >= 0) {
293 <                        try {
294 <                            wait();
295 <                        } catch (InterruptedException ie) {
296 <                            interrupted = true;
297 <                        }
298 <                    }
299 <                    if (interrupted)
300 <                        Thread.currentThread().interrupt();
301 <                    break;
290 >                int s;
291 >                while ((s = status) >= 0) {
292 >                    long nt;
293 >                    if (s == 0 &&
294 >                        !UNSAFE.compareAndSwapInt(this, statusOffset,
295 >                                                  0, SIGNAL))
296 >                        continue;
297 >                    else if (!timed)
298 >                        wait();
299 >                    else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
300 >                        wait(nt / 1000000, (int)(nt % 1000000));
301 >                    else
302 >                        break;
303                  }
304              }
305          }
# Line 308 | Line 334 | public abstract class ForkJoinTask<V> im
334       * #isDone} returning {@code true}.
335       *
336       * <p>This method may be invoked only from within {@code
337 <     * ForkJoinTask} computations (as may be determined using method
337 >     * ForkJoinPool} computations (as may be determined using method
338       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
339       * result in exceptions or errors, possibly including {@code
340       * ClassCastException}.
# Line 322 | Line 348 | public abstract class ForkJoinTask<V> im
348      }
349  
350      /**
351 <     * Returns the result of the computation when it {@link #isDone is done}.
352 <     * This method differs from {@link #get()} in that
351 >     * Returns the result of the computation when it {@link #isDone is
352 >     * done}.  This method differs from {@link #get()} in that
353       * abnormal completion results in {@code RuntimeException} or
354 <     * {@code Error}, not {@code ExecutionException}.
354 >     * {@code Error}, not {@code ExecutionException}, and that
355 >     * interrupts of the calling thread do <em>not</em> cause the
356 >     * method to abruptly return by throwing {@code
357 >     * InterruptedException}.
358       *
359       * @return the computed result
360       */
# Line 367 | Line 396 | public abstract class ForkJoinTask<V> im
396       * unprocessed.
397       *
398       * <p>This method may be invoked only from within {@code
399 <     * ForkJoinTask} computations (as may be determined using method
399 >     * ForkJoinPool} computations (as may be determined using method
400       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
401       * result in exceptions or errors, possibly including {@code
402       * ClassCastException}.
# Line 395 | Line 424 | public abstract class ForkJoinTask<V> im
424       * normally or exceptionally, or left unprocessed.
425       *
426       * <p>This method may be invoked only from within {@code
427 <     * ForkJoinTask} computations (as may be determined using method
427 >     * ForkJoinPool} computations (as may be determined using method
428       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
429       * result in exceptions or errors, possibly including {@code
430       * ClassCastException}.
# Line 450 | Line 479 | public abstract class ForkJoinTask<V> im
479       * unprocessed.
480       *
481       * <p>This method may be invoked only from within {@code
482 <     * ForkJoinTask} computations (as may be determined using method
482 >     * ForkJoinPool} computations (as may be determined using method
483       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
484       * result in exceptions or errors, possibly including {@code
485       * ClassCastException}.
# Line 502 | Line 531 | public abstract class ForkJoinTask<V> im
531  
532      /**
533       * Attempts to cancel execution of this task. This attempt will
534 <     * fail if the task has already completed, has already been
535 <     * cancelled, or could not be cancelled for some other reason. If
536 <     * successful, and this task has not started when cancel is
537 <     * called, execution of this task is suppressed, {@link
538 <     * #isCancelled} will report true, and {@link #join} will result
539 <     * in a {@code CancellationException} being thrown.
534 >     * fail if the task has already completed or could not be
535 >     * cancelled for some other reason. If successful, and this task
536 >     * has not started when {@code cancel} is called, execution of
537 >     * this task is suppressed. After this method returns
538 >     * successfully, unless there is an intervening call to {@link
539 >     * #reinitialize}, subsequent calls to {@link #isCancelled},
540 >     * {@link #isDone}, and {@code cancel} will return {@code true}
541 >     * and calls to {@link #join} and related methods will result in
542 >     * {@code CancellationException}.
543       *
544       * <p>This method may be overridden in subclasses, but if so, must
545 <     * still ensure that these minimal properties hold. In particular,
546 <     * the {@code cancel} method itself must not throw exceptions.
545 >     * still ensure that these properties hold. In particular, the
546 >     * {@code cancel} method itself must not throw exceptions.
547       *
548       * <p>This method is designed to be invoked by <em>other</em>
549       * tasks. To terminate the current task, you can just return or
550       * throw an unchecked exception from its computation method, or
551       * invoke {@link #completeExceptionally}.
552       *
553 <     * @param mayInterruptIfRunning this value is ignored in the
554 <     * default implementation because tasks are not
555 <     * cancelled via interruption
553 >     * @param mayInterruptIfRunning this value has no effect in the
554 >     * default implementation because interrupts are not used to
555 >     * control cancellation.
556       *
557       * @return {@code true} if this task is now cancelled
558       */
# Line 621 | Line 653 | public abstract class ForkJoinTask<V> im
653  
654      /**
655       * Completes this task, and if not already aborted or cancelled,
656 <     * returning a {@code null} result upon {@code join} and related
657 <     * operations. This method may be used to provide results for
658 <     * asynchronous tasks, or to provide alternative handling for
659 <     * tasks that would not otherwise complete normally. Its use in
660 <     * other situations is discouraged. This method is
661 <     * overridable, but overridden versions must invoke {@code super}
662 <     * implementation to maintain guarantees.
656 >     * returning the given value as the result of subsequent
657 >     * invocations of {@code join} and related operations. This method
658 >     * may be used to provide results for asynchronous tasks, or to
659 >     * provide alternative handling for tasks that would not otherwise
660 >     * complete normally. Its use in other situations is
661 >     * discouraged. This method is overridable, but overridden
662 >     * versions must invoke {@code super} implementation to maintain
663 >     * guarantees.
664       *
665       * @param value the result value for this task
666       */
# Line 641 | Line 674 | public abstract class ForkJoinTask<V> im
674          setCompletion(NORMAL);
675      }
676  
677 +    /**
678 +     * Waits if necessary for the computation to complete, and then
679 +     * retrieves its result.
680 +     *
681 +     * @return the computed result
682 +     * @throws CancellationException if the computation was cancelled
683 +     * @throws ExecutionException if the computation threw an
684 +     * exception
685 +     * @throws InterruptedException if the current thread is not a
686 +     * member of a ForkJoinPool and was interrupted while waiting
687 +     */
688      public final V get() throws InterruptedException, ExecutionException {
689 <        quietlyJoin();
690 <        if (Thread.interrupted())
691 <            throw new InterruptedException();
689 >        Thread t = Thread.currentThread();
690 >        if (t instanceof ForkJoinWorkerThread)
691 >            quietlyJoin();
692 >        else
693 >            externalInterruptibleAwaitDone(false, 0L);
694          int s = status;
695 <        if (s < NORMAL) {
695 >        if (s != NORMAL) {
696              Throwable ex;
697              if (s == CANCELLED)
698                  throw new CancellationException();
# Line 656 | Line 702 | public abstract class ForkJoinTask<V> im
702          return getRawResult();
703      }
704  
705 +    /**
706 +     * Waits if necessary for at most the given time for the computation
707 +     * to complete, and then retrieves its result, if available.
708 +     *
709 +     * @param timeout the maximum time to wait
710 +     * @param unit the time unit of the timeout argument
711 +     * @return the computed result
712 +     * @throws CancellationException if the computation was cancelled
713 +     * @throws ExecutionException if the computation threw an
714 +     * exception
715 +     * @throws InterruptedException if the current thread is not a
716 +     * member of a ForkJoinPool and was interrupted while waiting
717 +     * @throws TimeoutException if the wait timed out
718 +     */
719      public final V get(long timeout, TimeUnit unit)
720          throws InterruptedException, ExecutionException, TimeoutException {
721 +        long nanos = unit.toNanos(timeout);
722          Thread t = Thread.currentThread();
723 <        ForkJoinPool pool;
724 <        if (t instanceof ForkJoinWorkerThread) {
664 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
665 <            if (status >= 0 && w.unpushTask(this))
666 <                quietlyExec();
667 <            pool = w.pool;
668 <        }
723 >        if (t instanceof ForkJoinWorkerThread)
724 >            ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
725          else
726 <            pool = null;
727 <        /*
728 <         * Timed wait loop intermixes cases for FJ (pool != null) and
673 <         * non FJ threads. For FJ, decrement pool count but don't try
674 <         * for replacement; increment count on completion. For non-FJ,
675 <         * deal with interrupts. This is messy, but a little less so
676 <         * than is splitting the FJ and nonFJ cases.
677 <         */
678 <        boolean interrupted = false;
679 <        boolean dec = false; // true if pool count decremented
680 <        long nanos = unit.toNanos(timeout);
681 <        for (;;) {
682 <            if (Thread.interrupted() && pool == null) {
683 <                interrupted = true;
684 <                break;
685 <            }
686 <            int s = status;
687 <            if (s < 0)
688 <                break;
689 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
690 <                long startTime = System.nanoTime();
691 <                long nt; // wait time
692 <                while (status >= 0 &&
693 <                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
694 <                    if (pool != null && !dec)
695 <                        dec = pool.tryDecrementRunningCount();
696 <                    else {
697 <                        long ms = nt / 1000000;
698 <                        int ns = (int) (nt % 1000000);
699 <                        try {
700 <                            synchronized(this) {
701 <                                if (status >= 0)
702 <                                    wait(ms, ns);
703 <                            }
704 <                        } catch (InterruptedException ie) {
705 <                            if (pool != null)
706 <                                cancelIfTerminating();
707 <                            else {
708 <                                interrupted = true;
709 <                                break;
710 <                            }
711 <                        }
712 <                    }
713 <                }
714 <                break;
715 <            }
716 <        }
717 <        if (pool != null && dec)
718 <            pool.incrementRunningCount();
719 <        if (interrupted)
720 <            throw new InterruptedException();
721 <        int es = status;
722 <        if (es != NORMAL) {
726 >            externalInterruptibleAwaitDone(true, nanos);
727 >        int s = status;
728 >        if (s != NORMAL) {
729              Throwable ex;
730 <            if (es == CANCELLED)
730 >            if (s == CANCELLED)
731                  throw new CancellationException();
732 <            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
732 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
733                  throw new ExecutionException(ex);
734              throw new TimeoutException();
735          }
# Line 754 | Line 760 | public abstract class ForkJoinTask<V> im
760                          return;
761                      }
762                  }
763 <                w.joinTask(this);
763 >                w.joinTask(this, false, 0L);
764              }
765          }
766          else
# Line 764 | Line 770 | public abstract class ForkJoinTask<V> im
770      /**
771       * Commences performing this task and awaits its completion if
772       * necessary, without returning its result or throwing its
773 <     * exception. This method may be useful when processing
768 <     * collections of tasks when some have been cancelled or otherwise
769 <     * known to have aborted.
773 >     * exception.
774       */
775      public final void quietlyInvoke() {
776          if (status >= 0) {
# Line 792 | Line 796 | public abstract class ForkJoinTask<V> im
796       * processed.
797       *
798       * <p>This method may be invoked only from within {@code
799 <     * ForkJoinTask} computations (as may be determined using method
799 >     * ForkJoinPool} computations (as may be determined using method
800       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
801       * result in exceptions or errors, possibly including {@code
802       * ClassCastException}.
# Line 811 | Line 815 | public abstract class ForkJoinTask<V> im
815       * under any other usage conditions are not guaranteed.
816       * This method may be useful when executing
817       * pre-constructed trees of subtasks in loops.
818 +     *
819 +     * <p>Upon completion of this method, {@code isDone()} reports
820 +     * {@code false}, and {@code getException()} reports {@code
821 +     * null}. However, the value returned by {@code getRawResult} is
822 +     * unaffected. To clear this value, you can invoke {@code
823 +     * setRawResult(null)}.
824       */
825      public void reinitialize() {
826          if (status == EXCEPTIONAL)
# Line 832 | Line 842 | public abstract class ForkJoinTask<V> im
842      }
843  
844      /**
845 <     * Returns {@code true} if the current thread is executing as a
846 <     * ForkJoinPool computation.
845 >     * Returns {@code true} if the current thread is a {@link
846 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
847       *
848 <     * @return {@code true} if the current thread is executing as a
849 <     * ForkJoinPool computation, or false otherwise
848 >     * @return {@code true} if the current thread is a {@link
849 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
850 >     * or {@code false} otherwise
851       */
852      public static boolean inForkJoinPool() {
853          return Thread.currentThread() instanceof ForkJoinWorkerThread;
# Line 851 | Line 862 | public abstract class ForkJoinTask<V> im
862       * were not, stolen.
863       *
864       * <p>This method may be invoked only from within {@code
865 <     * ForkJoinTask} computations (as may be determined using method
865 >     * ForkJoinPool} computations (as may be determined using method
866       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
867       * result in exceptions or errors, possibly including {@code
868       * ClassCastException}.
# Line 870 | Line 881 | public abstract class ForkJoinTask<V> im
881       * fork other tasks.
882       *
883       * <p>This method may be invoked only from within {@code
884 <     * ForkJoinTask} computations (as may be determined using method
884 >     * ForkJoinPool} computations (as may be determined using method
885       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
886       * result in exceptions or errors, possibly including {@code
887       * ClassCastException}.
# Line 893 | Line 904 | public abstract class ForkJoinTask<V> im
904       * exceeded.
905       *
906       * <p>This method may be invoked only from within {@code
907 <     * ForkJoinTask} computations (as may be determined using method
907 >     * ForkJoinPool} computations (as may be determined using method
908       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
909       * result in exceptions or errors, possibly including {@code
910       * ClassCastException}.
# Line 951 | Line 962 | public abstract class ForkJoinTask<V> im
962       * otherwise.
963       *
964       * <p>This method may be invoked only from within {@code
965 <     * ForkJoinTask} computations (as may be determined using method
965 >     * ForkJoinPool} computations (as may be determined using method
966       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
967       * result in exceptions or errors, possibly including {@code
968       * ClassCastException}.
# Line 970 | Line 981 | public abstract class ForkJoinTask<V> im
981       * be useful otherwise.
982       *
983       * <p>This method may be invoked only from within {@code
984 <     * ForkJoinTask} computations (as may be determined using method
984 >     * ForkJoinPool} computations (as may be determined using method
985       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
986       * result in exceptions or errors, possibly including {@code
987       * ClassCastException}.
# Line 993 | Line 1004 | public abstract class ForkJoinTask<V> im
1004       * otherwise.
1005       *
1006       * <p>This method may be invoked only from within {@code
1007 <     * ForkJoinTask} computations (as may be determined using method
1007 >     * ForkJoinPool} computations (as may be determined using method
1008       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1009       * result in exceptions or errors, possibly including {@code
1010       * ClassCastException}.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines