Top Description Inners Fields Constructors Methods
java.util.concurrent

public Class FutureTask<V>

extends Object
implements RunnableFuture<V>
Class Inheritance
All Implemented Interfaces
java.util.concurrent.RunnableFuture, java.util.concurrent.Future, java.lang.Runnable
Known Direct Subclasses
java.util.concurrent.ScheduledThreadPoolExecutor.ScheduledFutureTask, java.util.concurrent.ThreadPerTaskExecutor.ThreadBoundFuture, java.util.concurrent.ExecutorCompletionService.QueueingFuture
Type Parameters
<V>
The result type returned by this FutureTask's get methods
Imports
java.lang.invoke.MethodHandles, .VarHandle, java.util.concurrent.locks.LockSupport

A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset).

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.

In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.

Author
Doug Lea
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
FutureTask.WaitNode

Simple linked list nodes to record waiting threads in a Treiber stack.

Field Summary

Modifier and TypeField and Description
private Callable<V>
callable

The underlying callable; nulled out after running

private static final int
private static final int
private static final int
private static final int
private static final int
private static final int
private static final int
private Object
outcome

The result to return or exception to throw from get()

private volatile Thread
runner

The thread running the callable; CASed during run()

private static final VarHandle
private volatile int
state

The run state of this task, initially NEW.

private static final VarHandle
private volatile FutureTask.WaitNode
waiters

Treiber stack of waiting threads

private static final VarHandle

Constructor Summary

AccessConstructor and Description
public
FutureTask(Callable<V>
the callable task
callable
)

Creates a FutureTask that will, upon running, execute the given Callable.

public
FutureTask(Runnable
the runnable task
runnable
,
V
the result to return on successful completion. If you don't need a particular result, consider using constructions of the form: Future<?> f = new FutureTask<Void>(runnable, null)
result
)

Creates a FutureTask that will, upon running, execute the given Runnable, and arrange that get will return the given result on successful completion.

Method Summary

Modifier and TypeMethod and Description
private int

Returns:

state upon completion or at timeout
awaitDone
(boolean
true if use timed waits
timed
,
long
time to wait, if timed
nanos
)

Awaits completion or aborts on interrupt or timeout.

public boolean
cancel(boolean
true if the thread executing this task should be interrupted (if the thread is known to the implementation); otherwise, in-progress tasks are allowed to complete
mayInterruptIfRunning
)

Implements java.util.concurrent.Future.cancel.

Attempts to cancel execution of this task.

protected void
done()

Protected method invoked when this task transitions to state isDone (whether normally or via cancellation).

public Throwable
exceptionNow()

Overrides default java.util.concurrent.Future.exceptionNow.

Returns the exception thrown by the task, without waiting.

private void
finishCompletion()

Removes and signals all waiting threads, invokes done(), and nulls out callable.

public V
get()

Implements java.util.concurrent.Future.get.

Waits if necessary for the computation to complete, and then retrieves its result.

public V
get(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Implements java.util.concurrent.Future.get.

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

private void
handlePossibleCancellationInterrupt(int s)

Ensures that any interrupt from a possible cancel(true) is only delivered to a task while in run or runAndReset.

public boolean
isCancelled()

Implements java.util.concurrent.Future.isCancelled.

Returns true if this task was cancelled before it completed normally.

public boolean
isDone()

Implements java.util.concurrent.Future.isDone.

Returns true if this task completed.

private void
removeWaiter(FutureTask.WaitNode node)

Tries to unlink a timed-out or interrupted wait node to avoid accumulating garbage.

private V
report(int
completed state value
s
)

Returns result or throws exception for completed task.

public V
resultNow()

Overrides default java.util.concurrent.Future.resultNow.

Returns the computed result, without waiting.

public void
run()

Implements java.util.concurrent.RunnableFuture.run.

Sets this Future to the result of its computation unless it has been cancelled.

protected boolean

Returns:

true if successfully run and reset
runAndReset
()

Executes the computation without setting its result, and then resets this future to initial state, failing to do so if the computation encounters an exception or is cancelled.

protected void
set(V
the value
v
)

Sets the result of this future to the given value unless this future has already been set or has been cancelled.

protected void
setException(Throwable
the cause of failure
t
)

Causes this future to report an ExecutionException with the given throwable as its cause, unless this future has already been set or has been cancelled.

public Future.State
state()

Overrides default java.util.concurrent.Future.state.

Returns the computation state.

public String

Returns:

a string representation of this FutureTask
toString
()

Overrides java.lang.Object.toString.

Returns a string representation of this FutureTask.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

callableback to summary
private Callable<V> callable

The underlying callable; nulled out after running

CANCELLEDback to summary
private static final int CANCELLED
COMPLETINGback to summary
private static final int COMPLETING
EXCEPTIONALback to summary
private static final int EXCEPTIONAL
INTERRUPTEDback to summary
private static final int INTERRUPTED
INTERRUPTINGback to summary
private static final int INTERRUPTING
NEWback to summary
private static final int NEW
NORMALback to summary
private static final int NORMAL
outcomeback to summary
private Object outcome

The result to return or exception to throw from get()

runnerback to summary
private volatile Thread runner

The thread running the callable; CASed during run()

RUNNERback to summary
private static final VarHandle RUNNER
stateback to summary
private volatile int state

The run state of this task, initially NEW. The run state transitions to a terminal state only in methods set, setException, and cancel. During completion, state may take on transient values of COMPLETING (while outcome is being set) or INTERRUPTING (only while interrupting the runner to satisfy a cancel(true)). Transitions from these intermediate to final states use cheaper ordered/lazy writes because values are unique and cannot be further modified. Possible state transitions: NEW -> COMPLETING -> NORMAL NEW -> COMPLETING -> EXCEPTIONAL NEW -> CANCELLED NEW -> INTERRUPTING -> INTERRUPTED

STATEback to summary
private static final VarHandle STATE
waitersback to summary
private volatile FutureTask.WaitNode waiters

Treiber stack of waiting threads

WAITERSback to summary
private static final VarHandle WAITERS

Constructor Detail

FutureTaskback to summary
public FutureTask(Callable<V> callable)

Creates a FutureTask that will, upon running, execute the given Callable.

Parameters
callable:Callable<V>

the callable task

Exceptions
NullPointerException:
if the callable is null
FutureTaskback to summary
public FutureTask(Runnable runnable, V result)

Creates a FutureTask that will, upon running, execute the given Runnable, and arrange that get will return the given result on successful completion.

Parameters
runnable:Runnable

the runnable task

result:V

the result to return on successful completion. If you don't need a particular result, consider using constructions of the form: Future<?> f = new FutureTask<Void>(runnable, null)

Exceptions
NullPointerException:
if the runnable is null

Method Detail

awaitDoneback to summary
private int awaitDone(boolean timed, long nanos) throws InterruptedException

Awaits completion or aborts on interrupt or timeout.

Parameters
timed:boolean

true if use timed waits

nanos:long

time to wait, if timed

Returns:int

state upon completion or at timeout

cancelback to summary
public boolean cancel(boolean mayInterruptIfRunning)

Implements java.util.concurrent.Future.cancel.

Doc from java.util.concurrent.Future.cancel.

Attempts to cancel execution of this task. This method has no effect if the task is already completed or cancelled, or could not be cancelled for some other reason. Otherwise, if this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task (when known by the implementation) is interrupted in an attempt to stop the task.

The return value from this method does not necessarily indicate whether the task is now cancelled; use isCancelled.

Parameters
mayInterruptIfRunning:boolean

true if the thread executing this task should be interrupted (if the thread is known to the implementation); otherwise, in-progress tasks are allowed to complete

Returns:boolean

false if the task could not be cancelled, typically because it has already completed; true otherwise. If two or more threads cause a task to be cancelled, then at least one of them returns true. Implementations may provide stronger guarantees.

doneback to summary
protected void done()

Protected method invoked when this task transitions to state isDone (whether normally or via cancellation). The default implementation does nothing. Subclasses may override this method to invoke completion callbacks or perform bookkeeping. Note that you can query status inside the implementation of this method to determine whether this task has been cancelled.

exceptionNowback to summary
public Throwable exceptionNow()

Overrides default java.util.concurrent.Future.exceptionNow.

Doc from java.util.concurrent.Future.exceptionNow.

Returns the exception thrown by the task, without waiting.

This method is for cases where the caller knows that the task has already completed with an exception.

Returns:Throwable

the exception thrown by the task

Annotations
@Override
finishCompletionback to summary
private void finishCompletion()

Removes and signals all waiting threads, invokes done(), and nulls out callable.

getback to summary
public V get() throws InterruptedException, ExecutionException

Implements java.util.concurrent.Future.get.

Doc from java.util.concurrent.Future.get.

Waits if necessary for the computation to complete, and then retrieves its result.

Returns:V

the computed result

Exceptions
InterruptedException:
if the current thread was interrupted while waiting
ExecutionException:
if the computation threw an exception
CancellationException:
if the computation was cancelled
getback to summary
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

Implements java.util.concurrent.Future.get.

Doc from java.util.concurrent.Future.get.

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Parameters
timeout:long

the maximum time to wait

unit:TimeUnit

the time unit of the timeout argument

Returns:V

the computed result

Exceptions
InterruptedException:
if the current thread was interrupted while waiting
ExecutionException:
if the computation threw an exception
TimeoutException:
if the wait timed out
CancellationException:
if the computation was cancelled
handlePossibleCancellationInterruptback to summary
private void handlePossibleCancellationInterrupt(int s)

Ensures that any interrupt from a possible cancel(true) is only delivered to a task while in run or runAndReset.

isCancelledback to summary
public boolean isCancelled()

Implements java.util.concurrent.Future.isCancelled.

Doc from java.util.concurrent.Future.isCancelled.

Returns true if this task was cancelled before it completed normally.

Returns:boolean

true if this task was cancelled before it completed

isDoneback to summary
public boolean isDone()

Implements java.util.concurrent.Future.isDone.

Doc from java.util.concurrent.Future.isDone.

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

Returns:boolean

true if this task completed

removeWaiterback to summary
private void removeWaiter(FutureTask.WaitNode node)

Tries to unlink a timed-out or interrupted wait node to avoid accumulating garbage. Internal nodes are simply unspliced without CAS since it is harmless if they are traversed anyway by releasers. To avoid effects of unsplicing from already removed nodes, the list is retraversed in case of an apparent race. This is slow when there are a lot of nodes, but we don't expect lists to be long enough to outweigh higher-overhead schemes.

reportback to summary
private V report(int s) throws ExecutionException

Returns result or throws exception for completed task.

Parameters
s:int

completed state value

Annotations
@SuppressWarnings:unchecked
resultNowback to summary
public V resultNow()

Overrides default java.util.concurrent.Future.resultNow.

Doc from java.util.concurrent.Future.resultNow.

Returns the computed result, without waiting.

This method is for cases where the caller knows that the task has already completed successfully, for example when filtering a stream of Future objects for the successful tasks and using a mapping operation to obtain a stream of results.

results = futures.stream() .filter(f -> f.state() == Future.State.SUCCESS) .map(Future::resultNow) .toList();
results = futures.stream()
           .filter(f -> f.state() == Future.State.SUCCESS)
           .map(Future::resultNow)
           .toList();
Returns:V

the computed result

Annotations
@Override
runback to summary
public void run()

Implements java.util.concurrent.RunnableFuture.run.

Doc from java.util.concurrent.RunnableFuture.run.

Sets this Future to the result of its computation unless it has been cancelled.

runAndResetback to summary
protected boolean runAndReset()

Executes the computation without setting its result, and then resets this future to initial state, failing to do so if the computation encounters an exception or is cancelled. This is designed for use with tasks that intrinsically execute more than once.

Returns:boolean

true if successfully run and reset

setback to summary
protected void set(V v)

Sets the result of this future to the given value unless this future has already been set or has been cancelled.

This method is invoked internally by the run method upon successful completion of the computation.

Parameters
v:V

the value

setExceptionback to summary
protected void setException(Throwable t)

Causes this future to report an ExecutionException with the given throwable as its cause, unless this future has already been set or has been cancelled.

This method is invoked internally by the run method upon failure of the computation.

Parameters
t:Throwable

the cause of failure

stateback to summary
public Future.State state()

Overrides default java.util.concurrent.Future.state.

Doc from java.util.concurrent.Future.state.

Returns the computation state.

Returns:Future.State

the computation state

Annotations
@Override
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Returns a string representation of this FutureTask.

Implementation Specification

The default implementation returns a string identifying this FutureTask, as well as its completion state. The state, in brackets, contains one of the strings "Completed Normally", "Completed Exceptionally", "Cancelled", or "Not completed".

Returns:String

a string representation of this FutureTask

java.util.concurrent back to summary

pack-priv final Class FutureTask.WaitNode

extends Object
Class Inheritance

Simple linked list nodes to record waiting threads in a Treiber stack. See other classes such as Phaser and SynchronousQueue for more detailed explanation.

Field Summary

Modifier and TypeField and Description
pack-priv volatile FutureTask.WaitNode
pack-priv volatile Thread

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

nextback to summary
pack-priv volatile FutureTask.WaitNode next
threadback to summary
pack-priv volatile Thread thread

Constructor Detail

WaitNodeback to summary
pack-priv WaitNode()