Representing Task Results

A Future<V> object represents the result of a task that is asynchronously executed— that is, it represents the result of a task that is executed sometime in the future after its submission. For example, methods for submitting or scheduling tasks with an executor service return immediately. When a submitted task is executed sometime in the future, its result is returned in a Future<V> object that can be queried to obtain the result. A Future<V> object also provides methods to determine whether the task it represents completed normally or was cancelled (p. 1444).

The API of the Future<V> interface shown below provides references to examples that compute task results.

Click here to view code image

V get() throws InterruptedException, ExecutionException
V get(long timeout, TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException

The first method blocks if necessary for the computation to complete, and then retrieves the result contained in this Future<V> object. In other words, the method does not return unless the task completes execution.

The second method blocks if necessary at most for the duration of the specified timeout in order for the computation to complete, and then retrieves the result contained in this Future<V> object, if one is available.

Calling these methods on a computation that has been cancelled, throws a java.util.concurrent.CancellationException. See Example 23.5, p. 1446.

Click here to view code image

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel the execution of the task this Future<V> object represents.

If this task is already completed or cancelled, or if could not be cancelled, the method has no effect. Otherwise, if this task has not started when the method is called, this task is never run.

If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task is interrupted in an attempt to stop the task. If the mayInterruptIfRunning parameter is true, the thread executing the task is interrupted; otherwise, the task is allowed to complete.

This method returns false if the task could not be cancelled, typically because it has already completed; otherwise, it returns true. However, the return value from this method does not necessarily indicate whether the task is now cancelled. For that purpose, the isCancelled() method should be used. See Example 23.5, p. 1446.

boolean isCancelled()

Returns true if this task was cancelled before it completed normally. See Example 23.5, p. 1446.

boolean isDone()

Returns true if this task completed. Note that completion implies either normal termination, or an exception, or cancellation.