Spec-Zone.ru › OpenJDK 27

Class RecursiveTask<V>

java.lang.Object
java.util.concurrent.ForkJoinTask<V>
java.util.concurrent.RecursiveTask<V>
Type Parameters:
V - the type of the result of the task
All Implemented Interfaces:
Serializable, Future<V>
public abstract class RecursiveTask<V> extends ForkJoinTask<V>
A recursive result-bearing ForkJoinTask.

For example, here is a task-based program for computing Factorials:

import java.util.concurrent.RecursiveTask;
import java.math.BigInteger;
public class Factorial {
  static class FactorialTask extends RecursiveTask<BigInteger> {
    private final int from, to;
    FactorialTask(int from, int to) { this.from = from; this.to = to; }
    protected BigInteger compute() {
      int range = to - from;
      if (range == 0) {                       // base case
        return BigInteger.valueOf(from);
      } else if (range == 1) {                // too small to parallelize
        return BigInteger.valueOf(from).multiply(BigInteger.valueOf(to));
      } else {                                // split in half
        int mid = from + range / 2;
        FactorialTask leftTask = new FactorialTask(from, mid);
        leftTask.fork();         // perform about half the work locally
        return new FactorialTask(mid + 1, to).compute()
               .multiply(leftTask.join());
      }
    }
  }
  static BigInteger factorial(int n) { // uses ForkJoinPool.commonPool()
    return (n <= 1) ? BigInteger.ONE : new FactorialTask(1, n).invoke();
  }
  public static void main(String[] args) {
    System.out.println(factorial(Integer.parseInt(args[0])));
  }
}
Since:
1.7
See Also:
  • Serialized Form

Nested Class Summary

Nested classes/interfaces declared in interface Future

Future.State
Modifier and Type Interface Description
static enum  Future.State
Represents the computation state.

Constructor Summary

Constructor Description
RecursiveTask()
Constructor for subclasses to call.

Method Summary

Modifier and Type Method Description
protected abstract V compute()
The main computation performed by this task.
protected final boolean exec()
Implements execution conventions for RecursiveTask.
final V getRawResult()
Returns the result that would be returned by ForkJoinTask.join(), even if this task completed abnormally, or null if this task is not known to have been completed.
protected final void setRawResult(V value)
Forces the given value to be returned as a result.

Methods declared in class ForkJoinTask

adapt, adapt, adapt, adaptInterruptible, adaptInterruptible, adaptInterruptible, cancel, compareAndSetForkJoinTaskTag, complete, completeExceptionally, exceptionNow, fork, get, get, getException, getForkJoinTaskTag, getPool, getQueuedTaskCount, getSurplusQueuedTaskCount, helpQuiesce, inForkJoinPool, invoke, invokeAll, invokeAll, invokeAll, isCancelled, isCompletedAbnormally, isCompletedNormally, isDone, join, peekNextLocalTask, pollNextLocalTask, pollSubmission, pollTask, quietlyComplete, quietlyInvoke, quietlyJoin, quietlyJoin, quietlyJoinUninterruptibly, reinitialize, resultNow, setForkJoinTaskTag, state, tryUnfork
Modifier and Type Method Description
static ForkJoinTask<?> adapt(Runnable runnable)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns a null result upon ForkJoinTask.join().
static <T> ForkJoinTask<T> adapt(Runnable runnable, T result)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns the given result upon ForkJoinTask.join().
static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable)
Returns a new ForkJoinTask that performs the call method of the given Callable as its action, and returns its result upon ForkJoinTask.join(), translating any checked exceptions encountered into RuntimeException.
static ForkJoinTask<?> adaptInterruptible(Runnable runnable)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns null upon ForkJoinTask.join(), translating any checked exceptions encountered into RuntimeException.
static <T> ForkJoinTask<T> adaptInterruptible(Runnable runnable, T result)
Returns a new ForkJoinTask that performs the run method of the given Runnable as its action, and returns the given result upon ForkJoinTask.join(), translating any checked exceptions encountered into RuntimeException.
static <T> ForkJoinTask<T> adaptInterruptible(Callable<? extends T> callable)
Returns a new ForkJoinTask that performs the call method of the given Callable as its action, and returns its result upon ForkJoinTask.join(), translating any checked exceptions encountered into RuntimeException.
boolean cancel(boolean mayInterruptIfRunning)
Attempts to cancel execution of this task.
final boolean compareAndSetForkJoinTaskTag(short expect, short update)
Atomically conditionally sets the tag value for this task.
void complete(V value)
Completes this task, and if not already aborted or cancelled, returning the given value as the result of subsequent invocations of join and related operations.
void completeExceptionally(Throwable ex)
Completes this task abnormally, and if not already aborted or cancelled, causes it to throw the given exception upon join and related operations.
Throwable exceptionNow()
Returns the exception thrown by the task, without waiting.
final ForkJoinTask<V> fork()
Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not ForkJoinTask.inForkJoinPool().
final V get()
Waits if necessary for the computation to complete, and then retrieves its result.
final V get(long timeout, TimeUnit unit)
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
final Throwable getException()
Returns the exception thrown by the base computation, or a CancellationException if cancelled, or null if none or if the method has not yet completed.
final short getForkJoinTaskTag()
Returns the tag for this task.
static ForkJoinPool getPool()
Returns the pool hosting the current thread, or null if the current thread is executing outside of any ForkJoinPool.
static int getQueuedTaskCount()
Returns an estimate of the number of tasks that have been forked by the current worker thread but not yet executed.
static int getSurplusQueuedTaskCount()
Returns an estimate of how many more locally queued tasks are held by the current worker thread than there are other worker threads that might steal them, or zero if this thread is not operating in a ForkJoinPool.
static void helpQuiesce()
Possibly executes tasks until the pool hosting the current task is quiescent.
static boolean inForkJoinPool()
Returns true if the current thread is a ForkJoinWorkerThread executing as a ForkJoinPool computation.
final V invoke()
Commences performing this task, awaits its completion if necessary, and returns its result, or throws an (unchecked) RuntimeException or Error if the underlying computation did so.
static <T extends ForkJoinTask<?>>
Collection<T>
invokeAll(Collection<T> tasks)
Forks all tasks in the specified collection, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
static void invokeAll(ForkJoinTask<?>... tasks)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2)
Forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
final boolean isCancelled()
Returns true if this task was cancelled before it completed normally.
final boolean isCompletedAbnormally()
Returns true if this task threw an exception or was cancelled.
final boolean isCompletedNormally()
Returns true if this task completed without throwing an exception and was not cancelled.
final boolean isDone()
Returns true if this task completed.
final V join()
Returns the result of the computation when it is done.
protected static ForkJoinTask<?> peekNextLocalTask()
Returns, but does not unschedule or execute, a task queued by the current thread but not yet executed, if one is immediately available.
protected static ForkJoinTask<?> pollNextLocalTask()
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if the current thread is operating in a ForkJoinPool.
protected static ForkJoinTask<?> pollSubmission()
If the current thread is operating in a ForkJoinPool, unschedules and returns, without executing, a task externally submitted to the pool, if one is available.
protected static ForkJoinTask<?> pollTask()
If the current thread is operating in a ForkJoinPool, unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if one is available, or if not available, a task that was forked by some other thread, if available.
final void quietlyComplete()
Completes this task normally without setting a value.
final void quietlyInvoke()
Commences performing this task and awaits its completion if necessary, without returning its result or throwing its exception.
final void quietlyJoin()
Joins this task, without returning its result or throwing its exception.
final boolean quietlyJoin(long timeout, TimeUnit unit)
Tries to join this task, returning true if it completed (possibly exceptionally) before the given timeout elapsed and the current thread has not been interrupted.
final boolean quietlyJoinUninterruptibly(long timeout, TimeUnit unit)
Tries to join this task, returning true if it completed (possibly exceptionally) before the given timeout elapsed.
void reinitialize()
Resets the internal bookkeeping state of this task, allowing a subsequent fork.
V resultNow()
Returns the computed result, without waiting.
final short setForkJoinTaskTag(short newValue)
Atomically sets the tag value for this task and returns the old value.
Future.State state()
Returns the computation state.
boolean tryUnfork()
Tries to unschedule this task for execution.

Methods declared in class Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Modifier and Type Method Description
protected Object clone()
Creates and returns a copy of this object.
boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
protected void finalize()
Deprecated, for removal: This API element is subject to removal in a future version.
Finalization is deprecated and subject to removal in a future release.
final Class<?> getClass()
Returns the runtime class of this Object.
int hashCode()
Returns a hash code value for this object.
final void notify()
Wakes up a single thread that is waiting on this object's monitor.
final void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
String toString()
Returns a string representation of the object.
final void wait()
Causes the current thread to wait until it is awakened, typically by being notified or interrupted.
final void wait(long timeoutMillis)
Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.
final void wait(long timeoutMillis, int nanos)
Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

Constructor Details

RecursiveTask

public RecursiveTask()
Constructor for subclasses to call.

Method Details

compute

protected abstract V compute()
The main computation performed by this task.
Returns:
the result of the computation

getRawResult

public final V getRawResult()
Description copied from class: ForkJoinTask
Returns the result that would be returned by ForkJoinTask.join(), even if this task completed abnormally, or null if this task is not known to have been completed. This method is designed to aid debugging, as well as to support extensions. Its use in any other context is discouraged.
Specified by:
getRawResult in class ForkJoinTask<V>
Returns:
the result, or null if not completed

setRawResult

protected final void setRawResult(V value)
Description copied from class: ForkJoinTask
Forces the given value to be returned as a result. This method is designed to support extensions, and should not in general be called otherwise.
Specified by:
setRawResult in class ForkJoinTask<V>
Parameters:
value - the value

exec

protected final boolean exec()
Implements execution conventions for RecursiveTask.
Specified by:
exec in class ForkJoinTask<V>
Returns:
true if this task is known to have completed normally

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2026, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

© 1993, 2025, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API