Future
in Java?When the executor service’s submit()
method submits a task to a thread for execution, it does not know the outcome’s availability. As a result, it returns a Future
object, 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
. It reflects the outcome of a calculation that will be completed at a later date.
Hence, a Future
is a placeholder used to store the result of an asynchronous computation.
isCancelled()
methodThe isCancelled()
method checks whether the task was cancelled before it got completed normally.
boolean isCancelled()
The method has no parameters.
This method returns true
if the task was canceled before it was completed. Otherwise, it returns false
.
import java.util.Random;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;int waitTimeCounter = new Random().nextInt(6);while(!stringFuture.isDone()) {Thread.sleep(200);count++;if(count > waitTimeCounter) stringFuture.cancel(true);}if(!stringFuture.isCancelled()){String result = stringFuture.get();System.out.println("Retrieved result from the task - " + result);}else {System.out.println("The future was cancelled");}executorService.shutdown();}}
submit()
method. We get a Future
as a result of this operation.Future
is finishing, we sleep for 200ms and check if the counter is greater than the wait time counter. The moment it is greater than the wait time counter, we invoke the cancel()
method on the future, passing true
for the mayInterruptIfRunning
parameter.isCancelled()
method. If the future is not cancelled, then we retrieve the result of the future using the get()
method and print it on the console.