In Java, we use an instance method of the CompletableFuture
class, cancel()
, that 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 has not yet started, the task will not get executed.mayInterruptIfRunning
parameter determines whether the task’s thread should be interrupted during the attempt to terminate it.The cancel()
method is defined in the CompletableFuture
class, which is defined in the java.util.concurrent
package. To import the CompletableFuture
class, we use the following import statement.
import java.util.concurrent.CompletableFuture;
boolean cancel(boolean mayInterruptIfRunning)
boolean mayInterruptIfRunning
: This is 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.Random;import java.util.concurrent.*;public class Main {static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws ExecutionException, InterruptedException {CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {sleep(4000);return "Hello-Educative";});int count = 0;int waitTimeCounter = new Random().nextInt(3);while(!completableFuture.isDone()) {sleep(2000);System.out.println("Waiting...");count++;if(count > waitTimeCounter) completableFuture.cancel(true);}if(!completableFuture.isCancelled()){String result = completableFuture.get();System.out.println("Retrieved result from the task - " + result);}else {System.out.println("The future was cancelled");}}}
sleep()
. It makes the current thread sleep for the given amount of milliseconds.submit()
method to submit the callable to the executor service. We get a CompletableFuture
class as a result of this operation.CompletableFuture
is finishing, we call sleep()
for two seconds and check if the counter is greater than the wait time counter. When it is greater than the wait time counter, we invoke the cancel()
method on the Completablefuture
. Then, we pass true
for the mayInterruptIfRunning
parameter.isCancelled()
method to check if the Completablefuture
class is in a canceled state. If the Completablefuture
is not canceled, we retrieve the result using the get()
method. Finally, we print it on the console.