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.50 by dl, Fri Jul 23 13:07:43 2010 UTC vs.
Revision 1.56 by jsr166, Sat Sep 4 00:21:31 2010 UTC

# Line 144 | 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      /*
# Line 164 | Line 165 | public abstract class ForkJoinTask<V> im
165       * them.
166       */
167  
168 <    /** Run status of this task */
168 >    /** The run status of this task */
169      volatile int status; // accessed directly by pool and workers
170  
171      private static final int NORMAL      = -1;
# Line 191 | Line 192 | public abstract class ForkJoinTask<V> im
192       * also clearing signal request bits.
193       *
194       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
194     * @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)
200 >                if (s != 0)
201                      synchronized (this) { notifyAll(); }
202 <                return completion;
202 >                break;
203              }
204          }
205        return s;
205      }
206  
207      /**
208 <     * Record exception and set exceptional completion
208 >     * Records exception and sets exceptional completion.
209 >     *
210       * @return status on exit
211       */
212 <    private int setExceptionalCompletion(Throwable rex) {
212 >    private void setExceptionalCompletion(Throwable rex) {
213          exceptionMap.put(this, rex);
214 <        return setCompletion(EXCEPTIONAL);
214 >        setCompletion(EXCEPTIONAL);
215      }
216  
217      /**
218 <     * Blocks a worker thread until completion. Called only by pool.
218 >     * Blocks a worker thread until completion. Called only by
219 >     * pool. Currently unused -- pool-based waits use timeout
220 >     * version below.
221       */
222      final void internalAwaitDone() {
223          int s;         // the odd construction reduces lock bias effects
# Line 232 | Line 234 | public abstract class ForkJoinTask<V> im
234      }
235  
236      /**
237 <     * Blocks a non-worker-thread until completion.
237 >     * Blocks a worker thread until completed or timed out.  Called
238 >     * only by pool.
239 >     *
240       * @return status on exit
241       */
242 <    private int externalAwaitDone() {
242 >    final int internalAwaitDone(long millis) {
243 >        int s;
244 >        if ((s = status) >= 0) {
245 >            try {
246 >                synchronized(this) {
247 >                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
248 >                        wait(millis, 0);
249 >                }
250 >            } catch (InterruptedException ie) {
251 >                cancelIfTerminating();
252 >            }
253 >            s = status;
254 >        }
255 >        return s;
256 >    }
257 >
258 >    /**
259 >     * Blocks a non-worker-thread until completion.
260 >     */
261 >    private void externalAwaitDone() {
262          int s;
263          while ((s = status) >= 0) {
264              synchronized(this) {
265                  if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
266                      boolean interrupted = false;
267 <                    while ((s = status) >= 0) {
267 >                    while (status >= 0) {
268                          try {
269                              wait();
270                          } catch (InterruptedException ie) {
# Line 254 | Line 277 | public abstract class ForkJoinTask<V> im
277                  }
278              }
279          }
257        return s;
280      }
281  
282      /**
# Line 262 | Line 284 | public abstract class ForkJoinTask<V> im
284       * doesn't wait for completion otherwise. Primary execution method
285       * for ForkJoinWorkerThread.
286       */
287 <    final void tryExec() {
287 >    final void quietlyExec() {
288          try {
289              if (status < 0 || !exec())
290                  return;
# Line 273 | Line 295 | public abstract class ForkJoinTask<V> im
295          setCompletion(NORMAL); // must be outside try block
296      }
297  
276    /**
277     * If not done and this task is next in worker queue, runs it,
278     * else waits for it.
279     * @return status on exit
280     */
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            if ((w = (ForkJoinWorkerThread) t).unpushTask(this)) {
289                boolean completed;
290                try {
291                    completed = exec();
292                } catch (Throwable rex) {
293                    return setExceptionalCompletion(rex);
294                }
295                if (completed)
296                    return setCompletion(NORMAL);
297            }
298            return w.joinTask(this);
299        }
300        return externalAwaitDone();
301    }
302
303    /**
304     * Unless done, calls exec and records status if completed, or
305     * waits for completion otherwise.
306     * @return status on exit
307     */
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            stat = completed ? setCompletion(NORMAL) : doJoin();
318        }
319        return stat;
320    }
321
322    /**
323     * Returns result or throws exception associated with given status.
324     * @param s the status
325     */
326    private V reportResult(int s) {
327        Throwable ex;
328        if (s < NORMAL && (ex = getException()) != null)
329            UNSAFE.throwException(ex);
330        return getRawResult();
331    }
332
298      // public methods
299  
300      /**
# Line 365 | Line 330 | public abstract class ForkJoinTask<V> im
330       * @return the computed result
331       */
332      public final V join() {
333 <        return reportResult(doJoin());
333 >        quietlyJoin();
334 >        Throwable ex;
335 >        if (status < NORMAL && (ex = getException()) != null)
336 >            UNSAFE.throwException(ex);
337 >        return getRawResult();
338      }
339  
340      /**
341       * Commences performing this task, awaits its completion if
342 <     * necessary, and return its result, or throws an (unchecked)
342 >     * necessary, and returns its result, or throws an (unchecked)
343       * exception if the underlying computation did so.
344       *
345       * @return the computed result
346       */
347      public final V invoke() {
348 <        return reportResult(doInvoke());
348 >        quietlyInvoke();
349 >        Throwable ex;
350 >        if (status < NORMAL && (ex = getException()) != null)
351 >            UNSAFE.throwException(ex);
352 >        return getRawResult();
353      }
354  
355      /**
# Line 434 | Line 407 | public abstract class ForkJoinTask<V> im
407              }
408              else if (i != 0)
409                  t.fork();
410 <            else if (t.doInvoke() < NORMAL && ex == null)
411 <                ex = t.getException();
410 >            else {
411 >                t.quietlyInvoke();
412 >                if (ex == null && t.status < NORMAL)
413 >                    ex = t.getException();
414 >            }
415          }
416          for (int i = 1; i <= last; ++i) {
417              ForkJoinTask<?> t = tasks[i];
418              if (t != null) {
419                  if (ex != null)
420                      t.cancel(false);
421 <                else if (t.doJoin() < NORMAL && ex == null)
422 <                    ex = t.getException();
421 >                else {
422 >                    t.quietlyJoin();
423 >                    if (ex == null && t.status < NORMAL)
424 >                        ex = t.getException();
425 >                }
426              }
427          }
428          if (ex != null)
# Line 490 | Line 469 | public abstract class ForkJoinTask<V> im
469              }
470              else if (i != 0)
471                  t.fork();
472 <            else if (t.doInvoke() < NORMAL && ex == null)
473 <                ex = t.getException();
472 >            else {
473 >                t.quietlyInvoke();
474 >                if (ex == null && t.status < NORMAL)
475 >                    ex = t.getException();
476 >            }
477          }
478          for (int i = 1; i <= last; ++i) {
479              ForkJoinTask<?> t = ts.get(i);
480              if (t != null) {
481                  if (ex != null)
482                      t.cancel(false);
483 <                else if (t.doJoin() < NORMAL && ex == null)
484 <                    ex = t.getException();
483 >                else {
484 >                    t.quietlyJoin();
485 >                    if (ex == null && t.status < NORMAL)
486 >                        ex = t.getException();
487 >                }
488              }
489          }
490          if (ex != null)
# Line 532 | Line 517 | public abstract class ForkJoinTask<V> im
517       * @return {@code true} if this task is now cancelled
518       */
519      public boolean cancel(boolean mayInterruptIfRunning) {
520 <        return setCompletion(CANCELLED) == CANCELLED;
520 >        setCompletion(CANCELLED);
521 >        return status == CANCELLED;
522      }
523  
524      /**
525 <     * Cancels, ignoring any exceptions it throws. Used during worker
526 <     * and pool shutdown.
525 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
526 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
527 >     * exceptions, but if it does anyway, we have no recourse during
528 >     * shutdown, so guard against this case.
529       */
530      final void cancelIgnoringExceptions() {
531          try {
# Line 547 | Line 535 | public abstract class ForkJoinTask<V> im
535      }
536  
537      /**
538 <     * Cancels ignoring exceptions if worker is terminating
538 >     * Cancels if current thread is a terminating worker thread,
539 >     * ignoring any exceptions thrown by cancel.
540       */
541      final void cancelIfTerminating() {
542          Thread t = Thread.currentThread();
# Line 645 | Line 634 | public abstract class ForkJoinTask<V> im
634      }
635  
636      public final V get() throws InterruptedException, ExecutionException {
637 <        int s = doJoin();
637 >        quietlyJoin();
638          if (Thread.interrupted())
639              throw new InterruptedException();
640 +        int s = status;
641          if (s < NORMAL) {
642              Throwable ex;
643              if (s == CANCELLED)
# Line 665 | Line 655 | public abstract class ForkJoinTask<V> im
655          if (t instanceof ForkJoinWorkerThread) {
656              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
657              if (status >= 0 && w.unpushTask(this))
658 <                tryExec();
658 >                quietlyExec();
659              pool = w.pool;
660          }
661          else
662              pool = null;
663          /*
664 <         * Timed wait loop intermixes cases for fj (pool != null) and
664 >         * Timed wait loop intermixes cases for FJ (pool != null) and
665           * non FJ threads. For FJ, decrement pool count but don't try
666           * for replacement; increment count on completion. For non-FJ,
667           * deal with interrupts. This is messy, but a little less so
# Line 679 | Line 669 | public abstract class ForkJoinTask<V> im
669           */
670          boolean interrupted = false;
671          boolean dec = false; // true if pool count decremented
672 +        long nanos = unit.toNanos(timeout);
673          for (;;) {
674              if (Thread.interrupted() && pool == null) {
675                  interrupted = true;
# Line 687 | Line 678 | public abstract class ForkJoinTask<V> im
678              int s = status;
679              if (s < 0)
680                  break;
681 <            if (UNSAFE.compareAndSwapInt(this, statusOffset,
691 <                                         s, s | SIGNAL)) {
681 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
682                  long startTime = System.nanoTime();
693                long nanos = unit.toNanos(timeout);
683                  long nt; // wait time
684                  while (status >= 0 &&
685                         (nt = nanos - (System.nanoTime() - startTime)) > 0) {
# Line 734 | Line 723 | public abstract class ForkJoinTask<V> im
723      }
724  
725      /**
726 <     * Joins this task, without returning its result or throwing an
726 >     * Joins this task, without returning its result or throwing its
727       * exception. This method may be useful when processing
728       * collections of tasks when some have been cancelled or otherwise
729       * known to have aborted.
730       */
731      public final void quietlyJoin() {
732 <        doJoin();
732 >        Thread t;
733 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
734 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
735 >            if (status >= 0) {
736 >                if (w.unpushTask(this)) {
737 >                    boolean completed;
738 >                    try {
739 >                        completed = exec();
740 >                    } catch (Throwable rex) {
741 >                        setExceptionalCompletion(rex);
742 >                        return;
743 >                    }
744 >                    if (completed) {
745 >                        setCompletion(NORMAL);
746 >                        return;
747 >                    }
748 >                }
749 >                w.joinTask(this);
750 >            }
751 >        }
752 >        else
753 >            externalAwaitDone();
754      }
755  
756      /**
757       * Commences performing this task and awaits its completion if
758 <     * necessary, without returning its result or throwing an
758 >     * necessary, without returning its result or throwing its
759       * exception. This method may be useful when processing
760       * collections of tasks when some have been cancelled or otherwise
761       * known to have aborted.
762       */
763      public final void quietlyInvoke() {
764 <        doInvoke();
764 >        if (status >= 0) {
765 >            boolean completed;
766 >            try {
767 >                completed = exec();
768 >            } catch (Throwable rex) {
769 >                setExceptionalCompletion(rex);
770 >                return;
771 >            }
772 >            if (completed)
773 >                setCompletion(NORMAL);
774 >            else
775 >                quietlyJoin();
776 >        }
777      }
778  
779      /**
# Line 1073 | Line 1095 | public abstract class ForkJoinTask<V> im
1095      private static final long serialVersionUID = -7721805057305804111L;
1096  
1097      /**
1098 <     * Saves the state to a stream.
1098 >     * Saves the state to a stream (that is, serializes it).
1099       *
1100       * @serialData the current run status and the exception thrown
1101       * during execution, or {@code null} if none
# Line 1086 | Line 1108 | public abstract class ForkJoinTask<V> im
1108      }
1109  
1110      /**
1111 <     * Reconstitutes the instance from a stream.
1111 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1112       *
1113       * @param s the stream
1114       */

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines