Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
future

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

What is the 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() method

The isCancelled() method checks whether the task was cancelled before it got completed normally.

Syntax


boolean isCancelled()

Parameters

The method has no parameters.

Return value

This method returns true if the task was canceled before it was completed. Otherwise, it returns false.

Code

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();
}
}
Implementation of the "isCancelled()" method

Explanation

  • Lines 1-2: We import the relevant packages.
  • Line 7: We define a single-threaded executor service.
  • Lines 9-12: We define a callable that sleeps for 1000ms and returns a string.
  • Line 14: We submit the callable to the executor service using the submit() method. We get a Future as a result of this operation.
  • Line 16: We initialize a counter to zero.
  • Line 17: We initialize the wait time counter to a random value.
  • Lines 19-23: While the 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.
  • Lines 25-29: We check if the future is in a cancelled state using the 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.
  • Line 32: The executor service is shut down.

RELATED TAGS

java
communitycreator
future

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring