Future
in Java?The executor service’s submit()
method submits the task to a thread for execution. However, submit()
does not know when the task’s outcome will be available. As a result, the method returns Future
, a reference that can be used to retrieve the task’s outcome when it becomes available.
In other languages, such as Javascript, the idea of Future
is similar to Promise
. Future
reflects the outcome of a calculation that will be completed at a later date.
Hence, Future
is a placeholder used to store the result of an asynchronous computation.
cancel()
methodThe cancel()
method attempts to cancel the execution of a task. The possible outcomes of calling this method are as follows:
cancel()
method is invoked and the task is not yet started, then the task will never get executed.mayInterruptIfRunning
parameter determines whether the task’s thread should be interrupted during the attempt to terminate it.boolean cancel(boolean mayInterruptIfRunning)
boolean mayInterruptIfRunning
: The flag to indicate whether to interrupt the thread executing the task.This method returns true
if the task is successfully canceled. 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);int count = 0;while(!stringFuture.isDone()) {Thread.sleep(200);count++;if(count > 4) stringFuture.cancel(true);}String result = stringFuture.get();System.out.println("Retrieved result from the task - " + result);executorService.shutdown();}}
executor service
.callable
that sleeps for 1000ms and returns a string.submit()
method to submit the callable
to the executor service
. We get a Future
as a result of this operation.4
until the Future
finishes. The moment the counter is greater than 4
, we invoke the cancel()
method on the Future
and pass true
for the mayInterruptIfRunning
parameter.get()
method to retrieve the result of the Future
.Future
on the console.executor service
is shut down.