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 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.
boolean isDone()
This method has no parameters.
This method returns True
if the task is completed. Otherwise, it returns False
.
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();}}
submit()
method. We get a Future
as a result of this operation.Future
is done and is not cancelled.get()
method.