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.46 by dl, Mon Apr 5 15:52:26 2010 UTC vs.
Revision 1.54 by dl, Wed Aug 11 19:44:30 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 SIGNAL_MASK bits set --
158 <     * bit 15 for external (nonFJ) waits, and the rest a count of
159 <     * waiting FJ threads.  (This representation relies on
160 <     * ForkJoinPool max thread limits). Signal counts are not directly
161 <     * incremented by ForkJoinTask methods, but instead via a call to
162 <     * requestSignal within ForkJoinPool.preJoin, once their need is
163 <     * established.
164 <     *
165 <     * Completion of a stolen task with SIGNAL_MASK bits set awakens
169 <     * any waiters via notifyAll. Even though suboptimal for some
170 <     * purposes, we use basic builtin wait/notify to take advantage of
171 <     * "monitor inflation" in JVMs that we would otherwise need to
172 <     * emulate to avoid adding further per-task bookkeeping overhead.
173 <     * We want these monitors to be "fat", i.e., not use biasing or
174 <     * thin-lock techniques, so use some odd coding idioms that tend
175 <     * to avoid them.
176 <     *
177 <     * Note that bits 16-28 are currently unused. Also value
178 <     * 0x80000000 is available as spare completion value.
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.
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;
186 <    private static final int SIGNAL_MASK          = 0x0000ffff;
187 <    private static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
188 <    private static final int EXTERNAL_SIGNAL      = 0x00008000;
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 211 | 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_MASK) != 0) {
215 <                    Thread t = Thread.currentThread();
216 <                    if (t instanceof ForkJoinWorkerThread)
217 <                        ((ForkJoinWorkerThread) t).pool.updateRunningCount
218 <                            (s & INTERNAL_SIGNAL_MASK);
200 >                if (s != 0)
201                      synchronized (this) { notifyAll(); }
202 <                }
221 <                return;
202 >                break;
203              }
204          }
205      }
206  
207      /**
208       * Record exception and set exceptional completion
209 +     * @return status on exit
210       */
211 <    private void setDoneExceptionally(Throwable rex) {
211 >    private void setExceptionalCompletion(Throwable rex) {
212          exceptionMap.put(this, rex);
213          setCompletion(EXCEPTIONAL);
214      }
215  
216      /**
217 <     * Main internal execution method: Unless done, calls exec and
236 <     * records completion.
237 <     *
238 <     * @return true if ran and completed normally
239 <     */
240 <    final boolean tryExec() {
241 <        try {
242 <            if (status < 0 || !exec())
243 <                return false;
244 <        } catch (Throwable rex) {
245 <            setDoneExceptionally(rex);
246 <            return false;
247 <        }
248 <        setCompletion(NORMAL); // must be outside try block
249 <        return true;
250 <    }
251 <
252 <    /**
253 <     * Increments internal signal count (thus requesting signal upon
254 <     * completion) unless already done.  Call only once per join.
255 <     * Used by ForkJoinPool.preJoin.
256 <     *
257 <     * @return status
258 <     */
259 <    final int requestSignal() {
260 <        int s;
261 <        do {} while ((s = status) >= 0 &&
262 <                     !UNSAFE.compareAndSwapInt(this, statusOffset, s, s + 1));
263 <        return s;
264 <    }
265 <    
266 <    /**
267 <     * Sets external signal request unless already done.
268 <     *
269 <     * @return status
270 <     */
271 <    private int requestExternalSignal() {
272 <        int s;
273 <        do {} while ((s = status) >= 0 &&
274 <                     !UNSAFE.compareAndSwapInt(this, statusOffset,
275 <                                               s, s | EXTERNAL_SIGNAL));
276 <        return s;
277 <    }
278 <
279 <    /*
280 <     * Awaiting completion. The four versions, internal vs external X
281 <     * untimed vs timed, have the same overall structure but differ
282 <     * from each other enough to defy simple integration.
283 <     */
284 <
285 <    /**
286 <     * Blocks a worker until this task is done, also maintaining pool
287 <     * and signal counts
217 >     * Blocks a worker thread until completion. Called only by pool.
218       */
219 <    private void awaitDone(ForkJoinWorkerThread w) {
220 <        if (status >= 0) {
221 <            w.pool.preJoin(this);
222 <            while (status >= 0) {
223 <                try { // minimize lock scope
224 <                    synchronized(this) {
225 <                        if (status >= 0)
296 <                            wait();
297 <                        else { // help release; also helps avoid lock-biasing
298 <                            notifyAll();
299 <                            break;
300 <                        }
301 <                    }
302 <                } catch (InterruptedException ie) {
303 <                    cancelIfTerminating();
219 >    final void internalAwaitDone() {
220 >        int s;         // the odd construction reduces lock bias effects
221 >        while ((s = status) >= 0) {
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-ForkJoin thread until this task is done.
234 >     * Blocks a non-worker-thread until completion.
235       */
236      private void externalAwaitDone() {
237 <        if (requestExternalSignal() >= 0) {
238 <            boolean interrupted = false;
239 <            while (status >= 0) {
240 <                try {
241 <                    synchronized(this) {
242 <                        if (status >= 0)
243 <                            wait();
244 <                        else {
245 <                            notifyAll();
246 <                            break;
323 <                        }
324 <                    }
325 <                } catch (InterruptedException ie) {
326 <                    interrupted = true;
327 <                }
328 <            }
329 <            if (interrupted)
330 <                Thread.currentThread().interrupt();
331 <        }
332 <    }
333 <
334 <    /**
335 <     * Blocks a worker until this task is done or timeout elapses
336 <     */
337 <    private void timedAwaitDone(ForkJoinWorkerThread w, long nanos) {
338 <        if (status >= 0) {
339 <            long startTime = System.nanoTime();
340 <            ForkJoinPool pool = w.pool;
341 <            pool.preJoin(this);
342 <            while (status >= 0) {
343 <                long nt = nanos - (System.nanoTime() - startTime);
344 <                if (nt > 0) {
345 <                    long ms = nt / 1000000;
346 <                    int ns = (int) (nt % 1000000);
347 <                    try {
348 <                        synchronized(this) { if (status >= 0) wait(ms, ns); }
349 <                    } catch (InterruptedException ie) {
350 <                        cancelIfTerminating();
351 <                    }
352 <                }
353 <                else {
354 <                    int s; // adjust running count on timeout
355 <                    while ((s = status) >= 0 &&
356 <                           (s & INTERNAL_SIGNAL_MASK) != 0) {
357 <                        if (UNSAFE.compareAndSwapInt(this, statusOffset,
358 <                                                     s, s - 1)) {
359 <                            pool.updateRunningCount(1);
360 <                            break;
237 >        int s;
238 >        while ((s = status) >= 0) {
239 >            synchronized(this) {
240 >                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
241 >                    boolean interrupted = false;
242 >                    while (status >= 0) {
243 >                        try {
244 >                            wait();
245 >                        } catch (InterruptedException ie) {
246 >                            interrupted = true;
247                          }
248                      }
249 +                    if (interrupted)
250 +                        Thread.currentThread().interrupt();
251                      break;
252                  }
253              }
# Line 367 | Line 255 | public abstract class ForkJoinTask<V> im
255      }
256  
257      /**
258 <     * Blocks a non-ForkJoin thread until this task is done or timeout elapses
259 <     */
260 <    private void externalTimedAwaitDone(long nanos) {
373 <        if (requestExternalSignal() >= 0) {
374 <            long startTime = System.nanoTime();
375 <            boolean interrupted = false;
376 <            while (status >= 0) {
377 <                long nt = nanos - (System.nanoTime() - startTime);
378 <                if (nt <= 0)
379 <                    break;
380 <                long ms = nt / 1000000;
381 <                int ns = (int) (nt % 1000000);
382 <                try {
383 <                    synchronized(this) { if (status >= 0) wait(ms, ns); }
384 <                } catch (InterruptedException ie) {
385 <                    interrupted = true;
386 <                }
387 <            }
388 <            if (interrupted)
389 <                Thread.currentThread().interrupt();
390 <        }
391 <    }
392 <
393 <    // reporting results
394 <
395 <    /**
396 <     * Returns result or throws the exception associated with status.
397 <     * Uses Unsafe as a workaround for javac not allowing rethrow of
398 <     * unchecked exceptions.
258 >     * Unless done, calls exec and records status if completed, but
259 >     * doesn't wait for completion otherwise. Primary execution method
260 >     * for ForkJoinWorkerThread.
261       */
262 <    private V reportResult() {
263 <        if ((status & COMPLETION_MASK) < NORMAL) {
264 <            Throwable ex = getException();
265 <            if (ex != null)
266 <                UNSAFE.throwException(ex);
267 <        }
268 <        return getRawResult();
407 <    }
408 <
409 <    /**
410 <     * Returns result or throws exception using j.u.c.Future conventions.
411 <     * Only call when {@code isDone} known to be true or thread known
412 <     * to be interrupted.
413 <     */
414 <    private V reportFutureResult()
415 <        throws InterruptedException, ExecutionException {
416 <        if (Thread.interrupted())
417 <            throw new InterruptedException();
418 <        int s = status & COMPLETION_MASK;
419 <        if (s < NORMAL) {
420 <            Throwable ex;
421 <            if (s == CANCELLED)
422 <                throw new CancellationException();
423 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
424 <                throw new ExecutionException(ex);
262 >    final void quietlyExec() {
263 >        try {
264 >            if (status < 0 || !exec())
265 >                return;
266 >        } catch (Throwable rex) {
267 >            setExceptionalCompletion(rex);
268 >            return;
269          }
270 <        return getRawResult();
427 <    }
428 <
429 <    /**
430 <     * Returns result or throws exception using j.u.c.Future conventions
431 <     * with timeouts.
432 <     */
433 <    private V reportTimedFutureResult()
434 <        throws InterruptedException, ExecutionException, TimeoutException {
435 <        if (Thread.interrupted())
436 <            throw new InterruptedException();
437 <        Throwable ex;
438 <        int s = status & COMPLETION_MASK;
439 <        if (s == NORMAL)
440 <            return getRawResult();
441 <        else if (s == CANCELLED)
442 <            throw new CancellationException();
443 <        else if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
444 <            throw new ExecutionException(ex);
445 <        else
446 <            throw new TimeoutException();
270 >        setCompletion(NORMAL); // must be outside try block
271      }
272  
273      // public methods
# Line 482 | Line 306 | public abstract class ForkJoinTask<V> im
306       */
307      public final V join() {
308          quietlyJoin();
309 <        return reportResult();
309 >        Throwable ex;
310 >        if (status < NORMAL && (ex = getException()) != null)
311 >            UNSAFE.throwException(ex);
312 >        return getRawResult();
313      }
314  
315      /**
# Line 493 | Line 320 | public abstract class ForkJoinTask<V> im
320       * @return the computed result
321       */
322      public final V invoke() {
323 <        if (!tryExec())
324 <            quietlyJoin();
325 <        return reportResult();
323 >        quietlyInvoke();
324 >        Throwable ex;
325 >        if (status < NORMAL && (ex = getException()) != null)
326 >            UNSAFE.throwException(ex);
327 >        return getRawResult();
328      }
329  
330      /**
# Line 555 | Line 384 | public abstract class ForkJoinTask<V> im
384                  t.fork();
385              else {
386                  t.quietlyInvoke();
387 <                if (ex == null)
387 >                if (ex == null && t.status < NORMAL)
388                      ex = t.getException();
389              }
390          }
# Line 566 | Line 395 | public abstract class ForkJoinTask<V> im
395                      t.cancel(false);
396                  else {
397                      t.quietlyJoin();
398 <                    if (ex == null)
398 >                    if (ex == null && t.status < NORMAL)
399                          ex = t.getException();
400                  }
401              }
# Line 617 | Line 446 | public abstract class ForkJoinTask<V> im
446                  t.fork();
447              else {
448                  t.quietlyInvoke();
449 <                if (ex == null)
449 >                if (ex == null && t.status < NORMAL)
450                      ex = t.getException();
451              }
452          }
# Line 628 | Line 457 | public abstract class ForkJoinTask<V> im
457                      t.cancel(false);
458                  else {
459                      t.quietlyJoin();
460 <                    if (ex == null)
460 >                    if (ex == null && t.status < NORMAL)
461                          ex = t.getException();
462                  }
463              }
# Line 664 | 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 681 | 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()) {
518 >            ((ForkJoinWorkerThread) t).isTerminating()) {
519              try {
520                  cancel(false);
521              } catch (Throwable ignore) {
# Line 697 | 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 706 | 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 717 | 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 728 | 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 749 | Line 580 | public abstract class ForkJoinTask<V> im
580       * thrown will be a {@code RuntimeException} with cause {@code ex}.
581       */
582      public void completeExceptionally(Throwable ex) {
583 <        setDoneExceptionally((ex instanceof RuntimeException) ||
584 <                             (ex instanceof Error) ? ex :
585 <                             new RuntimeException(ex));
583 >        setExceptionalCompletion((ex instanceof RuntimeException) ||
584 >                                 (ex instanceof Error) ? ex :
585 >                                 new RuntimeException(ex));
586      }
587  
588      /**
# Line 770 | Line 601 | public abstract class ForkJoinTask<V> im
601          try {
602              setRawResult(value);
603          } catch (Throwable rex) {
604 <            setDoneExceptionally(rex);
604 >            setExceptionalCompletion(rex);
605              return;
606          }
607          setCompletion(NORMAL);
# Line 778 | Line 609 | public abstract class ForkJoinTask<V> im
609  
610      public final V get() throws InterruptedException, ExecutionException {
611          quietlyJoin();
612 <        return reportFutureResult();
612 >        if (Thread.interrupted())
613 >            throw new InterruptedException();
614 >        int s = status;
615 >        if (s < NORMAL) {
616 >            Throwable ex;
617 >            if (s == CANCELLED)
618 >                throw new CancellationException();
619 >            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
620 >                throw new ExecutionException(ex);
621 >        }
622 >        return getRawResult();
623      }
624 <    
624 >
625      public final V get(long timeout, TimeUnit unit)
626          throws InterruptedException, ExecutionException, TimeoutException {
786        long nanos = unit.toNanos(timeout);
627          Thread t = Thread.currentThread();
628 +        ForkJoinPool pool;
629          if (t instanceof ForkJoinWorkerThread) {
630              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
631 <            if (!w.unpushTask(this) || !tryExec())
632 <                timedAwaitDone(w, nanos);
631 >            if (status >= 0 && w.unpushTask(this))
632 >                quietlyExec();
633 >            pool = w.pool;
634          }
635          else
636 <            externalTimedAwaitDone(nanos);
637 <        return reportTimedFutureResult();
638 <    }
639 <
640 <    /**
641 <     * Possibly executes other tasks until this task {@link #isDone is
642 <     * done}, then returns the result of the computation.  This method
643 <     * may be more efficient than {@code join}, but is only applicable
644 <     * when there are no potential dependencies between continuation
645 <     * of the current task and that of any other task that might be
646 <     * executed while helping. (This usually holds for pure
647 <     * divide-and-conquer tasks).
648 <     *
649 <     * <p>This method may be invoked only from within {@code
650 <     * ForkJoinTask} computations (as may be determined using method
651 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
652 <     * result in exceptions or errors, possibly including {@code
653 <     * ClassCastException}.
654 <     *
655 <     * @return the computed result
656 <     */
657 <    public final V helpJoin() {
658 <        quietlyHelpJoin();
659 <        return reportResult();
660 <    }
661 <
662 <    /**
663 <     * Possibly executes other tasks until this task {@link #isDone is
664 <     * done}.  This method may be useful when processing collections
665 <     * of tasks when some have been cancelled or otherwise known to
666 <     * have aborted.
667 <     *
668 <     * <p>This method may be invoked only from within {@code
669 <     * ForkJoinTask} computations (as may be determined using method
670 <     * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
671 <     * result in exceptions or errors, possibly including {@code
672 <     * ClassCastException}.
673 <     */
674 <    public final void quietlyHelpJoin() {
675 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread();
676 <        if (!w.unpushTask(this) || !tryExec()) {
677 <            while (status >= 0) {
678 <                ForkJoinTask<?> t = w.scanWhileJoining(this);
837 <                if (t == null) {
838 <                    if (status >= 0)
839 <                        awaitDone(w);
840 <                    break;
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
646 >        long nanos = unit.toNanos(timeout);
647 >        for (;;) {
648 >            if (Thread.interrupted() && pool == null) {
649 >                interrupted = true;
650 >                break;
651 >            }
652 >            int s = status;
653 >            if (s < 0)
654 >                break;
655 >            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
656 >                long startTime = System.nanoTime();
657 >                long nt; // wait time
658 >                while (status >= 0 &&
659 >                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
660 >                    if (pool != null && !dec)
661 >                        dec = pool.tryDecrementRunningCount();
662 >                    else {
663 >                        long ms = nt / 1000000;
664 >                        int ns = (int) (nt % 1000000);
665 >                        try {
666 >                            synchronized(this) {
667 >                                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 >                            }
677 >                        }
678 >                    }
679                  }
680 <                t.tryExec();
680 >                break;
681              }
682          }
683 +        if (pool != null && dec)
684 +            pool.incrementRunningCount();
685 +        if (interrupted)
686 +            throw new InterruptedException();
687 +        int es = status;
688 +        if (es != NORMAL) {
689 +            Throwable ex;
690 +            if (es == CANCELLED)
691 +                throw new CancellationException();
692 +            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
693 +                throw new ExecutionException(ex);
694 +            throw new TimeoutException();
695 +        }
696 +        return getRawResult();
697      }
698  
699      /**
700 <     * 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 <        Thread t = Thread.currentThread();
707 <        if (t instanceof ForkJoinWorkerThread) {
706 >        Thread t;
707 >        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
708              ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
709 <            if (!w.unpushTask(this) || !tryExec())
710 <                awaitDone(w);
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();
# Line 863 | Line 729 | public abstract class ForkJoinTask<V> im
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 <        if (!tryExec())
739 <            quietlyJoin();
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 902 | 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 1212 | 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();
1215        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1216        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1092          Object ex = s.readObject();
1093          if (ex != null)
1094 <            setDoneExceptionally((Throwable) ex);
1094 >            setExceptionalCompletion((Throwable) ex);
1095      }
1096  
1097      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines