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.53 by dl, Wed Aug 11 18:45:12 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.
218       */
219      final void internalAwaitDone() {
220 <        int s;
220 >        int s;         // the odd construction reduces lock bias effects
221          while ((s = status) >= 0) {
222 <            synchronized(this) {
223 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
224 <                    do {
225 <                        try {
234 <                            wait();
235 <                        } catch (InterruptedException ie) {
236 <                            cancelIfTerminating();
237 <                        }
238 <                    } while (status >= 0);
239 <                    break;
222 >            try {
223 >                synchronized(this) {
224 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
225 >                        wait();
226                  }
227 +            } catch (InterruptedException ie) {
228 +                cancelIfTerminating();
229              }
230          }
231      }
232  
233      /**
234       * Blocks a non-worker-thread until completion.
247     * @return status on exit
235       */
236 <    private int externalAwaitDone() {
236 >    private void externalAwaitDone() {
237          int s;
238          while ((s = status) >= 0) {
239              synchronized(this) {
240 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
240 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
241                      boolean interrupted = false;
242 <                    do {
242 >                    while (status >= 0) {
243                          try {
244                              wait();
245                          } catch (InterruptedException ie) {
246                              interrupted = true;
247                          }
248 <                    } while ((s = status) >= 0);
248 >                    }
249                      if (interrupted)
250                          Thread.currentThread().interrupt();
251                      break;
252                  }
253              }
254          }
268        return s;
255      }
256  
257      /**
258       * Unless done, calls exec and records status if completed, but
259 <     * doesn't wait for completion otherwise.
259 >     * doesn't wait for completion otherwise. Primary execution method
260 >     * for ForkJoinWorkerThread.
261       */
262 <    final void tryExec() {
262 >    final void quietlyExec() {
263          try {
264              if (status < 0 || !exec())
265                  return;
# Line 283 | Line 270 | public abstract class ForkJoinTask<V> im
270          setCompletion(NORMAL); // must be outside try block
271      }
272  
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
273      // public methods
274  
275      /**
# Line 400 | Line 305 | public abstract class ForkJoinTask<V> im
305       * @return the computed result
306       */
307      public final V join() {
308 <        return reportResult(waitingJoin());
308 >        quietlyJoin();
309 >        Throwable ex;
310 >        if (status < NORMAL && (ex = getException()) != null)
311 >            UNSAFE.throwException(ex);
312 >        return getRawResult();
313      }
314  
315      /**
# Line 411 | Line 320 | public abstract class ForkJoinTask<V> im
320       * @return the computed result
321       */
322      public final V invoke() {
323 <        return reportResult(waitingInvoke());
323 >        quietlyInvoke();
324 >        Throwable ex;
325 >        if (status < NORMAL && (ex = getException()) != null)
326 >            UNSAFE.throwException(ex);
327 >        return getRawResult();
328      }
329  
330      /**
# Line 469 | Line 382 | public abstract class ForkJoinTask<V> im
382              }
383              else if (i != 0)
384                  t.fork();
385 <            else if (t.waitingInvoke() < NORMAL && ex == null)
386 <                ex = t.getException();
385 >            else {
386 >                t.quietlyInvoke();
387 >                if (ex == null && t.status < NORMAL)
388 >                    ex = t.getException();
389 >            }
390          }
391          for (int i = 1; i <= last; ++i) {
392              ForkJoinTask<?> t = tasks[i];
393              if (t != null) {
394                  if (ex != null)
395                      t.cancel(false);
396 <                else if (t.waitingJoin() < NORMAL && ex == null)
397 <                    ex = t.getException();
396 >                else {
397 >                    t.quietlyJoin();
398 >                    if (ex == null && t.status < NORMAL)
399 >                        ex = t.getException();
400 >                }
401              }
402          }
403          if (ex != null)
# Line 525 | Line 444 | public abstract class ForkJoinTask<V> im
444              }
445              else if (i != 0)
446                  t.fork();
447 <            else if (t.waitingInvoke() < NORMAL && ex == null)
448 <                ex = t.getException();
447 >            else {
448 >                t.quietlyInvoke();
449 >                if (ex == null && t.status < NORMAL)
450 >                    ex = t.getException();
451 >            }
452          }
453          for (int i = 1; i <= last; ++i) {
454              ForkJoinTask<?> t = ts.get(i);
455              if (t != null) {
456                  if (ex != null)
457                      t.cancel(false);
458 <                else if (t.waitingJoin() < NORMAL && ex == null)
459 <                    ex = t.getException();
458 >                else {
459 >                    t.quietlyJoin();
460 >                    if (ex == null && t.status < NORMAL)
461 >                        ex = t.getException();
462 >                }
463              }
464          }
465          if (ex != null)
# Line 568 | Line 493 | public abstract class ForkJoinTask<V> im
493       */
494      public boolean cancel(boolean mayInterruptIfRunning) {
495          setCompletion(CANCELLED);
496 <        return (status & COMPLETION_MASK) == CANCELLED;
496 >        return status == CANCELLED;
497      }
498  
499      /**
500 <     * Cancels, ignoring any exceptions it throws. Used during worker
501 <     * and pool shutdown.
500 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
501 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
502 >     * exceptions, but if it does anyway, we have no recourse during
503 >     * shutdown, so guard against this case.
504       */
505      final void cancelIgnoringExceptions() {
506          try {
# Line 585 | Line 512 | public abstract class ForkJoinTask<V> im
512      /**
513       * Cancels ignoring exceptions if worker is terminating
514       */
515 <    private void cancelIfTerminating() {
515 >    final void cancelIfTerminating() {
516          Thread t = Thread.currentThread();
517          if ((t instanceof ForkJoinWorkerThread) &&
518              ((ForkJoinWorkerThread) t).isTerminating()) {
# Line 601 | Line 528 | public abstract class ForkJoinTask<V> im
528      }
529  
530      public final boolean isCancelled() {
531 <        return (status & COMPLETION_MASK) == CANCELLED;
531 >        return status == CANCELLED;
532      }
533  
534      /**
# Line 610 | Line 537 | public abstract class ForkJoinTask<V> im
537       * @return {@code true} if this task threw an exception or was cancelled
538       */
539      public final boolean isCompletedAbnormally() {
540 <        return (status & COMPLETION_MASK) < NORMAL;
540 >        return status < NORMAL;
541      }
542  
543      /**
# Line 621 | Line 548 | public abstract class ForkJoinTask<V> im
548       * exception and was not cancelled
549       */
550      public final boolean isCompletedNormally() {
551 <        return (status & COMPLETION_MASK) == NORMAL;
551 >        return status == NORMAL;
552      }
553  
554      /**
# Line 632 | Line 559 | public abstract class ForkJoinTask<V> im
559       * @return the exception, or {@code null} if none
560       */
561      public final Throwable getException() {
562 <        int s = status & COMPLETION_MASK;
562 >        int s = status;
563          return ((s >= NORMAL)    ? null :
564                  (s == CANCELLED) ? new CancellationException() :
565                  exceptionMap.get(this));
# Line 681 | Line 608 | public abstract class ForkJoinTask<V> im
608      }
609  
610      public final V get() throws InterruptedException, ExecutionException {
611 <        int s = waitingJoin() & COMPLETION_MASK;
611 >        quietlyJoin();
612          if (Thread.interrupted())
613              throw new InterruptedException();
614 +        int s = status;
615          if (s < NORMAL) {
616              Throwable ex;
617              if (s == CANCELLED)
# Line 701 | Line 629 | public abstract class ForkJoinTask<V> im
629          if (t instanceof ForkJoinWorkerThread) {
630              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
631              if (status >= 0 && w.unpushTask(this))
632 <                tryExec();
632 >                quietlyExec();
633              pool = w.pool;
634          }
635          else
636              pool = null;
637          /*
638 <         * Timed wait loop intermixes cases for fj (pool != null) and
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
# Line 723 | Line 651 | public abstract class ForkJoinTask<V> im
651              int s = status;
652              if (s < 0)
653                  break;
654 <            if (UNSAFE.compareAndSwapInt(this, statusOffset,
727 <                                         s, s | SIGNAL)) {
654 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
655                  long startTime = System.nanoTime();
656                  long nanos = unit.toNanos(timeout);
657                  long nt; // wait time
# Line 754 | Line 681 | public abstract class ForkJoinTask<V> im
681              }
682          }
683          if (pool != null && dec)
684 <            pool.updateRunningCount(1);
684 >            pool.incrementRunningCount();
685          if (interrupted)
686              throw new InterruptedException();
687 <        int es = status & COMPLETION_MASK;
687 >        int es = status;
688          if (es != NORMAL) {
689              Throwable ex;
690              if (es == CANCELLED)
# Line 770 | Line 697 | public abstract class ForkJoinTask<V> im
697      }
698  
699      /**
700 <     * 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
700 >     * Joins this task, without returning its result or throwing its
701       * exception. This method may be useful when processing
702       * collections of tasks when some have been cancelled or otherwise
703       * known to have aborted.
704       */
705      public final void quietlyJoin() {
706 <        waitingJoin();
706 >        Thread t;
707 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
708 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
709 >            if (status >= 0) {
710 >                if (w.unpushTask(this)) {
711 >                    boolean completed;
712 >                    try {
713 >                        completed = exec();
714 >                    } catch (Throwable rex) {
715 >                        setExceptionalCompletion(rex);
716 >                        return;
717 >                    }
718 >                    if (completed) {
719 >                        setCompletion(NORMAL);
720 >                        return;
721 >                    }
722 >                }
723 >                w.joinTask(this);
724 >            }
725 >        }
726 >        else
727 >            externalAwaitDone();
728      }
729  
730      /**
731       * Commences performing this task and awaits its completion if
732 <     * necessary, without returning its result or throwing an
732 >     * necessary, without returning its result or throwing its
733       * exception. This method may be useful when processing
734       * collections of tasks when some have been cancelled or otherwise
735       * known to have aborted.
736       */
737      public final void quietlyInvoke() {
738 <        waitingInvoke();
738 >        if (status >= 0) {
739 >            boolean completed;
740 >            try {
741 >                completed = exec();
742 >            } catch (Throwable rex) {
743 >                setExceptionalCompletion(rex);
744 >                return;
745 >            }
746 >            if (completed)
747 >                setCompletion(NORMAL);
748 >            else
749 >                quietlyJoin();
750 >        }
751      }
752  
753      /**
# Line 856 | Line 779 | public abstract class ForkJoinTask<V> im
779       * pre-constructed trees of subtasks in loops.
780       */
781      public void reinitialize() {
782 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
782 >        if (status == EXCEPTIONAL)
783              exceptionMap.remove(this);
784          status = 0;
785      }
# Line 1166 | Line 1089 | public abstract class ForkJoinTask<V> im
1089      private void readObject(java.io.ObjectInputStream s)
1090          throws java.io.IOException, ClassNotFoundException {
1091          s.defaultReadObject();
1169        status |= SIGNAL; // conservatively set external signal
1092          Object ex = s.readObject();
1093          if (ex != null)
1094              setExceptionalCompletion((Throwable) ex);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines