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.54 by dl, Wed Aug 11 19:44:30 2010 UTC vs.
Revision 1.66 by dl, Sun Oct 24 19:37:26 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 100 | Line 108 | import java.util.WeakHashMap;
108   * ForkJoinTasks (as may be determined using method {@link
109   * #inForkJoinPool}).  Attempts to invoke them in other contexts
110   * result in exceptions or errors, possibly including
111 < * ClassCastException.
111 > * {@code ClassCastException}.
112   *
113   * <p>Most base support methods are {@code final}, to prevent
114   * overriding of implementations that are intrinsically tied to the
# Line 153 | Line 161 | public abstract class ForkJoinTask<V> im
161       * single int to minimize footprint and to ensure atomicity (via
162       * CAS).  Status is initially zero, and takes on nonnegative
163       * values until completed, upon which status holds value
164 <     * COMPLETED. CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
164 >     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
165       * waits by other threads have the SIGNAL bit set.  Completion of
166       * a stolen task with SIGNAL set awakens any waiters via
167       * notifyAll. Even though suboptimal for some purposes, we use
# Line 205 | Line 213 | public abstract class ForkJoinTask<V> im
213      }
214  
215      /**
216 <     * Record exception and set exceptional completion
216 >     * Records exception and sets exceptional completion.
217 >     *
218       * @return status on exit
219       */
220      private void setExceptionalCompletion(Throwable rex) {
# Line 214 | Line 223 | public abstract class ForkJoinTask<V> im
223      }
224  
225      /**
226 <     * Blocks a worker thread until completion. Called only by pool.
226 >     * Blocks a worker thread until completion. Called only by
227 >     * pool. Currently unused -- pool-based waits use timeout
228 >     * version below.
229       */
230      final void internalAwaitDone() {
231          int s;         // the odd construction reduces lock bias effects
232          while ((s = status) >= 0) {
233              try {
234 <                synchronized(this) {
234 >                synchronized (this) {
235                      if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
236                          wait();
237                  }
# Line 231 | Line 242 | public abstract class ForkJoinTask<V> im
242      }
243  
244      /**
245 +     * Blocks a worker thread until completed or timed out.  Called
246 +     * only by pool.
247 +     *
248 +     * @return status on exit
249 +     */
250 +    final int internalAwaitDone(long millis, int nanos) {
251 +        int s;
252 +        if ((s = status) >= 0) {
253 +            try {
254 +                synchronized (this) {
255 +                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
256 +                        wait(millis, nanos);
257 +                }
258 +            } catch (InterruptedException ie) {
259 +                cancelIfTerminating();
260 +            }
261 +            s = status;
262 +        }
263 +        return s;
264 +    }
265 +
266 +    /**
267       * Blocks a non-worker-thread until completion.
268       */
269      private void externalAwaitDone() {
270          int s;
271          while ((s = status) >= 0) {
272 <            synchronized(this) {
273 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
272 >            synchronized (this) {
273 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
274                      boolean interrupted = false;
275                      while (status >= 0) {
276                          try {
# Line 314 | Line 347 | public abstract class ForkJoinTask<V> im
347  
348      /**
349       * Commences performing this task, awaits its completion if
350 <     * necessary, and return its result, or throws an (unchecked)
351 <     * exception if the underlying computation did so.
350 >     * necessary, and returns its result, or throws an (unchecked)
351 >     * {@code RuntimeException} or {@code Error} if the underlying
352 >     * computation did so.
353       *
354       * @return the computed result
355       */
# Line 330 | Line 364 | public abstract class ForkJoinTask<V> im
364      /**
365       * Forks the given tasks, returning when {@code isDone} holds for
366       * each task or an (unchecked) exception is encountered, in which
367 <     * case the exception is rethrown.  If either task encounters an
368 <     * exception, the other one may be, but is not guaranteed to be,
369 <     * cancelled.  If both tasks throw an exception, then this method
370 <     * throws one of them.  The individual status of each task may be
371 <     * checked using {@link #getException()} and related methods.
367 >     * case the exception is rethrown. If more than one task
368 >     * encounters an exception, then this method throws any one of
369 >     * these exceptions. If any task encounters an exception, the
370 >     * other may be cancelled. However, the execution status of
371 >     * individual tasks is not guaranteed upon exceptional return. The
372 >     * status of each task may be obtained using {@link
373 >     * #getException()} and related methods to check if they have been
374 >     * cancelled, completed normally or exceptionally, or left
375 >     * unprocessed.
376       *
377       * <p>This method may be invoked only from within {@code
378       * ForkJoinTask} computations (as may be determined using method
# Line 355 | Line 393 | public abstract class ForkJoinTask<V> im
393      /**
394       * Forks the given tasks, returning when {@code isDone} holds for
395       * each task or an (unchecked) exception is encountered, in which
396 <     * case the exception is rethrown. If any task encounters an
397 <     * exception, others may be, but are not guaranteed to be,
398 <     * cancelled.  If more than one task encounters an exception, then
399 <     * this method throws any one of these exceptions.  The individual
400 <     * status of each task may be checked using {@link #getException()}
401 <     * and related methods.
396 >     * case the exception is rethrown. If more than one task
397 >     * encounters an exception, then this method throws any one of
398 >     * these exceptions. If any task encounters an exception, others
399 >     * may be cancelled. However, the execution status of individual
400 >     * tasks is not guaranteed upon exceptional return. The status of
401 >     * each task may be obtained using {@link #getException()} and
402 >     * related methods to check if they have been cancelled, completed
403 >     * normally or exceptionally, or left unprocessed.
404       *
405       * <p>This method may be invoked only from within {@code
406       * ForkJoinTask} computations (as may be determined using method
# Line 407 | Line 447 | public abstract class ForkJoinTask<V> im
447      /**
448       * Forks all tasks in the specified collection, returning when
449       * {@code isDone} holds for each task or an (unchecked) exception
450 <     * is encountered.  If any task encounters an exception, others
451 <     * may be, but are not guaranteed to be, cancelled.  If more than
452 <     * one task encounters an exception, then this method throws any
453 <     * one of these exceptions.  The individual status of each task
454 <     * may be checked using {@link #getException()} and related
455 <     * methods.  The behavior of this operation is undefined if the
456 <     * specified collection is modified while the operation is in
457 <     * progress.
450 >     * is encountered, in which case the exception is rethrown. If
451 >     * more than one task encounters an exception, then this method
452 >     * throws any one of these exceptions. If any task encounters an
453 >     * exception, others may be cancelled. However, the execution
454 >     * status of individual tasks is not guaranteed upon exceptional
455 >     * return. The status of each task may be obtained using {@link
456 >     * #getException()} and related methods to check if they have been
457 >     * cancelled, completed normally or exceptionally, or left
458 >     * unprocessed.
459       *
460       * <p>This method may be invoked only from within {@code
461       * ForkJoinTask} computations (as may be determined using method
# Line 510 | Line 551 | public abstract class ForkJoinTask<V> im
551      }
552  
553      /**
554 <     * Cancels ignoring exceptions if worker is terminating
554 >     * Cancels if current thread is a terminating worker thread,
555 >     * ignoring any exceptions thrown by cancel.
556       */
557      final void cancelIfTerminating() {
558          Thread t = Thread.currentThread();
# Line 587 | Line 629 | public abstract class ForkJoinTask<V> im
629  
630      /**
631       * Completes this task, and if not already aborted or cancelled,
632 <     * returning a {@code null} result upon {@code join} and related
633 <     * operations. This method may be used to provide results for
634 <     * asynchronous tasks, or to provide alternative handling for
635 <     * tasks that would not otherwise complete normally. Its use in
636 <     * other situations is discouraged. This method is
637 <     * overridable, but overridden versions must invoke {@code super}
638 <     * implementation to maintain guarantees.
632 >     * returning the given value as the result of subsequent
633 >     * invocations of {@code join} and related operations. This method
634 >     * may be used to provide results for asynchronous tasks, or to
635 >     * provide alternative handling for tasks that would not otherwise
636 >     * complete normally. Its use in other situations is
637 >     * discouraged. This method is overridable, but overridden
638 >     * versions must invoke {@code super} implementation to maintain
639 >     * guarantees.
640       *
641       * @param value the result value for this task
642       */
# Line 607 | Line 650 | public abstract class ForkJoinTask<V> im
650          setCompletion(NORMAL);
651      }
652  
653 +    /**
654 +     * Waits if necessary for the computation to complete, and then
655 +     * retrieves its result.
656 +     *
657 +     * @return the computed result
658 +     * @throws CancellationException if the computation was cancelled
659 +     * @throws ExecutionException if the computation threw an
660 +     * exception
661 +     * @throws InterruptedException if the current thread is not a
662 +     * member of a ForkJoinPool and was interrupted while waiting
663 +     */
664      public final V get() throws InterruptedException, ExecutionException {
665 <        quietlyJoin();
666 <        if (Thread.interrupted())
667 <            throw new InterruptedException();
668 <        int s = status;
665 >        int s;
666 >        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
667 >            quietlyJoin();
668 >            s = status;
669 >        }
670 >        else {
671 >            while ((s = status) >= 0) {
672 >                synchronized (this) { // interruptible form of awaitDone
673 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
674 >                                                 s, SIGNAL)) {
675 >                        while (status >= 0)
676 >                            wait();
677 >                    }
678 >                }
679 >            }
680 >        }
681          if (s < NORMAL) {
682              Throwable ex;
683              if (s == CANCELLED)
# Line 622 | Line 688 | public abstract class ForkJoinTask<V> im
688          return getRawResult();
689      }
690  
691 +    /**
692 +     * Waits if necessary for at most the given time for the computation
693 +     * to complete, and then retrieves its result, if available.
694 +     *
695 +     * @param timeout the maximum time to wait
696 +     * @param unit the time unit of the timeout argument
697 +     * @return the computed result
698 +     * @throws CancellationException if the computation was cancelled
699 +     * @throws ExecutionException if the computation threw an
700 +     * exception
701 +     * @throws InterruptedException if the current thread is not a
702 +     * member of a ForkJoinPool and was interrupted while waiting
703 +     * @throws TimeoutException if the wait timed out
704 +     */
705      public final V get(long timeout, TimeUnit unit)
706          throws InterruptedException, ExecutionException, TimeoutException {
627        Thread t = Thread.currentThread();
628        ForkJoinPool pool;
629        if (t instanceof ForkJoinWorkerThread) {
630            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
631            if (status >= 0 && w.unpushTask(this))
632                quietlyExec();
633            pool = w.pool;
634        }
635        else
636            pool = null;
637        /*
638         * Timed wait loop intermixes cases for FJ (pool != null) and
639         * non FJ threads. For FJ, decrement pool count but don't try
640         * for replacement; increment count on completion. For non-FJ,
641         * deal with interrupts. This is messy, but a little less so
642         * than is splitting the FJ and nonFJ cases.
643         */
644        boolean interrupted = false;
645        boolean dec = false; // true if pool count decremented
707          long nanos = unit.toNanos(timeout);
708 <        for (;;) {
709 <            if (Thread.interrupted() && pool == null) {
710 <                interrupted = true;
711 <                break;
708 >        if (status >= 0) {
709 >            Thread t = Thread.currentThread();
710 >            if (t instanceof ForkJoinWorkerThread) {
711 >                ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
712 >                boolean completed = false; // timed variant of quietlyJoin
713 >                if (w.unpushTask(this)) {
714 >                    try {
715 >                        completed = exec();
716 >                    } catch (Throwable rex) {
717 >                        setExceptionalCompletion(rex);
718 >                    }
719 >                }
720 >                if (completed)
721 >                    setCompletion(NORMAL);
722 >                else if (status >= 0)
723 >                    w.joinTask(this, true, nanos);
724              }
725 <            int s = status;
726 <            if (s < 0)
727 <                break;
655 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
725 >            else if (Thread.interrupted())
726 >                throw new InterruptedException();
727 >            else {
728                  long startTime = System.nanoTime();
729 <                long nt; // wait time
730 <                while (status >= 0 &&
729 >                int s; long nt;
730 >                while ((s = status) >= 0 &&
731                         (nt = nanos - (System.nanoTime() - startTime)) > 0) {
732 <                    if (pool != null && !dec)
733 <                        dec = pool.tryDecrementRunningCount();
662 <                    else {
732 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,
733 >                                                 SIGNAL)) {
734                          long ms = nt / 1000000;
735                          int ns = (int) (nt % 1000000);
736 <                        try {
737 <                            synchronized(this) {
738 <                                if (status >= 0)
668 <                                    wait(ms, ns);
669 <                            }
670 <                        } catch (InterruptedException ie) {
671 <                            if (pool != null)
672 <                                cancelIfTerminating();
673 <                            else {
674 <                                interrupted = true;
675 <                                break;
676 <                            }
736 >                        synchronized (this) {
737 >                            if (status >= 0)
738 >                                wait(ms, ns); // exit on IE throw
739                          }
740                      }
741                  }
680                break;
742              }
743          }
683        if (pool != null && dec)
684            pool.incrementRunningCount();
685        if (interrupted)
686            throw new InterruptedException();
744          int es = status;
745          if (es != NORMAL) {
746              Throwable ex;
# Line 720 | Line 777 | public abstract class ForkJoinTask<V> im
777                          return;
778                      }
779                  }
780 <                w.joinTask(this);
780 >                w.joinTask(this, false, 0L);
781              }
782          }
783          else
# Line 730 | Line 787 | public abstract class ForkJoinTask<V> im
787      /**
788       * Commences performing this task and awaits its completion if
789       * necessary, without returning its result or throwing its
790 <     * exception. This method may be useful when processing
734 <     * collections of tasks when some have been cancelled or otherwise
735 <     * known to have aborted.
790 >     * exception.
791       */
792      public final void quietlyInvoke() {
793          if (status >= 0) {
# Line 1069 | Line 1124 | public abstract class ForkJoinTask<V> im
1124      private static final long serialVersionUID = -7721805057305804111L;
1125  
1126      /**
1127 <     * Saves the state to a stream.
1127 >     * Saves the state to a stream (that is, serializes it).
1128       *
1129       * @serialData the current run status and the exception thrown
1130       * during execution, or {@code null} if none
# Line 1082 | Line 1137 | public abstract class ForkJoinTask<V> im
1137      }
1138  
1139      /**
1140 <     * Reconstitutes the instance from a stream.
1140 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1141       *
1142       * @param s the stream
1143       */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines