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.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.4 by dl, Mon Jan 12 17:16:18 2009 UTC

# Line 13 | Line 13 | import sun.misc.Unsafe;
13   import java.lang.reflect.*;
14  
15   /**
16 < * Abstract base class for tasks that run within a ForkJoinPool.  A
17 < * ForkJoinTask is a thread-like entity that is much lighter weight
18 < * than a normal thread.  Huge numbers of tasks and subtasks may be
19 < * hosted by a small number of actual threads in a ForkJoinPool,
20 < * at the price of some usage limitations.
16 > * Abstract base class for tasks that run within a {@link
17 > * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
18 > * lighter weight than a normal thread.  Huge numbers of tasks and
19 > * subtasks may be hosted by a small number of actual threads in a
20 > * ForkJoinPool, at the price of some usage limitations.
21   *
22 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
23 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
24 < * set of restrictions (that are only partially statically
25 < * enforceable) reflecting their intended use as computational tasks
26 < * calculating pure functions or operating on purely isolated objects.
27 < * The primary coordination mechanisms supported for ForkJoinTasks are
28 < * <tt>fork</tt>, that arranges asynchronous execution, and
29 < * <tt>join</tt>, that doesn't proceed until the task's result has
30 < * been computed. (Cancellation is also supported).  The computation
31 < * defined in the <tt>compute</tt> method should avoid
32 < * <tt>synchronized</tt> methods or blocks, and should minimize
33 < * blocking synchronization apart from joining other tasks or using
22 > * <p> A "main" ForkJoinTask begins execution when submitted to a
23 > * {@link ForkJoinPool}. Once started, it will usually in turn start
24 > * other subtasks.  As indicated by the name of this class, many
25 > * programs using ForkJoinTasks employ only methods <code>fork</code>
26 > * and <code>join</code>, or derivatives such as
27 > * <code>invokeAll</code>.  However, this class also provides a number
28 > * of other methods that can come into play in advanced usages, as
29 > * well as extension mechanics that allow support of new forms of
30 > * fork/join processing.
31 > *
32 > * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
33 > * efficiency of ForkJoinTasks stems from a set of restrictions (that
34 > * are only partially statically enforceable) reflecting their
35 > * intended use as computational tasks calculating pure functions or
36 > * operating on purely isolated objects.  The primary coordination
37 > * mechanisms are {@link #fork}, that arranges asynchronous execution,
38 > * and {@link #join}, that doesn't proceed until the task's result has
39 > * been computed.  Computations should avoid <code>synchronized</code>
40 > * methods or blocks, and should minimize other blocking
41 > * synchronization apart from joining other tasks or using
42   * synchronizers such as Phasers that are advertised to cooperate with
43   * fork/join scheduling. Tasks should also not perform blocking IO,
44   * and should ideally access variables that are completely independent
# Line 38 | Line 46 | import java.lang.reflect.*;
46   * restrictions, for example using shared output streams, may be
47   * tolerable in practice, but frequent use may result in poor
48   * performance, and the potential to indefinitely stall if the number
49 < * of threads not waiting for external synchronization becomes
50 < * exhausted. This usage restriction is in part enforced by not
51 < * permitting checked exceptions such as IOExceptions to be
52 < * thrown. However, computations may still encounter unchecked
49 > * of threads not waiting for IO or other external synchronization
50 > * becomes exhausted. This usage restriction is in part enforced by
51 > * not permitting checked exceptions such as <code>IOExceptions</code>
52 > * to be thrown. However, computations may still encounter unchecked
53   * exceptions, that are rethrown to callers attempting join
54   * them. These exceptions may additionally include
55   * RejectedExecutionExceptions stemming from internal resource
56   * exhaustion such as failure to allocate internal task queues.
57   *
58 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
59 < * subclassed.  Instead, you subclass one of the abstract classes that
60 < * support different styles of fork/join processing.  Normally, a
61 < * concrete ForkJoinTask subclass declares fields comprising its
62 < * parameters, established in a constructor, and then defines a
63 < * <tt>compute</tt> method that somehow uses the control methods
64 < * supplied by this base class. While these methods have
65 < * <tt>public</tt> access, some of them may only be called from within
66 < * other ForkJoinTasks. Attempts to invoke them in other contexts
67 < * result in exceptions or errors including ClassCastException.  The
68 < * only way to invoke a "main" driver task is to submit it to a
69 < * ForkJoinPool. Once started, this will usually in turn start other
70 < * subtasks.
58 > * <p>The primary method for awaiting completion and extracting
59 > * results of a task is {@link #join}, but there are several variants:
60 > * The {@link Future#get} methods support interruptible and/or timed
61 > * waits for completion and report results using <code>Future</code>
62 > * conventions. Method {@link #helpJoin} enables callers to actively
63 > * execute other tasks while awaiting joins, which is sometimes more
64 > * efficient but only applies when all subtasks are known to be
65 > * strictly tree-structured. Method {@link #invoke} is semantically
66 > * equivalent to <code>fork(); join()</code> but always attempts to
67 > * begin execution in the current thread. The "<em>quiet</em>" forms
68 > * of these methods do not extract results or report exceptions. These
69 > * may be useful when a set of tasks are being executed, and you need
70 > * to delay processing of results or exceptions until all complete.
71 > * Method <code>invokeAll</code> (available in multiple versions)
72 > * performs the most common form of parallel invocation: forking a set
73 > * of tasks and joining them all.
74 > *
75 > * <p> The ForkJoinTask class is not usually directly subclassed.
76 > * Instead, you subclass one of the abstract classes that support a
77 > * particular style of fork/join processing.  Normally, a concrete
78 > * ForkJoinTask subclass declares fields comprising its parameters,
79 > * established in a constructor, and then defines a <code>compute</code>
80 > * method that somehow uses the control methods supplied by this base
81 > * class. While these methods have <code>public</code> access (to allow
82 > * instances of different task subclasses to call each others
83 > * methods), some of them may only be called from within other
84 > * ForkJoinTasks. Attempts to invoke them in other contexts result in
85 > * exceptions or errors possibly including ClassCastException.
86   *
87 < * <p>Most base support methods are <tt>final</tt> because their
87 > * <p>Most base support methods are <code>final</code> because their
88   * implementations are intrinsically tied to the underlying
89   * lightweight task scheduling framework, and so cannot be overridden.
90   * Developers creating new basic styles of fork/join processing should
91 < * minimally implement protected methods <tt>exec</tt>,
92 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
93 < * introducing an abstract computational method that can be
94 < * implemented in its subclasses. To support such extensions,
95 < * instances of ForkJoinTasks maintain an atomically updated
96 < * <tt>short</tt> representing user-defined control state.  Control
74 < * state is guaranteed initially to be zero, and to be negative upon
75 < * completion, but may otherwise be used for any other control
76 < * purposes, such as maintaining join counts.  The {@link
77 < * ForkJoinWorkerThread} class supports additional inspection and
78 < * tuning methods that can be useful when developing extensions.
91 > * minimally implement <code>protected</code> methods
92 > * <code>exec</code>, <code>setRawResult</code>, and
93 > * <code>getRawResult</code>, while also introducing an abstract
94 > * computational method that can be implemented in its subclasses,
95 > * possibly relying on other <code>protected</code> methods provided
96 > * by this class.
97   *
98   * <p>ForkJoinTasks should perform relatively small amounts of
99   * computations, othewise splitting into smaller tasks. As a very
# Line 84 | Line 102 | import java.lang.reflect.*;
102   * parellelism cannot improve throughput. If too small, then memory
103   * and internal task maintenance overhead may overwhelm processing.
104   *
105 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
106 < * be used in extensions such as remote execution frameworks. However,
107 < * it is in general safe to serialize tasks only before or after, but
105 > * <p>ForkJoinTasks are <code>Serializable</code>, which enables them
106 > * to be used in extensions such as remote execution frameworks. It is
107 > * in general sensible to serialize tasks only before or after, but
108   * not during execution. Serialization is not relied on during
109   * execution itself.
110   */
111   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
112 +
113      /**
114 <     * Status field holding all run status. We pack this into a single
115 <     * int both to minimize footprint overhead and to ensure atomicity
116 <     * (updates are via CAS).
98 <     *
99 <     * Status is initially zero, and takes on nonnegative values until
114 >     * Run control status bits packed into a single int to minimize
115 >     * footprint and to ensure atomicity (via CAS).  Status is
116 >     * initially zero, and takes on nonnegative values until
117       * completed, upon which status holds COMPLETED. CANCELLED, or
118       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
119       * blocking waits by other threads have SIGNAL_MASK bits set --
# Line 144 | Line 161 | public abstract class ForkJoinTask<V> im
161                  (ForkJoinWorkerThread)t : null);
162      }
163  
147    /**
148     * Get pool of current worker thread, or null if not a worker thread
149     */
150    static ForkJoinPool getWorkerPool() {
151        Thread t = Thread.currentThread();
152        return ((t instanceof ForkJoinWorkerThread)?
153                ((ForkJoinWorkerThread)t).pool : null);
154    }
155
164      final boolean casStatus(int cmp, int val) {
165          return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
166      }
# Line 172 | Line 180 | public abstract class ForkJoinTask<V> im
180       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
181       */
182      final void setCompletion(int completion) {
183 <        ForkJoinPool pool = getWorkerPool();
183 >        ForkJoinPool pool = getPool();
184          if (pool != null) {
185              int s; // Clear signal bits while setting completion status
186              do;while ((s = status) >= 0 && !casStatus(s, completion));
# Line 249 | Line 257 | public abstract class ForkJoinTask<V> im
257       * surrounded with pool notifications.
258       * @return status upon exit
259       */
260 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
260 >    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
261          ForkJoinPool pool = w == null? null : w.pool;
262          int s;
263          while ((s = status) >= 0) {
# Line 268 | Line 276 | public abstract class ForkJoinTask<V> im
276       * Timed version of awaitDone
277       * @return status upon exit
278       */
279 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
279 >    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
280          ForkJoinPool pool = w == null? null : w.pool;
281          int s;
282          while ((s = status) >= 0) {
# Line 314 | Line 322 | public abstract class ForkJoinTask<V> im
322          }
323      }
324  
325 +    /**
326 +     * Handle interruptions during waits.
327 +     */
328      private void onInterruptedWait() {
329 <        Thread t = Thread.currentThread();
330 <        if (t instanceof ForkJoinWorkerThread) {
331 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
332 <            if (w.isTerminating())
333 <                cancelIgnoreExceptions();
334 <        }
324 <        else { // re-interrupt
325 <            try {
326 <                t.interrupt();
327 <            } catch (SecurityException ignore) {
328 <            }
329 <        }
329 >        ForkJoinWorkerThread w = getWorker();
330 >        if (w == null)
331 >            Thread.currentThread().interrupt(); // re-interrupt
332 >        else if (w.isTerminating())
333 >            cancelIgnoringExceptions();
334 >        // else if FJworker, ignore interrupt
335      }
336  
337      // Recording and reporting exceptions
# Line 444 | Line 449 | public abstract class ForkJoinTask<V> im
449      /**
450       * Cancel, ignoring any exceptions it throws
451       */
452 <    final void cancelIgnoreExceptions() {
452 >    final void cancelIgnoringExceptions() {
453          try {
454              cancel(false);
455          } catch(Throwable ignore) {
456          }
457      }
458  
459 +    /**
460 +     * Main implementation of helpJoin
461 +     */
462 +    private int busyJoin(ForkJoinWorkerThread w) {
463 +        int s;
464 +        ForkJoinTask<?> t;
465 +        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
466 +            t.quietlyExec();
467 +        return (s >= 0)? awaitDone(w, false) : s; // block if no work
468 +    }
469 +
470      // public methods
471  
472      /**
473       * Arranges to asynchronously execute this task.  While it is not
474       * necessarily enforced, it is a usage error to fork a task more
475       * than once unless it has completed and been reinitialized.  This
476 <     * method may be invoked only from within other ForkJoinTask
476 >     * method may be invoked only from within ForkJoinTask
477       * computations. Attempts to invoke in other contexts result in
478 <     * exceptions or errors including ClassCastException.
478 >     * exceptions or errors possibly including ClassCastException.
479       */
480      public final void fork() {
481          ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
# Line 467 | Line 483 | public abstract class ForkJoinTask<V> im
483  
484      /**
485       * Returns the result of the computation when it is ready.
486 <     * This method differs from <tt>get</tt> in that abnormal
486 >     * This method differs from <code>get</code> in that abnormal
487       * completion results in RuntimeExceptions or Errors, not
488       * ExecutionExceptions.
489       *
# Line 480 | Line 496 | public abstract class ForkJoinTask<V> im
496          return getRawResult();
497      }
498  
483    public final V get() throws InterruptedException, ExecutionException {
484        ForkJoinWorkerThread w = getWorker();
485        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
486            awaitDone(w, true);
487        return reportFutureResult();
488    }
489
490    public final V get(long timeout, TimeUnit unit)
491        throws InterruptedException, ExecutionException, TimeoutException {
492        ForkJoinWorkerThread w = getWorker();
493        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
494            awaitDone(w, unit.toNanos(timeout));
495        return reportTimedFutureResult();
496    }
497
499      /**
500 <     * Possibly executes other tasks until this task is ready, then
501 <     * returns the result of the computation.  This method may be more
501 <     * efficient than <tt>join</tt>, but is only applicable when there
502 <     * are no potemtial dependencies between continuation of the
503 <     * current task and that of any other task that might be executed
504 <     * while helping. (This usually holds for pure divide-and-conquer
505 <     * tasks).
506 <     * @return the computed result
507 <     */
508 <    public final V helpJoin() {
509 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
510 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
511 <            reportException(w.helpJoinTask(this));
512 <        return getRawResult();
513 <    }
514 <
515 <    /**
516 <     * Performs this task, awaits its completion if necessary, and
517 <     * return its result.
500 >     * Commences performing this task, awaits its completion if
501 >     * necessary, and return its result.
502       * @throws Throwable (a RuntimeException, Error, or unchecked
503       * exception) if the underlying computation did so.
504       * @return the computed result
# Line 527 | Line 511 | public abstract class ForkJoinTask<V> im
511      }
512  
513      /**
514 <     * Joins this task, without returning its result or throwing an
515 <     * exception. This method may be useful when processing
516 <     * collections of tasks when some have been cancelled or otherwise
517 <     * known to have aborted.
514 >     * Forks both tasks, returning when <code>isDone</code> holds for
515 >     * both of them or an exception is encountered. This method may be
516 >     * invoked only from within ForkJoinTask computations. Attempts to
517 >     * invoke in other contexts result in exceptions or errors
518 >     * possibly including ClassCastException.
519 >     * @param t1 one task
520 >     * @param t2 the other task
521 >     * @throws NullPointerException if t1 or t2 are null
522 >     * @throws RuntimeException or Error if either task did so.
523       */
524 <    public final void quietlyJoin() {
525 <        if (status >= 0) {
526 <            ForkJoinWorkerThread w = getWorker();
527 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
524 >    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
525 >        t2.fork();
526 >        t1.invoke();
527 >        t2.join();
528      }
529  
530      /**
531 <     * Possibly executes other tasks until this task is ready.
531 >     * Forks the given tasks, returning when <code>isDone</code> holds
532 >     * for all of them. If any task encounters an exception, others
533 >     * may be cancelled.  This method may be invoked only from within
534 >     * ForkJoinTask computations. Attempts to invoke in other contexts
535 >     * result in exceptions or errors possibly including ClassCastException.
536 >     * @param tasks the array of tasks
537 >     * @throws NullPointerException if tasks or any element are null.
538 >     * @throws RuntimeException or Error if any task did so.
539       */
540 <    public final void quietlyHelpJoin() {
541 <        if (status >= 0) {
542 <            ForkJoinWorkerThread w =
543 <                (ForkJoinWorkerThread)(Thread.currentThread());
544 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
545 <                w.helpJoinTask(this);
540 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
541 >        Throwable ex = null;
542 >        int last = tasks.length - 1;
543 >        for (int i = last; i >= 0; --i) {
544 >            ForkJoinTask<?> t = tasks[i];
545 >            if (t == null) {
546 >                if (ex == null)
547 >                    ex = new NullPointerException();
548 >            }
549 >            else if (i != 0)
550 >                t.fork();
551 >            else {
552 >                t.quietlyInvoke();
553 >                if (ex == null)
554 >                    ex = t.getException();
555 >            }
556 >        }
557 >        for (int i = 1; i <= last; ++i) {
558 >            ForkJoinTask<?> t = tasks[i];
559 >            if (t != null) {
560 >                if (ex != null)
561 >                    t.cancel(false);
562 >                else {
563 >                    t.quietlyJoin();
564 >                    if (ex == null)
565 >                        ex = t.getException();
566 >                }
567 >            }
568          }
569 +        if (ex != null)
570 +            rethrowException(ex);
571      }
572  
573      /**
574 <     * Performs this task and awaits its completion if necessary,
575 <     * without returning its result or throwing an exception. This
576 <     * method may be useful when processing collections of tasks when
577 <     * some have been cancelled or otherwise known to have aborted.
574 >     * Forks all tasks in the collection, returning when
575 >     * <code>isDone</code> holds for all of them. If any task
576 >     * encounters an exception, others may be cancelled.  This method
577 >     * may be invoked only from within ForkJoinTask
578 >     * computations. Attempts to invoke in other contexts resul!t in
579 >     * exceptions or errors possibly including ClassCastException.
580 >     * @param tasks the collection of tasks
581 >     * @throws NullPointerException if tasks or any element are null.
582 >     * @throws RuntimeException or Error if any task did so.
583       */
584 <    public final void quietlyInvoke() {
585 <        if (status >= 0 && !tryQuietlyInvoke())
586 <            quietlyJoin();
584 >    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
585 >        if (!(tasks instanceof List)) {
586 >            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
587 >            return;
588 >        }
589 >        List<? extends ForkJoinTask<?>> ts =
590 >            (List<? extends ForkJoinTask<?>>)tasks;
591 >        Throwable ex = null;
592 >        int last = ts.size() - 1;
593 >        for (int i = last; i >= 0; --i) {
594 >            ForkJoinTask<?> t = ts.get(i);
595 >            if (t == null) {
596 >                if (ex == null)
597 >                    ex = new NullPointerException();
598 >            }
599 >            else if (i != 0)
600 >                t.fork();
601 >            else {
602 >                t.quietlyInvoke();
603 >                if (ex == null)
604 >                    ex = t.getException();
605 >            }
606 >        }
607 >        for (int i = 1; i <= last; ++i) {
608 >            ForkJoinTask<?> t = ts.get(i);
609 >            if (t != null) {
610 >                if (ex != null)
611 >                    t.cancel(false);
612 >                else {
613 >                    t.quietlyJoin();
614 >                    if (ex == null)
615 >                        ex = t.getException();
616 >                }
617 >            }
618 >        }
619 >        if (ex != null)
620 >            rethrowException(ex);
621      }
622  
623      /**
# Line 581 | Line 638 | public abstract class ForkJoinTask<V> im
638      }
639  
640      /**
584     * Returns true if this task threw an exception or was cancelled
585     * @return true if this task threw an exception or was cancelled
586     */
587    public final boolean completedAbnormally() {
588        return (status & COMPLETION_MASK) < NORMAL;
589    }
590
591    /**
592     * Returns the exception thrown by the base computation, or a
593     * CancellationException if cancelled, or null if none or if the
594     * method has not yet completed.
595     * @return the exception, or null if none
596     */
597    public final Throwable getException() {
598        int s = status & COMPLETION_MASK;
599        if (s >= NORMAL)
600            return null;
601        if (s == CANCELLED)
602            return new CancellationException();
603        return exceptionMap.get(this);
604    }
605
606    /**
641       * Asserts that the results of this task's computation will not be
642 <     * used. If a cancellation occurs before this task is processed,
643 <     * then its <tt>compute</tt> method will not be executed,
644 <     * <tt>isCancelled</tt> will report true, and <tt>join</tt> will
645 <     * result in a CancellationException being thrown. Otherwise, when
642 >     * used. If a cancellation occurs before atempting to execute this
643 >     * task, then execution will be suppressed, <code>isCancelled</code>
644 >     * will report true, and <code>join</code> will result in a
645 >     * <code>CancellationException</code> being thrown. Otherwise, when
646       * cancellation races with completion, there are no guarantees
647 <     * about whether <tt>isCancelled</tt> will report true, whether
648 <     * <tt>join</tt> will return normally or via an exception, or
647 >     * about whether <code>isCancelled</code> will report true, whether
648 >     * <code>join</code> will return normally or via an exception, or
649       * whether these behaviors will remain consistent upon repeated
650       * invocation.
651       *
# Line 622 | Line 656 | public abstract class ForkJoinTask<V> im
656       * <p> This method is designed to be invoked by <em>other</em>
657       * tasks. To terminate the current task, you can just return or
658       * throw an unchecked exception from its computation method, or
659 <     * invoke <tt>completeExceptionally(someException)</tt>.
659 >     * invoke <code>completeExceptionally</code>.
660       *
661       * @param mayInterruptIfRunning this value is ignored in the
662       * default implementation because tasks are not in general
# Line 636 | Line 670 | public abstract class ForkJoinTask<V> im
670      }
671  
672      /**
673 +     * Returns true if this task threw an exception or was cancelled
674 +     * @return true if this task threw an exception or was cancelled
675 +     */
676 +    public final boolean isCompletedAbnormally() {
677 +        return (status & COMPLETION_MASK) < NORMAL;
678 +    }
679 +
680 +    /**
681 +     * Returns the exception thrown by the base computation, or a
682 +     * CancellationException if cancelled, or null if none or if the
683 +     * method has not yet completed.
684 +     * @return the exception, or null if none
685 +     */
686 +    public final Throwable getException() {
687 +        int s = status & COMPLETION_MASK;
688 +        if (s >= NORMAL)
689 +            return null;
690 +        if (s == CANCELLED)
691 +            return new CancellationException();
692 +        return exceptionMap.get(this);
693 +    }
694 +
695 +    /**
696       * Completes this task abnormally, and if not already aborted or
697       * cancelled, causes it to throw the given exception upon
698 <     * <tt>join</tt> and related operations. This method may be used
698 >     * <code>join</code> and related operations. This method may be used
699       * to induce exceptions in asynchronous tasks, or to force
700 <     * completion of tasks that would not otherwise complete.  This
701 <     * method is overridable, but overridden versions must invoke
702 <     * <tt>super</tt> implementation to maintain guarantees.
700 >     * completion of tasks that would not otherwise complete.  Its use
701 >     * in other situations is likely to be wrong.  This method is
702 >     * overridable, but overridden versions must invoke <code>super</code>
703 >     * implementation to maintain guarantees.
704 >     *
705       * @param ex the exception to throw. If this exception is
706       * not a RuntimeException or Error, the actual exception thrown
707       * will be a RuntimeException with cause ex.
# Line 655 | Line 714 | public abstract class ForkJoinTask<V> im
714  
715      /**
716       * Completes this task, and if not already aborted or cancelled,
717 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
717 >     * returning a <code>null</code> result upon <code>join</code> and related
718       * operations. This method may be used to provide results for
719       * asynchronous tasks, or to provide alternative handling for
720 <     * tasks that would not otherwise complete normally.
720 >     * tasks that would not otherwise complete normally. Its use in
721 >     * other situations is likely to be wrong. This method is
722 >     * overridable, but overridden versions must invoke <code>super</code>
723 >     * implementation to maintain guarantees.
724       *
725       * @param value the result value for this task.
726       */
# Line 672 | Line 734 | public abstract class ForkJoinTask<V> im
734          setNormalCompletion();
735      }
736  
737 <    /**
738 <     * Resets the internal bookkeeping state of this task, allowing a
739 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
740 <     * this task, but only if reuse occurs when this task has either
741 <     * never been forked, or has been forked, then completed and all
742 <     * outstanding joins of this task have also completed. Effects
743 <     * under any other usage conditions are not guaranteed, and are
744 <     * almost surely wrong. This method may be useful when executing
745 <     * pre-constructed trees of subtasks in loops.
746 <     */
747 <    public void reinitialize() {
748 <        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
749 <            exceptionMap.remove(this);
688 <        status = 0;
737 >    public final V get() throws InterruptedException, ExecutionException {
738 >        ForkJoinWorkerThread w = getWorker();
739 >        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
740 >            awaitDone(w, true);
741 >        return reportFutureResult();
742 >    }
743 >
744 >    public final V get(long timeout, TimeUnit unit)
745 >        throws InterruptedException, ExecutionException, TimeoutException {
746 >        ForkJoinWorkerThread w = getWorker();
747 >        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
748 >            awaitDone(w, unit.toNanos(timeout));
749 >        return reportTimedFutureResult();
750      }
751  
752      /**
753 <     * Tries to unschedule this task for execution. This method will
754 <     * typically succeed if this task is the next task that would be
755 <     * executed by the current thread, and will typically fail (return
756 <     * false) otherwise. This method may be useful when arranging
757 <     * faster local processing of tasks that could have been, but were
758 <     * not, stolen.
759 <     * @return true if unforked
753 >     * Possibly executes other tasks until this task is ready, then
754 >     * returns the result of the computation.  This method may be more
755 >     * efficient than <code>join</code>, but is only applicable when
756 >     * there are no potemtial dependencies between continuation of the
757 >     * current task and that of any other task that might be executed
758 >     * while helping. (This usually holds for pure divide-and-conquer
759 >     * tasks). This method may be invoked only from within
760 >     * ForkJoinTask computations. Attempts to invoke in other contexts
761 >     * resul!t in exceptions or errors possibly including ClassCastException.
762 >     * @return the computed result
763       */
764 <    public boolean tryUnfork() {
765 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
764 >    public final V helpJoin() {
765 >        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
766 >        if (status < 0 || !w.unpushTask(this) || !tryExec())
767 >            reportException(busyJoin(w));
768 >        return getRawResult();
769      }
770  
771      /**
772 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
773 <     * of them or an exception is encountered. This method may be
774 <     * invoked only from within other ForkJoinTask
775 <     * computations. Attempts to invoke in other contexts result in
709 <     * exceptions or errors including ClassCastException.
710 <     * @param t1 one task
711 <     * @param t2 the other task
712 <     * @throws NullPointerException if t1 or t2 are null
713 <     * @throws RuntimeException or Error if either task did so.
772 >     * Possibly executes other tasks until this task is ready.  This
773 >     * method may be invoked only from within ForkJoinTask
774 >     * computations. Attempts to invoke in other contexts resul!t in
775 >     * exceptions or errors possibly including ClassCastException.
776       */
777 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
778 <        t2.fork();
779 <        t1.invoke();
780 <        t2.join();
777 >    public final void quietlyHelpJoin() {
778 >        if (status >= 0) {
779 >            ForkJoinWorkerThread w =
780 >                (ForkJoinWorkerThread)(Thread.currentThread());
781 >            if (!w.unpushTask(this) || !tryQuietlyInvoke())
782 >                busyJoin(w);
783 >        }
784      }
785  
786      /**
787 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
788 <     * all of them. If any task encounters an exception, others may be
789 <     * cancelled.  This method may be invoked only from within other
790 <     * ForkJoinTask computations. Attempts to invoke in other contexts
726 <     * result in exceptions or errors including ClassCastException.
727 <     * @param tasks the array of tasks
728 <     * @throws NullPointerException if tasks or any element are null.
729 <     * @throws RuntimeException or Error if any task did so.
787 >     * Joins this task, without returning its result or throwing an
788 >     * exception. This method may be useful when processing
789 >     * collections of tasks when some have been cancelled or otherwise
790 >     * known to have aborted.
791       */
792 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
793 <        Throwable ex = null;
794 <        int last = tasks.length - 1;
795 <        for (int i = last; i >= 0; --i) {
796 <            ForkJoinTask<?> t = tasks[i];
736 <            if (t == null) {
737 <                if (ex == null)
738 <                    ex = new NullPointerException();
739 <            }
740 <            else if (i != 0)
741 <                t.fork();
742 <            else {
743 <                t.quietlyInvoke();
744 <                if (ex == null)
745 <                    ex = t.getException();
746 <            }
747 <        }
748 <        for (int i = 1; i <= last; ++i) {
749 <            ForkJoinTask<?> t = tasks[i];
750 <            if (t != null) {
751 <                if (ex != null)
752 <                    t.cancel(false);
753 <                else {
754 <                    t.quietlyJoin();
755 <                    if (ex == null)
756 <                        ex = t.getException();
757 <                }
758 <            }
792 >    public final void quietlyJoin() {
793 >        if (status >= 0) {
794 >            ForkJoinWorkerThread w = getWorker();
795 >            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
796 >                awaitDone(w, true);
797          }
760        if (ex != null)
761            rethrowException(ex);
798      }
799  
800      /**
801 <     * Forks all tasks in the collection, returning when
802 <     * <tt>isDone</tt> holds for all of them. If any task encounters
803 <     * an exception, others may be cancelled.  This method may be
804 <     * invoked only from within other ForkJoinTask
805 <     * computations. Attempts to invoke in other contexts result in
770 <     * exceptions or errors including ClassCastException.
771 <     * @param tasks the collection of tasks
772 <     * @throws NullPointerException if tasks or any element are null.
773 <     * @throws RuntimeException or Error if any task did so.
801 >     * Commences performing this task and awaits its completion if
802 >     * necessary, without returning its result or throwing an
803 >     * exception. This method may be useful when processing
804 >     * collections of tasks when some have been cancelled or otherwise
805 >     * known to have aborted.
806       */
807 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
808 <        if (!(tasks instanceof List)) {
809 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
778 <            return;
779 <        }
780 <        List<? extends ForkJoinTask<?>> ts =
781 <            (List<? extends ForkJoinTask<?>>)tasks;
782 <        Throwable ex = null;
783 <        int last = ts.size() - 1;
784 <        for (int i = last; i >= 0; --i) {
785 <            ForkJoinTask<?> t = ts.get(i);
786 <            if (t == null) {
787 <                if (ex == null)
788 <                    ex = new NullPointerException();
789 <            }
790 <            else if (i != 0)
791 <                t.fork();
792 <            else {
793 <                t.quietlyInvoke();
794 <                if (ex == null)
795 <                    ex = t.getException();
796 <            }
797 <        }
798 <        for (int i = 1; i <= last; ++i) {
799 <            ForkJoinTask<?> t = ts.get(i);
800 <            if (t != null) {
801 <                if (ex != null)
802 <                    t.cancel(false);
803 <                else {
804 <                    t.quietlyJoin();
805 <                    if (ex == null)
806 <                        ex = t.getException();
807 <                }
808 <            }
809 <        }
810 <        if (ex != null)
811 <            rethrowException(ex);
807 >    public final void quietlyInvoke() {
808 >        if (status >= 0 && !tryQuietlyInvoke())
809 >            quietlyJoin();
810      }
811  
812      /**
# Line 823 | Line 821 | public abstract class ForkJoinTask<V> im
821      }
822  
823      /**
824 +     * Resets the internal bookkeeping state of this task, allowing a
825 +     * subsequent <code>fork</code>. This method allows repeated reuse of
826 +     * this task, but only if reuse occurs when this task has either
827 +     * never been forked, or has been forked, then completed and all
828 +     * outstanding joins of this task have also completed. Effects
829 +     * under any other usage conditions are not guaranteed, and are
830 +     * almost surely wrong. This method may be useful when executing
831 +     * pre-constructed trees of subtasks in loops.
832 +     */
833 +    public void reinitialize() {
834 +        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
835 +            exceptionMap.remove(this);
836 +        status = 0;
837 +    }
838 +
839 +    /**
840 +     * Returns the pool hosting the current task execution, or null
841 +     * if this task is executing outside of any pool.
842 +     * @return the pool, or null if none.
843 +     */
844 +    public static ForkJoinPool getPool() {
845 +        Thread t = Thread.currentThread();
846 +        return ((t instanceof ForkJoinWorkerThread)?
847 +                ((ForkJoinWorkerThread)t).pool : null);
848 +    }
849 +
850 +    /**
851 +     * Tries to unschedule this task for execution. This method will
852 +     * typically succeed if this task is the most recently forked task
853 +     * by the current thread, and has not commenced executing in
854 +     * another thread.  This method may be useful when arranging
855 +     * alternative local processing of tasks that could have been, but
856 +     * were not, stolen. This method may be invoked only from within
857 +     * ForkJoinTask computations. Attempts to invoke in other contexts
858 +     * result in exceptions or errors possibly including ClassCastException.
859 +     * @return true if unforked
860 +     */
861 +    public boolean tryUnfork() {
862 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
863 +    }
864 +
865 +    /**
866 +     * Returns an estimate of the number of tasks that have been
867 +     * forked by the current worker thread but not yet executed. This
868 +     * value may be useful for heuristic decisions about whether to
869 +     * fork other tasks.
870 +     * @return the number of tasks
871 +     */
872 +    public static int getQueuedTaskCount() {
873 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).
874 +            getQueueSize();
875 +    }
876 +
877 +    /**
878       * Returns a estimate of how many more locally queued tasks are
879       * held by the current worker thread than there are other worker
880 <     * threads that might want to steal them.  This value may be
881 <     * useful for heuristic decisions about whether to fork other
882 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
883 <     * worker should aim to maintain a small constant surplus (for
884 <     * example, 3) of tasks, and to process computations locally if
885 <     * this threshold is exceeded.
880 >     * threads that might steal them.  This value may be useful for
881 >     * heuristic decisions about whether to fork other tasks. In many
882 >     * usages of ForkJoinTasks, at steady state, each worker should
883 >     * aim to maintain a small constant surplus (for example, 3) of
884 >     * tasks, and to process computations locally if this threshold is
885 >     * exceeded.
886       * @return the surplus number of tasks, which may be negative
887       */
888 <    public static int surplus() {
888 >    public static int getSurplusQueuedTaskCount() {
889          return ((ForkJoinWorkerThread)(Thread.currentThread()))
890              .getEstimatedSurplusTaskCount();
891      }
892  
893 <    // Extension kit
893 >    // Extension methods
894  
895      /**
896 <     * Returns the result that would be returned by <tt>join</tt>, or
897 <     * null if this task is not known to have been completed.  This
898 <     * method is designed to aid debugging, as well as to support
899 <     * extensions. Its use in any other context is discouraged.
896 >     * Returns the result that would be returned by <code>join</code>,
897 >     * even if this task completed abnormally, or null if this task is
898 >     * not known to have been completed.  This method is designed to
899 >     * aid debugging, as well as to support extensions. Its use in any
900 >     * other context is discouraged.
901       *
902       * @return the result, or null if not completed.
903       */
# Line 865 | Line 918 | public abstract class ForkJoinTask<V> im
918       * called otherwise. The return value controls whether this task
919       * is considered to be done normally. It may return false in
920       * asynchronous actions that require explicit invocations of
921 <     * <tt>complete</tt> to become joinable. It may throw exceptions
921 >     * <code>complete</code> to become joinable. It may throw exceptions
922       * to indicate abnormal exit.
923       * @return true if completed normally
924       * @throws Error or RuntimeException if encountered during computation
925       */
926      protected abstract boolean exec();
927  
928 +    /**
929 +     * Returns, but does not unschedule or execute, the task most
930 +     * recently forked by the current thread but not yet executed, if
931 +     * one is available. There is no guarantee that this task will
932 +     * actually be polled or executed next.
933 +     * This method is designed primarily to support extensions,
934 +     * and is unlikely to be useful otherwise.
935 +     * This method may be invoked only from within
936 +     * ForkJoinTask computations. Attempts to invoke in other contexts
937 +     * result in exceptions or errors possibly including ClassCastException.
938 +     *
939 +     * @return the next task, or null if none are available
940 +     */
941 +    protected static ForkJoinTask<?> peekNextLocalTask() {
942 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
943 +    }
944 +
945 +    /**
946 +     * Unschedules and returns, without executing, the task most
947 +     * recently forked by the current thread but not yet executed.
948 +     * This method is designed primarily to support extensions,
949 +     * and is unlikely to be useful otherwise.
950 +     * This method may be invoked only from within
951 +     * ForkJoinTask computations. Attempts to invoke in other contexts
952 +     * result in exceptions or errors possibly including ClassCastException.
953 +     *
954 +     * @return the next task, or null if none are available
955 +     */
956 +    protected static ForkJoinTask<?> pollNextLocalTask() {
957 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask();
958 +    }
959 +
960 +    /**
961 +     * Unschedules and returns, without executing, the task most
962 +     * recently forked by the current thread but not yet executed, if
963 +     * one is available, or if not available, a task that was forked
964 +     * by some other thread, if available. Availability may be
965 +     * transient, so a <code>null</code> result does not necessarily
966 +     * imply quiecence of the pool this task is operating in.
967 +     * This method is designed primarily to support extensions,
968 +     * and is unlikely to be useful otherwise.
969 +     * This method may be invoked only from within
970 +     * ForkJoinTask computations. Attempts to invoke in other contexts
971 +     * result in exceptions or errors possibly including ClassCastException.
972 +     *
973 +     * @return a task, or null if none are available
974 +     */
975 +    protected static ForkJoinTask<?> pollTask() {
976 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).
977 +            pollTask();
978 +    }
979 +
980      // Serialization support
981  
982      private static final long serialVersionUID = -7721805057305804111L;
# Line 896 | Line 1001 | public abstract class ForkJoinTask<V> im
1001      private void readObject(java.io.ObjectInputStream s)
1002          throws java.io.IOException, ClassNotFoundException {
1003          s.defaultReadObject();
1004 <        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1004 >        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1005 >        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1006          Object ex = s.readObject();
1007          if (ex != null)
1008              setDoneExceptionally((Throwable)ex);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines