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.48 by dl, Thu May 27 16:46:48 2010 UTC vs.
Revision 1.55 by dl, Sun Aug 29 23:34:46 2010 UTC

# Line 64 | Line 64 | import java.util.WeakHashMap;
64   * results of a task is {@link #join}, but there are several variants:
65   * The {@link Future#get} methods support interruptible and/or timed
66   * waits for completion and report results using {@code Future}
67 < * conventions. Method {@link #helpJoin} enables callers to actively
68 < * execute other tasks while awaiting joins, which is sometimes more
69 < * efficient but only applies when all subtasks are known to be
70 < * strictly tree-structured. Method {@link #invoke} is semantically
67 > * conventions. Method {@link #invoke} is semantically
68   * equivalent to {@code fork(); join()} but always attempts to begin
69   * execution in the current thread. The "<em>quiet</em>" forms of
70   * these methods do not extract results or report exceptions. These
# Line 125 | Line 122 | import java.util.WeakHashMap;
122   *
123   * <p>This class provides {@code adapt} methods for {@link Runnable}
124   * and {@link Callable}, that may be of use when mixing execution of
125 < * {@code ForkJoinTasks} with other kinds of tasks. When all tasks
126 < * are of this form, consider using a pool in
130 < * {@linkplain ForkJoinPool#setAsyncMode async mode}.
125 > * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
126 > * of this form, consider using a pool constructed in <em>asyncMode</em>.
127   *
128   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
129   * used in extensions such as remote execution frameworks. It is
# Line 148 | Line 144 | public abstract class ForkJoinTask<V> im
144       * status maintenance (2) execution and awaiting completion (3)
145       * user-level methods that additionally report results. This is
146       * sometimes hard to see because this file orders exported methods
147 <     * in a way that flows well in javadocs.
147 >     * in a way that flows well in javadocs. In particular, most
148 >     * join mechanics are in method quietlyJoin, below.
149       */
150  
151 <    /**
152 <     * Run control status bits packed into a single int to minimize
153 <     * footprint and to ensure atomicity (via CAS).  Status is
154 <     * initially zero, and takes on nonnegative values until
155 <     * completed, upon which status holds COMPLETED. CANCELLED, or
156 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
157 <     * blocking waits by other threads have the SIGNAL bit set.
158 <     *
159 <     * Completion of a stolen task with SIGNAL set awakens any waiters
163 <     * via notifyAll. Even though suboptimal for some purposes, we use
151 >    /*
152 >     * The status field holds run control status bits packed into a
153 >     * single int to minimize footprint and to ensure atomicity (via
154 >     * CAS).  Status is initially zero, and takes on nonnegative
155 >     * values until completed, upon which status holds value
156 >     * COMPLETED. CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
157 >     * waits by other threads have the SIGNAL bit set.  Completion of
158 >     * a stolen task with SIGNAL set awakens any waiters via
159 >     * notifyAll. Even though suboptimal for some purposes, we use
160       * basic builtin wait/notify to take advantage of "monitor
161       * inflation" in JVMs that we would otherwise need to emulate to
162       * avoid adding further per-task bookkeeping overhead.  We want
163       * these monitors to be "fat", i.e., not use biasing or thin-lock
164       * techniques, so use some odd coding idioms that tend to avoid
165       * them.
170     *
171     * Note that bits 1-28 are currently unused. Also value
172     * 0x80000000 is available as spare completion value.
166       */
167 +
168 +    /** The run status of this task */
169      volatile int status; // accessed directly by pool and workers
170  
171 <    private static final int COMPLETION_MASK      = 0xe0000000;
172 <    private static final int NORMAL               = 0xe0000000; // == mask
173 <    private static final int CANCELLED            = 0xc0000000;
174 <    private static final int EXCEPTIONAL          = 0xa0000000;
180 <    private static final int SIGNAL               = 0x00000001;
171 >    private static final int NORMAL      = -1;
172 >    private static final int CANCELLED   = -2;
173 >    private static final int EXCEPTIONAL = -3;
174 >    private static final int SIGNAL      =  1;
175  
176      /**
177       * Table of exceptions thrown by tasks, to enable reporting by
# Line 198 | Line 192 | public abstract class ForkJoinTask<V> im
192       * also clearing signal request bits.
193       *
194       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
201     * @return status on exit
195       */
196 <    private int setCompletion(int completion) {
196 >    private void setCompletion(int completion) {
197          int s;
198          while ((s = status) >= 0) {
199              if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
200 <                if ((s & SIGNAL) != 0)
200 >                if (s != 0)
201                      synchronized (this) { notifyAll(); }
202 <                return completion;
202 >                break;
203              }
204          }
212        return s;
205      }
206  
207      /**
208       * Record exception and set exceptional completion
209       * @return status on exit
210       */
211 <    private int setExceptionalCompletion(Throwable rex) {
211 >    private void setExceptionalCompletion(Throwable rex) {
212          exceptionMap.put(this, rex);
213 <        return setCompletion(EXCEPTIONAL);
213 >        setCompletion(EXCEPTIONAL);
214      }
215  
216      /**
217 <     * Blocks a worker thread until completion. Called only by pool.
217 >     * Blocks a worker thread until completion. Called only by
218 >     * pool. Currently unused -- pool-based waits use timeout
219 >     * version below.
220       */
221      final void internalAwaitDone() {
222 <        int s;
222 >        int s;         // the odd construction reduces lock bias effects
223          while ((s = status) >= 0) {
224 <            synchronized(this) {
225 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
226 <                    do {
227 <                        try {
234 <                            wait();
235 <                        } catch (InterruptedException ie) {
236 <                            cancelIfTerminating();
237 <                        }
238 <                    } while (status >= 0);
239 <                    break;
224 >            try {
225 >                synchronized(this) {
226 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
227 >                        wait();
228                  }
229 +            } catch (InterruptedException ie) {
230 +                cancelIfTerminating();
231              }
232          }
233      }
234  
235      /**
236 <     * Blocks a non-worker-thread until completion.
236 >     * Blocks a worker thread until completed or timed out.  Called
237 >     * only by pool.
238 >     *
239       * @return status on exit
240       */
241 <    private int externalAwaitDone() {
241 >    final int internalAwaitDone(long millis) {
242 >        int s;
243 >        if ((s = status) >= 0) {
244 >            try {
245 >                synchronized(this) {
246 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
247 >                        wait(millis, 0);
248 >                }
249 >            } catch (InterruptedException ie) {
250 >                cancelIfTerminating();
251 >            }
252 >            s = status;
253 >        }
254 >        return s;
255 >    }
256 >
257 >    /**
258 >     * Blocks a non-worker-thread until completion.
259 >     */
260 >    private void externalAwaitDone() {
261          int s;
262          while ((s = status) >= 0) {
263              synchronized(this) {
264 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
264 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
265                      boolean interrupted = false;
266 <                    do {
266 >                    while (status >= 0) {
267                          try {
268                              wait();
269                          } catch (InterruptedException ie) {
270                              interrupted = true;
271                          }
272 <                    } while ((s = status) >= 0);
272 >                    }
273                      if (interrupted)
274                          Thread.currentThread().interrupt();
275                      break;
276                  }
277              }
278          }
268        return s;
279      }
280  
281      /**
282       * Unless done, calls exec and records status if completed, but
283 <     * doesn't wait for completion otherwise.
283 >     * doesn't wait for completion otherwise. Primary execution method
284 >     * for ForkJoinWorkerThread.
285       */
286 <    final void tryExec() {
286 >    final void quietlyExec() {
287          try {
288              if (status < 0 || !exec())
289                  return;
# Line 283 | Line 294 | public abstract class ForkJoinTask<V> im
294          setCompletion(NORMAL); // must be outside try block
295      }
296  
286    /**
287     * If not done and this task is next in worker queue, runs it,
288     * else waits for it.
289     * @return status on exit
290     */
291    private int waitingJoin() {
292        int s = status;
293        if (s < 0)
294            return s;
295        Thread t = Thread.currentThread();
296        if (t instanceof ForkJoinWorkerThread) {
297            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
298            if (w.unpushTask(this)) {
299                boolean completed;
300                try {
301                    completed = exec();
302                } catch (Throwable rex) {
303                    return setExceptionalCompletion(rex);
304                }
305                if (completed)
306                    return setCompletion(NORMAL);
307            }
308            return w.pool.awaitJoin(this);
309        }
310        else
311            return externalAwaitDone();
312    }
313
314    /**
315     * Unless done, calls exec and records status if completed, or
316     * waits for completion otherwise.
317     * @return status on exit
318     */
319    private int waitingInvoke() {
320        int s = status;
321        if (s < 0)
322            return s;
323        boolean completed;
324        try {
325            completed = exec();
326        } catch (Throwable rex) {
327            return setExceptionalCompletion(rex);
328        }
329        if (completed)
330            return setCompletion(NORMAL);
331        return waitingJoin();
332    }
333
334    /**
335     * If this task is next in worker queue, runs it, else processes other
336     * tasks until complete.
337     * @return status on exit
338     */
339    private int busyJoin() {
340        int s = status;
341        if (s < 0)
342            return s;
343        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
344        if (w.unpushTask(this)) {
345            boolean completed;
346            try {
347                completed = exec();
348            } catch (Throwable rex) {
349                return setExceptionalCompletion(rex);
350            }
351            if (completed)
352                return setCompletion(NORMAL);
353        }
354        return w.execWhileJoining(this);
355    }
356
357    /**
358     * Returns result or throws exception associated with given status.
359     * @param s the status
360     */
361    private V reportResult(int s) {
362        Throwable ex;
363        if (s < NORMAL && (ex = getException()) != null)
364            UNSAFE.throwException(ex);
365        return getRawResult();
366    }
367
297      // public methods
298  
299      /**
# Line 400 | Line 329 | public abstract class ForkJoinTask<V> im
329       * @return the computed result
330       */
331      public final V join() {
332 <        return reportResult(waitingJoin());
332 >        quietlyJoin();
333 >        Throwable ex;
334 >        if (status < NORMAL && (ex = getException()) != null)
335 >            UNSAFE.throwException(ex);
336 >        return getRawResult();
337      }
338  
339      /**
# Line 411 | Line 344 | public abstract class ForkJoinTask<V> im
344       * @return the computed result
345       */
346      public final V invoke() {
347 <        return reportResult(waitingInvoke());
347 >        quietlyInvoke();
348 >        Throwable ex;
349 >        if (status < NORMAL && (ex = getException()) != null)
350 >            UNSAFE.throwException(ex);
351 >        return getRawResult();
352      }
353  
354      /**
# Line 469 | Line 406 | public abstract class ForkJoinTask<V> im
406              }
407              else if (i != 0)
408                  t.fork();
409 <            else if (t.waitingInvoke() < NORMAL && ex == null)
410 <                ex = t.getException();
409 >            else {
410 >                t.quietlyInvoke();
411 >                if (ex == null && t.status < NORMAL)
412 >                    ex = t.getException();
413 >            }
414          }
415          for (int i = 1; i <= last; ++i) {
416              ForkJoinTask<?> t = tasks[i];
417              if (t != null) {
418                  if (ex != null)
419                      t.cancel(false);
420 <                else if (t.waitingJoin() < NORMAL && ex == null)
421 <                    ex = t.getException();
420 >                else {
421 >                    t.quietlyJoin();
422 >                    if (ex == null && t.status < NORMAL)
423 >                        ex = t.getException();
424 >                }
425              }
426          }
427          if (ex != null)
# Line 525 | Line 468 | public abstract class ForkJoinTask<V> im
468              }
469              else if (i != 0)
470                  t.fork();
471 <            else if (t.waitingInvoke() < NORMAL && ex == null)
472 <                ex = t.getException();
471 >            else {
472 >                t.quietlyInvoke();
473 >                if (ex == null && t.status < NORMAL)
474 >                    ex = t.getException();
475 >            }
476          }
477          for (int i = 1; i <= last; ++i) {
478              ForkJoinTask<?> t = ts.get(i);
479              if (t != null) {
480                  if (ex != null)
481                      t.cancel(false);
482 <                else if (t.waitingJoin() < NORMAL && ex == null)
483 <                    ex = t.getException();
482 >                else {
483 >                    t.quietlyJoin();
484 >                    if (ex == null && t.status < NORMAL)
485 >                        ex = t.getException();
486 >                }
487              }
488          }
489          if (ex != null)
# Line 568 | Line 517 | public abstract class ForkJoinTask<V> im
517       */
518      public boolean cancel(boolean mayInterruptIfRunning) {
519          setCompletion(CANCELLED);
520 <        return (status & COMPLETION_MASK) == CANCELLED;
520 >        return status == CANCELLED;
521      }
522  
523      /**
524 <     * Cancels, ignoring any exceptions it throws. Used during worker
525 <     * and pool shutdown.
524 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
525 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
526 >     * exceptions, but if it does anyway, we have no recourse during
527 >     * shutdown, so guard against this case.
528       */
529      final void cancelIgnoringExceptions() {
530          try {
# Line 585 | Line 536 | public abstract class ForkJoinTask<V> im
536      /**
537       * Cancels ignoring exceptions if worker is terminating
538       */
539 <    private void cancelIfTerminating() {
539 >    final void cancelIfTerminating() {
540          Thread t = Thread.currentThread();
541          if ((t instanceof ForkJoinWorkerThread) &&
542              ((ForkJoinWorkerThread) t).isTerminating()) {
# Line 601 | Line 552 | public abstract class ForkJoinTask<V> im
552      }
553  
554      public final boolean isCancelled() {
555 <        return (status & COMPLETION_MASK) == CANCELLED;
555 >        return status == CANCELLED;
556      }
557  
558      /**
# Line 610 | Line 561 | public abstract class ForkJoinTask<V> im
561       * @return {@code true} if this task threw an exception or was cancelled
562       */
563      public final boolean isCompletedAbnormally() {
564 <        return (status & COMPLETION_MASK) < NORMAL;
564 >        return status < NORMAL;
565      }
566  
567      /**
# Line 621 | Line 572 | public abstract class ForkJoinTask<V> im
572       * exception and was not cancelled
573       */
574      public final boolean isCompletedNormally() {
575 <        return (status & COMPLETION_MASK) == NORMAL;
575 >        return status == NORMAL;
576      }
577  
578      /**
# Line 632 | Line 583 | public abstract class ForkJoinTask<V> im
583       * @return the exception, or {@code null} if none
584       */
585      public final Throwable getException() {
586 <        int s = status & COMPLETION_MASK;
586 >        int s = status;
587          return ((s >= NORMAL)    ? null :
588                  (s == CANCELLED) ? new CancellationException() :
589                  exceptionMap.get(this));
# Line 681 | Line 632 | public abstract class ForkJoinTask<V> im
632      }
633  
634      public final V get() throws InterruptedException, ExecutionException {
635 <        int s = waitingJoin() & COMPLETION_MASK;
635 >        quietlyJoin();
636          if (Thread.interrupted())
637              throw new InterruptedException();
638 +        int s = status;
639          if (s < NORMAL) {
640              Throwable ex;
641              if (s == CANCELLED)
# Line 701 | Line 653 | public abstract class ForkJoinTask<V> im
653          if (t instanceof ForkJoinWorkerThread) {
654              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
655              if (status >= 0 && w.unpushTask(this))
656 <                tryExec();
656 >                quietlyExec();
657              pool = w.pool;
658          }
659          else
660              pool = null;
661          /*
662 <         * Timed wait loop intermixes cases for fj (pool != null) and
662 >         * Timed wait loop intermixes cases for FJ (pool != null) and
663           * non FJ threads. For FJ, decrement pool count but don't try
664           * for replacement; increment count on completion. For non-FJ,
665           * deal with interrupts. This is messy, but a little less so
# Line 715 | Line 667 | public abstract class ForkJoinTask<V> im
667           */
668          boolean interrupted = false;
669          boolean dec = false; // true if pool count decremented
670 +        long nanos = unit.toNanos(timeout);
671          for (;;) {
672              if (Thread.interrupted() && pool == null) {
673                  interrupted = true;
# Line 723 | Line 676 | public abstract class ForkJoinTask<V> im
676              int s = status;
677              if (s < 0)
678                  break;
679 <            if (UNSAFE.compareAndSwapInt(this, statusOffset,
727 <                                         s, s | SIGNAL)) {
679 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
680                  long startTime = System.nanoTime();
729                long nanos = unit.toNanos(timeout);
681                  long nt; // wait time
682                  while (status >= 0 &&
683                         (nt = nanos - (System.nanoTime() - startTime)) > 0) {
# Line 754 | Line 705 | public abstract class ForkJoinTask<V> im
705              }
706          }
707          if (pool != null && dec)
708 <            pool.updateRunningCount(1);
708 >            pool.incrementRunningCount();
709          if (interrupted)
710              throw new InterruptedException();
711 <        int es = status & COMPLETION_MASK;
711 >        int es = status;
712          if (es != NORMAL) {
713              Throwable ex;
714              if (es == CANCELLED)
# Line 770 | Line 721 | public abstract class ForkJoinTask<V> im
721      }
722  
723      /**
724 <     * Possibly executes other tasks until this task {@link #isDone is
774 <     * done}, then returns the result of the computation.  This method
775 <     * may be more efficient than {@code join}, but is only applicable
776 <     * when there are no potential dependencies between continuation
777 <     * of the current task and that of any other task that might be
778 <     * executed while helping. (This usually holds for pure
779 <     * divide-and-conquer tasks).
780 <     *
781 <     * <p>This method may be invoked only from within {@code
782 <     * ForkJoinTask} computations (as may be determined using method
783 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
784 <     * result in exceptions or errors, possibly including {@code
785 <     * ClassCastException}.
786 <     *
787 <     * @return the computed result
788 <     */
789 <    public final V helpJoin() {
790 <        return reportResult(busyJoin());
791 <    }
792 <
793 <    /**
794 <     * Possibly executes other tasks until this task {@link #isDone is
795 <     * done}.  This method may be useful when processing collections
796 <     * of tasks when some have been cancelled or otherwise known to
797 <     * have aborted.
798 <     *
799 <     * <p>This method may be invoked only from within {@code
800 <     * ForkJoinTask} computations (as may be determined using method
801 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
802 <     * result in exceptions or errors, possibly including {@code
803 <     * ClassCastException}.
804 <     */
805 <    public final void quietlyHelpJoin() {
806 <        busyJoin();
807 <    }
808 <
809 <    /**
810 <     * Joins this task, without returning its result or throwing an
724 >     * Joins this task, without returning its result or throwing its
725       * exception. This method may be useful when processing
726       * collections of tasks when some have been cancelled or otherwise
727       * known to have aborted.
728       */
729      public final void quietlyJoin() {
730 <        waitingJoin();
730 >        Thread t;
731 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
732 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
733 >            if (status >= 0) {
734 >                if (w.unpushTask(this)) {
735 >                    boolean completed;
736 >                    try {
737 >                        completed = exec();
738 >                    } catch (Throwable rex) {
739 >                        setExceptionalCompletion(rex);
740 >                        return;
741 >                    }
742 >                    if (completed) {
743 >                        setCompletion(NORMAL);
744 >                        return;
745 >                    }
746 >                }
747 >                w.joinTask(this);
748 >            }
749 >        }
750 >        else
751 >            externalAwaitDone();
752      }
753  
754      /**
755       * Commences performing this task and awaits its completion if
756 <     * necessary, without returning its result or throwing an
756 >     * necessary, without returning its result or throwing its
757       * exception. This method may be useful when processing
758       * collections of tasks when some have been cancelled or otherwise
759       * known to have aborted.
760       */
761      public final void quietlyInvoke() {
762 <        waitingInvoke();
762 >        if (status >= 0) {
763 >            boolean completed;
764 >            try {
765 >                completed = exec();
766 >            } catch (Throwable rex) {
767 >                setExceptionalCompletion(rex);
768 >                return;
769 >            }
770 >            if (completed)
771 >                setCompletion(NORMAL);
772 >            else
773 >                quietlyJoin();
774 >        }
775      }
776  
777      /**
# Line 856 | Line 803 | public abstract class ForkJoinTask<V> im
803       * pre-constructed trees of subtasks in loops.
804       */
805      public void reinitialize() {
806 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
806 >        if (status == EXCEPTIONAL)
807              exceptionMap.remove(this);
808          status = 0;
809      }
# Line 1166 | Line 1113 | public abstract class ForkJoinTask<V> im
1113      private void readObject(java.io.ObjectInputStream s)
1114          throws java.io.IOException, ClassNotFoundException {
1115          s.defaultReadObject();
1169        status |= SIGNAL; // conservatively set external signal
1116          Object ex = s.readObject();
1117          if (ex != null)
1118              setExceptionalCompletion((Throwable) ex);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines