Java FutureTask

In this tutorial, we will learn about java.util.concurrent.FutureTask class, its methods with explanation, use cases of it and working examples of it.

java.util.concurrent.FutureTask class

FutureTask is a class in the java.util.concurrent package and this represents a computation that may not yet be complete or going to complete. It provides a way to asynchronously execute a task and retrieve its result later, using a Callable or Runnable object.

FutureTask class implemented the Future interface, which represents the result of an asynchronous computation that may not yet be available. A Future can be used to check whether the computation is complete, retrieve the result of the computation, or cancel the computation if it is no longer needed.

FutureTask also implements the java.util.concurrent.RunnableFuture interface, which extends both the Runnable and Future interfaces. This means that a FutureTask can be submitted to an Executor for asynchronous execution, or it can be executed synchronously in a separate thread.

FutureTask class methods

The following are the methods provided by FutureTask and which important for managing the computation of the Task.

cancel(): Attempts to cancel the computation. If the computation has not yet started, it will be cancelled, if it is already running, the attempt may or may not be succeed.

isCancelled(): Returns true if the computation was cancelled before it completed.

isDone(): Returns true if the computation has completed, either by returning a result or by being cancelled.

get(): Waits for the computation to complete and retrieves its result. This method blocks until the result is available.

get(timeout, unit): Waits for the computation to complete and retrieves its result, or throws a TimeoutException if the specified timeout elapses before the result is available.

Importance of FutureTask

  1. FutureTask can be used to execute a time-consuming task in the background, while allowing the main thread to continue executing other tasks. The result of the computation can be retrieved later, when it is needed.
  2. FutureTask provides a cancel() method that can be used to cancel the computation if it is no longer needed. This can be useful in situations where a long-running task needs to be cancelled due to user input or other external factors.
  3. FutureTask can be used to manage dependencies between tasks, by specifying that one task should not start until another task has completed. This can be useful in situations where tasks need to be executed in a specific order, or where the output of one task is required as input for another task.

FutureTask class example 1:

The following is an example of FutureTask

CopiedCopy Code
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Callable;
public class FutureTaskExample {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				Thread.sleep(1000);// Just to keep thread busy
				return 100;
			}
		});
		new Thread(futureTask).start();
		// Wait for the computation to be completed and retrieve the result
		Integer result = futureTask.get();
		System.out.println("The result is: " + result);
	}
}

Output:

The result is: 100

Explanation:

In the above example, we have created a FutureTask object that encapsulates a Callable that returns an Integer value.

We then start a new thread to execute the FutureTask, and use the get() method to wait for the computation to complete and retrieve the result.

FutureTask class example 2:

In this example, we will specify to wait for the task completion certain period to simulate TimeoutException.

CopiedCopy Code
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureTaskTimeOutExample {
	public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
		FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				Thread.sleep(1000);// Just to keep thread busy for 10secs
				return 100;
			}
		});
		new Thread(futureTask).start();
		System.out.println("Waiting for the computation to return in 0.5seconds");
		// Wait for the computation to be completed for 0.5secs
		Integer result = futureTask.get(500L,TimeUnit.MILLISECONDS);
		System.out.println("The result is: " + result);
	}
}

Output :

Waiting for the computation to return in 0.5seconds
Exception in thread "main" java.util.concurrent.TimeoutException
	at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:204)
	at FutureTaskTimeOutExample.main(FutureTaskTimeOutExample.java:19)

Explanation :

We kept the computation thread sleep for 1second and in the get method of computation result kept only to wait 0.5 seconds. Hence caused TimeoutException. This example is demonstrating computation wait time only.

Conclusion:

In this tutorial, we have covered about FutureTask, uses cases of it along with the working examples on how to get the result of future computation tasks.