Print this page


Split Close
Expand all
Collapse all
          --- old/src/share/classes/java/util/concurrent/ForkJoinTask.java
          +++ new/src/share/classes/java/util/concurrent/ForkJoinTask.java
↓ open down ↓ 34 lines elided ↑ open up ↑
  35   35  
  36   36  package java.util.concurrent;
  37   37  
  38   38  import java.io.Serializable;
  39   39  import java.util.Collection;
  40   40  import java.util.Collections;
  41   41  import java.util.List;
  42   42  import java.util.RandomAccess;
  43   43  import java.util.Map;
  44   44  import java.util.WeakHashMap;
       45 +import java.util.concurrent.Callable;
       46 +import java.util.concurrent.CancellationException;
       47 +import java.util.concurrent.ExecutionException;
       48 +import java.util.concurrent.Executor;
       49 +import java.util.concurrent.ExecutorService;
       50 +import java.util.concurrent.Future;
       51 +import java.util.concurrent.RejectedExecutionException;
       52 +import java.util.concurrent.RunnableFuture;
       53 +import java.util.concurrent.TimeUnit;
       54 +import java.util.concurrent.TimeoutException;
  45   55  
  46   56  /**
  47   57   * Abstract base class for tasks that run within a {@link ForkJoinPool}.
  48   58   * A {@code ForkJoinTask} is a thread-like entity that is much
  49   59   * lighter weight than a normal thread.  Huge numbers of tasks and
  50   60   * subtasks may be hosted by a small number of actual threads in a
  51   61   * ForkJoinPool, at the price of some usage limitations.
  52   62   *
  53   63   * <p>A "main" {@code ForkJoinTask} begins execution when submitted
  54   64   * to a {@link ForkJoinPool}.  Once started, it will usually in turn
↓ open down ↓ 67 lines elided ↑ open up ↑
 122  132   * established in a constructor, and then defines a {@code compute}
 123  133   * method that somehow uses the control methods supplied by this base
 124  134   * class. While these methods have {@code public} access (to allow
 125  135   * instances of different task subclasses to call each other's
 126  136   * methods), some of them may only be called from within other
 127  137   * ForkJoinTasks (as may be determined using method {@link
 128  138   * #inForkJoinPool}).  Attempts to invoke them in other contexts
 129  139   * result in exceptions or errors, possibly including
 130  140   * {@code ClassCastException}.
 131  141   *
      142 + * <p>Method {@link #join} and its variants are appropriate for use
      143 + * only when completion dependencies are acyclic; that is, the
      144 + * parallel computation can be described as a directed acyclic graph
      145 + * (DAG). Otherwise, executions may encounter a form of deadlock as
      146 + * tasks cyclically wait for each other.  However, this framework
      147 + * supports other methods and techniques (for example the use of
      148 + * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
      149 + * may be of use in constructing custom subclasses for problems that
      150 + * are not statically structured as DAGs.
      151 + *
 132  152   * <p>Most base support methods are {@code final}, to prevent
 133  153   * overriding of implementations that are intrinsically tied to the
 134  154   * underlying lightweight task scheduling framework.  Developers
 135  155   * creating new basic styles of fork/join processing should minimally
 136  156   * implement {@code protected} methods {@link #exec}, {@link
 137  157   * #setRawResult}, and {@link #getRawResult}, while also introducing
 138  158   * an abstract computational method that can be implemented in its
 139  159   * subclasses, possibly relying on other {@code protected} methods
 140  160   * provided by this class.
 141  161   *
 142  162   * <p>ForkJoinTasks should perform relatively small amounts of
 143  163   * computation. Large tasks should be split into smaller subtasks,
 144  164   * usually via recursive decomposition. As a very rough rule of thumb,
 145  165   * a task should perform more than 100 and less than 10000 basic
 146      - * computational steps. If tasks are too big, then parallelism cannot
 147      - * improve throughput. If too small, then memory and internal task
 148      - * maintenance overhead may overwhelm processing.
      166 + * computational steps, and should avoid indefinite looping. If tasks
      167 + * are too big, then parallelism cannot improve throughput. If too
      168 + * small, then memory and internal task maintenance overhead may
      169 + * overwhelm processing.
 149  170   *
 150  171   * <p>This class provides {@code adapt} methods for {@link Runnable}
 151  172   * and {@link Callable}, that may be of use when mixing execution of
 152  173   * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
 153  174   * of this form, consider using a pool constructed in <em>asyncMode</em>.
 154  175   *
 155  176   * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
 156  177   * used in extensions such as remote execution frameworks. It is
 157  178   * sensible to serialize tasks only before or after, but not during,
 158  179   * execution. Serialization is not relied on during execution itself.
↓ open down ↓ 76 lines elided ↑ open up ↑
 235  256       * Records exception and sets exceptional completion.
 236  257       *
 237  258       * @return status on exit
 238  259       */
 239  260      private void setExceptionalCompletion(Throwable rex) {
 240  261          exceptionMap.put(this, rex);
 241  262          setCompletion(EXCEPTIONAL);
 242  263      }
 243  264  
 244  265      /**
 245      -     * Blocks a worker thread until completion. Called only by
 246      -     * pool. Currently unused -- pool-based waits use timeout
 247      -     * version below.
 248      -     */
 249      -    final void internalAwaitDone() {
 250      -        int s;         // the odd construction reduces lock bias effects
 251      -        while ((s = status) >= 0) {
 252      -            try {
 253      -                synchronized (this) {
 254      -                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
 255      -                        wait();
 256      -                }
 257      -            } catch (InterruptedException ie) {
 258      -                cancelIfTerminating();
 259      -            }
 260      -        }
 261      -    }
 262      -
 263      -    /**
 264  266       * Blocks a worker thread until completed or timed out.  Called
 265  267       * only by pool.
 266      -     *
 267      -     * @return status on exit
 268  268       */
 269      -    final int internalAwaitDone(long millis) {
 270      -        int s;
 271      -        if ((s = status) >= 0) {
 272      -            try {
      269 +    final void internalAwaitDone(long millis, int nanos) {
      270 +        int s = status;
      271 +        if ((s == 0 &&
      272 +             UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL)) ||
      273 +            s > 0)  {
      274 +            try {     // the odd construction reduces lock bias effects
 273  275                  synchronized (this) {
 274      -                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
 275      -                        wait(millis, 0);
      276 +                    if (status > 0)
      277 +                        wait(millis, nanos);
      278 +                    else
      279 +                        notifyAll();
 276  280                  }
 277  281              } catch (InterruptedException ie) {
 278  282                  cancelIfTerminating();
 279  283              }
 280      -            s = status;
 281  284          }
 282      -        return s;
 283  285      }
 284  286  
 285  287      /**
 286  288       * Blocks a non-worker-thread until completion.
 287  289       */
 288  290      private void externalAwaitDone() {
 289      -        int s;
 290      -        while ((s = status) >= 0) {
      291 +        if (status >= 0) {
      292 +            boolean interrupted = false;
 291  293              synchronized (this) {
 292      -                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
 293      -                    boolean interrupted = false;
 294      -                    while (status >= 0) {
      294 +                for (;;) {
      295 +                    int s = status;
      296 +                    if (s == 0)
      297 +                        UNSAFE.compareAndSwapInt(this, statusOffset,
      298 +                                                 0, SIGNAL);
      299 +                    else if (s < 0) {
      300 +                        notifyAll();
      301 +                        break;
      302 +                    }
      303 +                    else {
 295  304                          try {
 296  305                              wait();
 297  306                          } catch (InterruptedException ie) {
 298  307                              interrupted = true;
 299  308                          }
 300  309                      }
 301      -                    if (interrupted)
 302      -                        Thread.currentThread().interrupt();
 303      -                    break;
 304  310                  }
 305  311              }
      312 +            if (interrupted)
      313 +                Thread.currentThread().interrupt();
 306  314          }
 307  315      }
 308  316  
 309  317      /**
      318 +     * Blocks a non-worker-thread until completion or interruption or timeout.
      319 +     */
      320 +    private void externalInterruptibleAwaitDone(boolean timed, long nanos)
      321 +        throws InterruptedException {
      322 +        if (Thread.interrupted())
      323 +            throw new InterruptedException();
      324 +        if (status >= 0) {
      325 +            long startTime = timed ? System.nanoTime() : 0L;
      326 +            synchronized (this) {
      327 +                for (;;) {
      328 +                    long nt;
      329 +                    int s = status;
      330 +                    if (s == 0)
      331 +                        UNSAFE.compareAndSwapInt(this, statusOffset,
      332 +                                                 0, SIGNAL);
      333 +                    else if (s < 0) {
      334 +                        notifyAll();
      335 +                        break;
      336 +                    }
      337 +                    else if (!timed)
      338 +                        wait();
      339 +                    else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
      340 +                        wait(nt / 1000000, (int)(nt % 1000000));
      341 +                    else
      342 +                        break;
      343 +                }
      344 +            }
      345 +        }
      346 +    }
      347 +
      348 +    /**
 310  349       * Unless done, calls exec and records status if completed, but
 311  350       * doesn't wait for completion otherwise. Primary execution method
 312  351       * for ForkJoinWorkerThread.
 313  352       */
 314  353      final void quietlyExec() {
 315  354          try {
 316  355              if (status < 0 || !exec())
 317  356                  return;
 318  357          } catch (Throwable rex) {
 319  358              setExceptionalCompletion(rex);
↓ open down ↓ 8 lines elided ↑ open up ↑
 328  367       * Arranges to asynchronously execute this task.  While it is not
 329  368       * necessarily enforced, it is a usage error to fork a task more
 330  369       * than once unless it has completed and been reinitialized.
 331  370       * Subsequent modifications to the state of this task or any data
 332  371       * it operates on are not necessarily consistently observable by
 333  372       * any thread other than the one executing it unless preceded by a
 334  373       * call to {@link #join} or related methods, or a call to {@link
 335  374       * #isDone} returning {@code true}.
 336  375       *
 337  376       * <p>This method may be invoked only from within {@code
 338      -     * ForkJoinTask} computations (as may be determined using method
      377 +     * ForkJoinPool} computations (as may be determined using method
 339  378       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 340  379       * result in exceptions or errors, possibly including {@code
 341  380       * ClassCastException}.
 342  381       *
 343  382       * @return {@code this}, to simplify usage
 344  383       */
 345  384      public final ForkJoinTask<V> fork() {
 346  385          ((ForkJoinWorkerThread) Thread.currentThread())
 347  386              .pushTask(this);
 348  387          return this;
 349  388      }
 350  389  
 351  390      /**
 352      -     * Returns the result of the computation when it {@link #isDone is done}.
 353      -     * This method differs from {@link #get()} in that
      391 +     * Returns the result of the computation when it {@link #isDone is
      392 +     * done}.  This method differs from {@link #get()} in that
 354  393       * abnormal completion results in {@code RuntimeException} or
 355      -     * {@code Error}, not {@code ExecutionException}.
      394 +     * {@code Error}, not {@code ExecutionException}, and that
      395 +     * interrupts of the calling thread do <em>not</em> cause the
      396 +     * method to abruptly return by throwing {@code
      397 +     * InterruptedException}.
 356  398       *
 357  399       * @return the computed result
 358  400       */
 359  401      public final V join() {
 360  402          quietlyJoin();
 361  403          Throwable ex;
 362  404          if (status < NORMAL && (ex = getException()) != null)
 363  405              UNSAFE.throwException(ex);
 364  406          return getRawResult();
 365  407      }
↓ open down ↓ 21 lines elided ↑ open up ↑
 387  429       * encounters an exception, then this method throws any one of
 388  430       * these exceptions. If any task encounters an exception, the
 389  431       * other may be cancelled. However, the execution status of
 390  432       * individual tasks is not guaranteed upon exceptional return. The
 391  433       * status of each task may be obtained using {@link
 392  434       * #getException()} and related methods to check if they have been
 393  435       * cancelled, completed normally or exceptionally, or left
 394  436       * unprocessed.
 395  437       *
 396  438       * <p>This method may be invoked only from within {@code
 397      -     * ForkJoinTask} computations (as may be determined using method
      439 +     * ForkJoinPool} computations (as may be determined using method
 398  440       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 399  441       * result in exceptions or errors, possibly including {@code
 400  442       * ClassCastException}.
 401  443       *
 402  444       * @param t1 the first task
 403  445       * @param t2 the second task
 404  446       * @throws NullPointerException if any task is null
 405  447       */
 406  448      public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
 407  449          t2.fork();
↓ open down ↓ 7 lines elided ↑ open up ↑
 415  457       * case the exception is rethrown. If more than one task
 416  458       * encounters an exception, then this method throws any one of
 417  459       * these exceptions. If any task encounters an exception, others
 418  460       * may be cancelled. However, the execution status of individual
 419  461       * tasks is not guaranteed upon exceptional return. The status of
 420  462       * each task may be obtained using {@link #getException()} and
 421  463       * related methods to check if they have been cancelled, completed
 422  464       * normally or exceptionally, or left unprocessed.
 423  465       *
 424  466       * <p>This method may be invoked only from within {@code
 425      -     * ForkJoinTask} computations (as may be determined using method
      467 +     * ForkJoinPool} computations (as may be determined using method
 426  468       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 427  469       * result in exceptions or errors, possibly including {@code
 428  470       * ClassCastException}.
 429  471       *
 430  472       * @param tasks the tasks
 431  473       * @throws NullPointerException if any task is null
 432  474       */
 433  475      public static void invokeAll(ForkJoinTask<?>... tasks) {
 434  476          Throwable ex = null;
 435  477          int last = tasks.length - 1;
↓ open down ↓ 34 lines elided ↑ open up ↑
 470  512       * more than one task encounters an exception, then this method
 471  513       * throws any one of these exceptions. If any task encounters an
 472  514       * exception, others may be cancelled. However, the execution
 473  515       * status of individual tasks is not guaranteed upon exceptional
 474  516       * return. The status of each task may be obtained using {@link
 475  517       * #getException()} and related methods to check if they have been
 476  518       * cancelled, completed normally or exceptionally, or left
 477  519       * unprocessed.
 478  520       *
 479  521       * <p>This method may be invoked only from within {@code
 480      -     * ForkJoinTask} computations (as may be determined using method
      522 +     * ForkJoinPool} computations (as may be determined using method
 481  523       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 482  524       * result in exceptions or errors, possibly including {@code
 483  525       * ClassCastException}.
 484  526       *
 485  527       * @param tasks the collection of tasks
 486  528       * @return the tasks argument, to simplify usage
 487  529       * @throws NullPointerException if tasks or any element are null
 488  530       */
 489  531      public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
 490  532          if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
↓ open down ↓ 31 lines elided ↑ open up ↑
 522  564                  }
 523  565              }
 524  566          }
 525  567          if (ex != null)
 526  568              UNSAFE.throwException(ex);
 527  569          return tasks;
 528  570      }
 529  571  
 530  572      /**
 531  573       * Attempts to cancel execution of this task. This attempt will
 532      -     * fail if the task has already completed, has already been
 533      -     * cancelled, or could not be cancelled for some other reason. If
 534      -     * successful, and this task has not started when cancel is
 535      -     * called, execution of this task is suppressed, {@link
 536      -     * #isCancelled} will report true, and {@link #join} will result
 537      -     * in a {@code CancellationException} being thrown.
      574 +     * fail if the task has already completed or could not be
      575 +     * cancelled for some other reason. If successful, and this task
      576 +     * has not started when {@code cancel} is called, execution of
      577 +     * this task is suppressed. After this method returns
      578 +     * successfully, unless there is an intervening call to {@link
      579 +     * #reinitialize}, subsequent calls to {@link #isCancelled},
      580 +     * {@link #isDone}, and {@code cancel} will return {@code true}
      581 +     * and calls to {@link #join} and related methods will result in
      582 +     * {@code CancellationException}.
 538  583       *
 539  584       * <p>This method may be overridden in subclasses, but if so, must
 540      -     * still ensure that these minimal properties hold. In particular,
 541      -     * the {@code cancel} method itself must not throw exceptions.
      585 +     * still ensure that these properties hold. In particular, the
      586 +     * {@code cancel} method itself must not throw exceptions.
 542  587       *
 543  588       * <p>This method is designed to be invoked by <em>other</em>
 544  589       * tasks. To terminate the current task, you can just return or
 545  590       * throw an unchecked exception from its computation method, or
 546  591       * invoke {@link #completeExceptionally}.
 547  592       *
 548      -     * @param mayInterruptIfRunning this value is ignored in the
 549      -     * default implementation because tasks are not
 550      -     * cancelled via interruption
      593 +     * @param mayInterruptIfRunning this value has no effect in the
      594 +     * default implementation because interrupts are not used to
      595 +     * control cancellation.
 551  596       *
 552  597       * @return {@code true} if this task is now cancelled
 553  598       */
 554  599      public boolean cancel(boolean mayInterruptIfRunning) {
 555  600          setCompletion(CANCELLED);
 556  601          return status == CANCELLED;
 557  602      }
 558  603  
 559  604      /**
 560  605       * Cancels, ignoring any exceptions thrown by cancel. Used during
↓ open down ↓ 113 lines elided ↑ open up ↑
 674  719       * retrieves its result.
 675  720       *
 676  721       * @return the computed result
 677  722       * @throws CancellationException if the computation was cancelled
 678  723       * @throws ExecutionException if the computation threw an
 679  724       * exception
 680  725       * @throws InterruptedException if the current thread is not a
 681  726       * member of a ForkJoinPool and was interrupted while waiting
 682  727       */
 683  728      public final V get() throws InterruptedException, ExecutionException {
 684      -        int s;
 685      -        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
      729 +        Thread t = Thread.currentThread();
      730 +        if (t instanceof ForkJoinWorkerThread)
 686  731              quietlyJoin();
 687      -            s = status;
 688      -        }
 689      -        else {
 690      -            while ((s = status) >= 0) {
 691      -                synchronized (this) { // interruptible form of awaitDone
 692      -                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
 693      -                                                 s, SIGNAL)) {
 694      -                        while (status >= 0)
 695      -                            wait();
 696      -                    }
 697      -                }
 698      -            }
 699      -        }
 700      -        if (s < NORMAL) {
      732 +        else
      733 +            externalInterruptibleAwaitDone(false, 0L);
      734 +        int s = status;
      735 +        if (s != NORMAL) {
 701  736              Throwable ex;
 702  737              if (s == CANCELLED)
 703  738                  throw new CancellationException();
 704  739              if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
 705  740                  throw new ExecutionException(ex);
 706  741          }
 707  742          return getRawResult();
 708  743      }
 709  744  
 710  745      /**
↓ open down ↓ 5 lines elided ↑ open up ↑
 716  751       * @return the computed result
 717  752       * @throws CancellationException if the computation was cancelled
 718  753       * @throws ExecutionException if the computation threw an
 719  754       * exception
 720  755       * @throws InterruptedException if the current thread is not a
 721  756       * member of a ForkJoinPool and was interrupted while waiting
 722  757       * @throws TimeoutException if the wait timed out
 723  758       */
 724  759      public final V get(long timeout, TimeUnit unit)
 725  760          throws InterruptedException, ExecutionException, TimeoutException {
      761 +        long nanos = unit.toNanos(timeout);
 726  762          Thread t = Thread.currentThread();
 727      -        ForkJoinPool pool;
 728      -        if (t instanceof ForkJoinWorkerThread) {
 729      -            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
 730      -            if (status >= 0 && w.unpushTask(this))
 731      -                quietlyExec();
 732      -            pool = w.pool;
 733      -        }
      763 +        if (t instanceof ForkJoinWorkerThread)
      764 +            ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
 734  765          else
 735      -            pool = null;
 736      -        /*
 737      -         * Timed wait loop intermixes cases for FJ (pool != null) and
 738      -         * non FJ threads. For FJ, decrement pool count but don't try
 739      -         * for replacement; increment count on completion. For non-FJ,
 740      -         * deal with interrupts. This is messy, but a little less so
 741      -         * than is splitting the FJ and nonFJ cases.
 742      -         */
 743      -        boolean interrupted = false;
 744      -        boolean dec = false; // true if pool count decremented
 745      -        long nanos = unit.toNanos(timeout);
 746      -        for (;;) {
 747      -            if (pool == null && Thread.interrupted()) {
 748      -                interrupted = true;
 749      -                break;
 750      -            }
 751      -            int s = status;
 752      -            if (s < 0)
 753      -                break;
 754      -            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
 755      -                long startTime = System.nanoTime();
 756      -                long nt; // wait time
 757      -                while (status >= 0 &&
 758      -                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
 759      -                    if (pool != null && !dec)
 760      -                        dec = pool.tryDecrementRunningCount();
 761      -                    else {
 762      -                        long ms = nt / 1000000;
 763      -                        int ns = (int) (nt % 1000000);
 764      -                        try {
 765      -                            synchronized (this) {
 766      -                                if (status >= 0)
 767      -                                    wait(ms, ns);
 768      -                            }
 769      -                        } catch (InterruptedException ie) {
 770      -                            if (pool != null)
 771      -                                cancelIfTerminating();
 772      -                            else {
 773      -                                interrupted = true;
 774      -                                break;
 775      -                            }
 776      -                        }
 777      -                    }
 778      -                }
 779      -                break;
 780      -            }
 781      -        }
 782      -        if (pool != null && dec)
 783      -            pool.incrementRunningCount();
 784      -        if (interrupted)
 785      -            throw new InterruptedException();
 786      -        int es = status;
 787      -        if (es != NORMAL) {
      766 +            externalInterruptibleAwaitDone(true, nanos);
      767 +        int s = status;
      768 +        if (s != NORMAL) {
 788  769              Throwable ex;
 789      -            if (es == CANCELLED)
      770 +            if (s == CANCELLED)
 790  771                  throw new CancellationException();
 791      -            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
      772 +            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
 792  773                  throw new ExecutionException(ex);
 793  774              throw new TimeoutException();
 794  775          }
 795  776          return getRawResult();
 796  777      }
 797  778  
 798  779      /**
 799  780       * Joins this task, without returning its result or throwing its
 800  781       * exception. This method may be useful when processing
 801  782       * collections of tasks when some have been cancelled or otherwise
↓ open down ↓ 10 lines elided ↑ open up ↑
 812  793                          completed = exec();
 813  794                      } catch (Throwable rex) {
 814  795                          setExceptionalCompletion(rex);
 815  796                          return;
 816  797                      }
 817  798                      if (completed) {
 818  799                          setCompletion(NORMAL);
 819  800                          return;
 820  801                      }
 821  802                  }
 822      -                w.joinTask(this);
      803 +                w.joinTask(this, false, 0L);
 823  804              }
 824  805          }
 825  806          else
 826  807              externalAwaitDone();
 827  808      }
 828  809  
 829  810      /**
 830  811       * Commences performing this task and awaits its completion if
 831  812       * necessary, without returning its result or throwing its
 832  813       * exception.
↓ open down ↓ 15 lines elided ↑ open up ↑
 848  829      }
 849  830  
 850  831      /**
 851  832       * Possibly executes tasks until the pool hosting the current task
 852  833       * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
 853  834       * be of use in designs in which many tasks are forked, but none
 854  835       * are explicitly joined, instead executing them until all are
 855  836       * processed.
 856  837       *
 857  838       * <p>This method may be invoked only from within {@code
 858      -     * ForkJoinTask} computations (as may be determined using method
      839 +     * ForkJoinPool} computations (as may be determined using method
 859  840       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 860  841       * result in exceptions or errors, possibly including {@code
 861  842       * ClassCastException}.
 862  843       */
 863  844      public static void helpQuiesce() {
 864  845          ((ForkJoinWorkerThread) Thread.currentThread())
 865  846              .helpQuiescePool();
 866  847      }
 867  848  
 868  849      /**
 869  850       * Resets the internal bookkeeping state of this task, allowing a
 870  851       * subsequent {@code fork}. This method allows repeated reuse of
 871  852       * this task, but only if reuse occurs when this task has either
 872  853       * never been forked, or has been forked, then completed and all
 873  854       * outstanding joins of this task have also completed. Effects
 874  855       * under any other usage conditions are not guaranteed.
 875  856       * This method may be useful when executing
 876  857       * pre-constructed trees of subtasks in loops.
      858 +     *
      859 +     * <p>Upon completion of this method, {@code isDone()} reports
      860 +     * {@code false}, and {@code getException()} reports {@code
      861 +     * null}. However, the value returned by {@code getRawResult} is
      862 +     * unaffected. To clear this value, you can invoke {@code
      863 +     * setRawResult(null)}.
 877  864       */
 878  865      public void reinitialize() {
 879  866          if (status == EXCEPTIONAL)
 880  867              exceptionMap.remove(this);
 881  868          status = 0;
 882  869      }
 883  870  
 884  871      /**
 885  872       * Returns the pool hosting the current task execution, or null
 886  873       * if this task is executing outside of any ForkJoinPool.
↓ open down ↓ 1 lines elided ↑ open up ↑
 888  875       * @see #inForkJoinPool
 889  876       * @return the pool, or {@code null} if none
 890  877       */
 891  878      public static ForkJoinPool getPool() {
 892  879          Thread t = Thread.currentThread();
 893  880          return (t instanceof ForkJoinWorkerThread) ?
 894  881              ((ForkJoinWorkerThread) t).pool : null;
 895  882      }
 896  883  
 897  884      /**
 898      -     * Returns {@code true} if the current thread is executing as a
 899      -     * ForkJoinPool computation.
      885 +     * Returns {@code true} if the current thread is a {@link
      886 +     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
 900  887       *
 901      -     * @return {@code true} if the current thread is executing as a
 902      -     * ForkJoinPool computation, or false otherwise
      888 +     * @return {@code true} if the current thread is a {@link
      889 +     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
      890 +     * or {@code false} otherwise
 903  891       */
 904  892      public static boolean inForkJoinPool() {
 905  893          return Thread.currentThread() instanceof ForkJoinWorkerThread;
 906  894      }
 907  895  
 908  896      /**
 909  897       * Tries to unschedule this task for execution. This method will
 910  898       * typically succeed if this task is the most recently forked task
 911  899       * by the current thread, and has not commenced executing in
 912  900       * another thread.  This method may be useful when arranging
 913  901       * alternative local processing of tasks that could have been, but
 914  902       * were not, stolen.
 915  903       *
 916  904       * <p>This method may be invoked only from within {@code
 917      -     * ForkJoinTask} computations (as may be determined using method
      905 +     * ForkJoinPool} computations (as may be determined using method
 918  906       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 919  907       * result in exceptions or errors, possibly including {@code
 920  908       * ClassCastException}.
 921  909       *
 922  910       * @return {@code true} if unforked
 923  911       */
 924  912      public boolean tryUnfork() {
 925  913          return ((ForkJoinWorkerThread) Thread.currentThread())
 926  914              .unpushTask(this);
 927  915      }
 928  916  
 929  917      /**
 930  918       * Returns an estimate of the number of tasks that have been
 931  919       * forked by the current worker thread but not yet executed. This
 932  920       * value may be useful for heuristic decisions about whether to
 933  921       * fork other tasks.
 934  922       *
 935  923       * <p>This method may be invoked only from within {@code
 936      -     * ForkJoinTask} computations (as may be determined using method
      924 +     * ForkJoinPool} computations (as may be determined using method
 937  925       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 938  926       * result in exceptions or errors, possibly including {@code
 939  927       * ClassCastException}.
 940  928       *
 941  929       * @return the number of tasks
 942  930       */
 943  931      public static int getQueuedTaskCount() {
 944  932          return ((ForkJoinWorkerThread) Thread.currentThread())
 945  933              .getQueueSize();
 946  934      }
↓ open down ↓ 2 lines elided ↑ open up ↑
 949  937       * Returns an estimate of how many more locally queued tasks are
 950  938       * held by the current worker thread than there are other worker
 951  939       * threads that might steal them.  This value may be useful for
 952  940       * heuristic decisions about whether to fork other tasks. In many
 953  941       * usages of ForkJoinTasks, at steady state, each worker should
 954  942       * aim to maintain a small constant surplus (for example, 3) of
 955  943       * tasks, and to process computations locally if this threshold is
 956  944       * exceeded.
 957  945       *
 958  946       * <p>This method may be invoked only from within {@code
 959      -     * ForkJoinTask} computations (as may be determined using method
      947 +     * ForkJoinPool} computations (as may be determined using method
 960  948       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
 961  949       * result in exceptions or errors, possibly including {@code
 962  950       * ClassCastException}.
 963  951       *
 964  952       * @return the surplus number of tasks, which may be negative
 965  953       */
 966  954      public static int getSurplusQueuedTaskCount() {
 967  955          return ((ForkJoinWorkerThread) Thread.currentThread())
 968  956              .getEstimatedSurplusTaskCount();
 969  957      }
↓ open down ↓ 37 lines elided ↑ open up ↑
1007  995       * Returns, but does not unschedule or execute, a task queued by
1008  996       * the current thread but not yet executed, if one is immediately
1009  997       * available. There is no guarantee that this task will actually
1010  998       * be polled or executed next. Conversely, this method may return
1011  999       * null even if a task exists but cannot be accessed without
1012 1000       * contention with other threads.  This method is designed
1013 1001       * primarily to support extensions, and is unlikely to be useful
1014 1002       * otherwise.
1015 1003       *
1016 1004       * <p>This method may be invoked only from within {@code
1017      -     * ForkJoinTask} computations (as may be determined using method
     1005 +     * ForkJoinPool} computations (as may be determined using method
1018 1006       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1019 1007       * result in exceptions or errors, possibly including {@code
1020 1008       * ClassCastException}.
1021 1009       *
1022 1010       * @return the next task, or {@code null} if none are available
1023 1011       */
1024 1012      protected static ForkJoinTask<?> peekNextLocalTask() {
1025 1013          return ((ForkJoinWorkerThread) Thread.currentThread())
1026 1014              .peekTask();
1027 1015      }
1028 1016  
1029 1017      /**
1030 1018       * Unschedules and returns, without executing, the next task
1031 1019       * queued by the current thread but not yet executed.  This method
1032 1020       * is designed primarily to support extensions, and is unlikely to
1033 1021       * be useful otherwise.
1034 1022       *
1035 1023       * <p>This method may be invoked only from within {@code
1036      -     * ForkJoinTask} computations (as may be determined using method
     1024 +     * ForkJoinPool} computations (as may be determined using method
1037 1025       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1038 1026       * result in exceptions or errors, possibly including {@code
1039 1027       * ClassCastException}.
1040 1028       *
1041 1029       * @return the next task, or {@code null} if none are available
1042 1030       */
1043 1031      protected static ForkJoinTask<?> pollNextLocalTask() {
1044 1032          return ((ForkJoinWorkerThread) Thread.currentThread())
1045 1033              .pollLocalTask();
1046 1034      }
↓ open down ↓ 2 lines elided ↑ open up ↑
1049 1037       * Unschedules and returns, without executing, the next task
1050 1038       * queued by the current thread but not yet executed, if one is
1051 1039       * available, or if not available, a task that was forked by some
1052 1040       * other thread, if available. Availability may be transient, so a
1053 1041       * {@code null} result does not necessarily imply quiescence
1054 1042       * of the pool this task is operating in.  This method is designed
1055 1043       * primarily to support extensions, and is unlikely to be useful
1056 1044       * otherwise.
1057 1045       *
1058 1046       * <p>This method may be invoked only from within {@code
1059      -     * ForkJoinTask} computations (as may be determined using method
     1047 +     * ForkJoinPool} computations (as may be determined using method
1060 1048       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1061 1049       * result in exceptions or errors, possibly including {@code
1062 1050       * ClassCastException}.
1063 1051       *
1064 1052       * @return a task, or {@code null} if none are available
1065 1053       */
1066 1054      protected static ForkJoinTask<?> pollTask() {
1067 1055          return ((ForkJoinWorkerThread) Thread.currentThread())
1068 1056              .pollTask();
1069 1057      }
↓ open down ↓ 141 lines elided ↑ open up ↑
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX