What is the Future.isDone() method in Java?

What is Future in Java?

The executor service’s submit() method submits a task to a thread for execution. However, it does not know when the task’s outcome will be made available. As a result, it returns a Future. A Future is a reference that can be used to retrieve the task’s outcome when it becomes available.

In other languages, such as JavaScript, Promise is similar to Future. Promise reflects the outcome of a calculation that will be completed at a later date.

Hence, Future is a placeholder that is used to store the result of an asynchronous computation.

The isDone() method

The isDone() method checks whether the task has been completed or not. The task completion can be due to normal termination of the task, an exception in the execution of the task, or cancellation of the task.

Syntax


boolean isDone()

Parameters

This method has no parameters.

Return value

This method returns True if the task is completed. Otherwise, it returns False.

Code

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> stringCallable = () -> {
Thread.sleep(1000);
return "hello edpresso";
};
Future<String> stringFuture = executorService.submit(stringCallable);
while(!stringFuture.isDone() && !stringFuture.isCancelled()) {
Thread.sleep(200);
System.out.println("Waiting for task completion...");
}
String result = stringFuture.get();
System.out.println("Retrieved result from the task - " + result);
executorService.shutdown();
}
}

Explanation

  • Line 1: We import the relevant packages.
  • Line 6: We define a single-threaded executor service.
  • Lines 8–11: We define a callable, which sleeps for 1000ms and returns a string.
  • Line 13: We submit the callable to the executor service, using the submit() method. We get a Future as a result of this operation.
  • Lines 19–23: We sleep for 200ms, until the Future is done and is not cancelled.
  • Line 20: We retrieve the result of the task, using the get() method.
  • Line 21: We print the result on the console.
  • Line 23: The executor service is shut down.

Free Resources