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.51 by dl, Fri Jul 23 16:49:11 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 151 | Line 147 | public abstract class ForkJoinTask<V> im
147       * in a way that flows well in javadocs.
148       */
149  
150 <    /**
151 <     * Run control status bits packed into a single int to minimize
152 <     * footprint and to ensure atomicity (via CAS).  Status is
153 <     * initially zero, and takes on nonnegative values until
154 <     * completed, upon which status holds COMPLETED. CANCELLED, or
155 <     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
156 <     * blocking waits by other threads have the SIGNAL bit set.
157 <     *
158 <     * Completion of a stolen task with SIGNAL set awakens any waiters
163 <     * via notifyAll. Even though suboptimal for some purposes, we use
150 >    /*
151 >     * The status field holds run control status bits packed into a
152 >     * single int to minimize footprint and to ensure atomicity (via
153 >     * CAS).  Status is initially zero, and takes on nonnegative
154 >     * values until completed, upon which status holds value
155 >     * COMPLETED. CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
156 >     * waits by other threads have the SIGNAL bit set.  Completion of
157 >     * a stolen task with SIGNAL set awakens any waiters via
158 >     * notifyAll. Even though suboptimal for some purposes, we use
159       * basic builtin wait/notify to take advantage of "monitor
160       * inflation" in JVMs that we would otherwise need to emulate to
161       * avoid adding further per-task bookkeeping overhead.  We want
162       * these monitors to be "fat", i.e., not use biasing or thin-lock
163       * techniques, so use some odd coding idioms that tend to avoid
164       * them.
170     *
171     * Note that bits 1-28 are currently unused. Also value
172     * 0x80000000 is available as spare completion value.
165       */
166 +
167 +    /** Run status of this task */
168      volatile int status; // accessed directly by pool and workers
169  
170 <    private static final int COMPLETION_MASK      = 0xe0000000;
171 <    private static final int NORMAL               = 0xe0000000; // == mask
172 <    private static final int CANCELLED            = 0xc0000000;
173 <    private static final int EXCEPTIONAL          = 0xa0000000;
180 <    private static final int SIGNAL               = 0x00000001;
170 >    private static final int NORMAL      = -1;
171 >    private static final int CANCELLED   = -2;
172 >    private static final int EXCEPTIONAL = -3;
173 >    private static final int SIGNAL      =  1;
174  
175      /**
176       * Table of exceptions thrown by tasks, to enable reporting by
# Line 204 | Line 197 | public abstract class ForkJoinTask<V> im
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;
203              }
# Line 225 | Line 218 | public abstract class ForkJoinTask<V> im
218       * Blocks a worker thread until completion. Called only by pool.
219       */
220      final void internalAwaitDone() {
221 <        int s;
221 >        int s;         // the odd construction reduces lock bias effects
222          while ((s = status) >= 0) {
223 <            synchronized(this) {
224 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
225 <                    do {
226 <                        try {
234 <                            wait();
235 <                        } catch (InterruptedException ie) {
236 <                            cancelIfTerminating();
237 <                        }
238 <                    } while (status >= 0);
239 <                    break;
223 >            try {
224 >                synchronized(this) {
225 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
226 >                        wait();
227                  }
228 +            } catch (InterruptedException ie) {
229 +                cancelIfTerminating();
230              }
231          }
232      }
# Line 250 | Line 239 | public abstract class ForkJoinTask<V> im
239          int s;
240          while ((s = status) >= 0) {
241              synchronized(this) {
242 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){
242 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
243                      boolean interrupted = false;
244 <                    do {
244 >                    while ((s = status) >= 0) {
245                          try {
246                              wait();
247                          } catch (InterruptedException ie) {
248                              interrupted = true;
249                          }
250 <                    } while ((s = status) >= 0);
250 >                    }
251                      if (interrupted)
252                          Thread.currentThread().interrupt();
253                      break;
# Line 270 | Line 259 | public abstract class ForkJoinTask<V> im
259  
260      /**
261       * Unless done, calls exec and records status if completed, but
262 <     * doesn't wait for completion otherwise.
262 >     * doesn't wait for completion otherwise. Primary execution method
263 >     * for ForkJoinWorkerThread.
264       */
265      final void tryExec() {
266          try {
# Line 288 | Line 278 | public abstract class ForkJoinTask<V> im
278       * else waits for it.
279       * @return status on exit
280       */
281 <    private int waitingJoin() {
282 <        int s = status;
283 <        if (s < 0)
284 <            return s;
281 >    private int doJoin() {
282 >        int stat;
283 >        if ((stat = status) < 0)
284 >            return stat;
285          Thread t = Thread.currentThread();
286 +        ForkJoinWorkerThread w;
287          if (t instanceof ForkJoinWorkerThread) {
288 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
298 <            if (w.unpushTask(this)) {
288 >            if ((w = (ForkJoinWorkerThread) t).unpushTask(this)) {
289                  boolean completed;
290                  try {
291                      completed = exec();
# Line 305 | Line 295 | public abstract class ForkJoinTask<V> im
295                  if (completed)
296                      return setCompletion(NORMAL);
297              }
298 <            return w.pool.awaitJoin(this);
298 >            return w.joinTask(this);
299          }
300 <        else
311 <            return externalAwaitDone();
300 >        return externalAwaitDone();
301      }
302  
303      /**
# Line 316 | Line 305 | public abstract class ForkJoinTask<V> im
305       * waits for completion otherwise.
306       * @return status on exit
307       */
308 <    private int waitingInvoke() {
309 <        int s = status;
310 <        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)) {
308 >    private int doInvoke() {
309 >        int stat;
310 >        if ((stat = status) >= 0) {
311              boolean completed;
312              try {
313                  completed = exec();
314              } catch (Throwable rex) {
315                  return setExceptionalCompletion(rex);
316              }
317 <            if (completed)
352 <                return setCompletion(NORMAL);
317 >            stat = completed ? setCompletion(NORMAL) : doJoin();
318          }
319 <        return w.execWhileJoining(this);
319 >        return stat;
320      }
321  
322      /**
# Line 400 | Line 365 | public abstract class ForkJoinTask<V> im
365       * @return the computed result
366       */
367      public final V join() {
368 <        return reportResult(waitingJoin());
368 >        return reportResult(doJoin());
369      }
370  
371      /**
# Line 411 | Line 376 | public abstract class ForkJoinTask<V> im
376       * @return the computed result
377       */
378      public final V invoke() {
379 <        return reportResult(waitingInvoke());
379 >        return reportResult(doInvoke());
380      }
381  
382      /**
# Line 469 | Line 434 | public abstract class ForkJoinTask<V> im
434              }
435              else if (i != 0)
436                  t.fork();
437 <            else if (t.waitingInvoke() < NORMAL && ex == null)
437 >            else if (t.doInvoke() < NORMAL && ex == null)
438                  ex = t.getException();
439          }
440          for (int i = 1; i <= last; ++i) {
# Line 477 | Line 442 | public abstract class ForkJoinTask<V> im
442              if (t != null) {
443                  if (ex != null)
444                      t.cancel(false);
445 <                else if (t.waitingJoin() < NORMAL && ex == null)
445 >                else if (t.doJoin() < NORMAL && ex == null)
446                      ex = t.getException();
447              }
448          }
# Line 525 | Line 490 | public abstract class ForkJoinTask<V> im
490              }
491              else if (i != 0)
492                  t.fork();
493 <            else if (t.waitingInvoke() < NORMAL && ex == null)
493 >            else if (t.doInvoke() < NORMAL && ex == null)
494                  ex = t.getException();
495          }
496          for (int i = 1; i <= last; ++i) {
# Line 533 | Line 498 | public abstract class ForkJoinTask<V> im
498              if (t != null) {
499                  if (ex != null)
500                      t.cancel(false);
501 <                else if (t.waitingJoin() < NORMAL && ex == null)
501 >                else if (t.doJoin() < NORMAL && ex == null)
502                      ex = t.getException();
503              }
504          }
# Line 567 | Line 532 | public abstract class ForkJoinTask<V> im
532       * @return {@code true} if this task is now cancelled
533       */
534      public boolean cancel(boolean mayInterruptIfRunning) {
535 <        setCompletion(CANCELLED);
571 <        return (status & COMPLETION_MASK) == CANCELLED;
535 >        return setCompletion(CANCELLED) == CANCELLED;
536      }
537  
538      /**
# Line 585 | Line 549 | public abstract class ForkJoinTask<V> im
549      /**
550       * Cancels ignoring exceptions if worker is terminating
551       */
552 <    private void cancelIfTerminating() {
552 >    final void cancelIfTerminating() {
553          Thread t = Thread.currentThread();
554          if ((t instanceof ForkJoinWorkerThread) &&
555              ((ForkJoinWorkerThread) t).isTerminating()) {
# Line 601 | Line 565 | public abstract class ForkJoinTask<V> im
565      }
566  
567      public final boolean isCancelled() {
568 <        return (status & COMPLETION_MASK) == CANCELLED;
568 >        return status == CANCELLED;
569      }
570  
571      /**
# Line 610 | Line 574 | public abstract class ForkJoinTask<V> im
574       * @return {@code true} if this task threw an exception or was cancelled
575       */
576      public final boolean isCompletedAbnormally() {
577 <        return (status & COMPLETION_MASK) < NORMAL;
577 >        return status < NORMAL;
578      }
579  
580      /**
# Line 621 | Line 585 | public abstract class ForkJoinTask<V> im
585       * exception and was not cancelled
586       */
587      public final boolean isCompletedNormally() {
588 <        return (status & COMPLETION_MASK) == NORMAL;
588 >        return status == NORMAL;
589      }
590  
591      /**
# Line 632 | Line 596 | public abstract class ForkJoinTask<V> im
596       * @return the exception, or {@code null} if none
597       */
598      public final Throwable getException() {
599 <        int s = status & COMPLETION_MASK;
599 >        int s = status;
600          return ((s >= NORMAL)    ? null :
601                  (s == CANCELLED) ? new CancellationException() :
602                  exceptionMap.get(this));
# Line 681 | Line 645 | public abstract class ForkJoinTask<V> im
645      }
646  
647      public final V get() throws InterruptedException, ExecutionException {
648 <        int s = waitingJoin() & COMPLETION_MASK;
648 >        int s = doJoin();
649          if (Thread.interrupted())
650              throw new InterruptedException();
651          if (s < NORMAL) {
# Line 754 | Line 718 | public abstract class ForkJoinTask<V> im
718              }
719          }
720          if (pool != null && dec)
721 <            pool.updateRunningCount(1);
721 >            pool.incrementRunningCount();
722          if (interrupted)
723              throw new InterruptedException();
724 <        int es = status & COMPLETION_MASK;
724 >        int es = status;
725          if (es != NORMAL) {
726              Throwable ex;
727              if (es == CANCELLED)
# Line 770 | Line 734 | public abstract class ForkJoinTask<V> im
734      }
735  
736      /**
773     * 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    /**
737       * Joins this task, without returning its result or throwing an
738       * exception. This method may be useful when processing
739       * collections of tasks when some have been cancelled or otherwise
740       * known to have aborted.
741       */
742      public final void quietlyJoin() {
743 <        waitingJoin();
743 >        doJoin();
744      }
745  
746      /**
# Line 824 | Line 751 | public abstract class ForkJoinTask<V> im
751       * known to have aborted.
752       */
753      public final void quietlyInvoke() {
754 <        waitingInvoke();
754 >        doInvoke();
755      }
756  
757      /**
# Line 856 | Line 783 | public abstract class ForkJoinTask<V> im
783       * pre-constructed trees of subtasks in loops.
784       */
785      public void reinitialize() {
786 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
786 >        if (status == EXCEPTIONAL)
787              exceptionMap.remove(this);
788          status = 0;
789      }
# Line 1166 | Line 1093 | public abstract class ForkJoinTask<V> im
1093      private void readObject(java.io.ObjectInputStream s)
1094          throws java.io.IOException, ClassNotFoundException {
1095          s.defaultReadObject();
1169        status |= SIGNAL; // conservatively set external signal
1096          Object ex = s.readObject();
1097          if (ex != null)
1098              setExceptionalCompletion((Throwable) ex);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines