What is CompletableFuture.isDone() in Java?

Overview

isDone() is an instance method of the CompletableFuture and is used to check whether the given future has been completed normally, exceptionally, or via cancellation.

The isDone method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, check the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


public boolean isDone()

Parameters

This method has no parameters.

Return value

This method returns true if the string is blank. Otherwise, it returns false.

Code

import java.util.concurrent.*;
public class Main {
private static CompletableFuture<Void> createFuture(){
Runnable runnable = () -> {
sleep(3000);
System.out.println("Hello Educative");
System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());
};
return CompletableFuture.runAsync(runnable);
}
private static void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
CompletableFuture<Void> completableFuture = createFuture();
while(!completableFuture.isDone()) {
System.out.println("Sleeping for 1 sec");
sleep(1000);
}
System.out.println("Completed Processing");
}
}

Explanation

  • Line 1: We import the relevant packages and classes.
  • Line 5: We define a function called createFuture() that submits the runnable to the ForkJoinPool.commonPool() and returns a CompletableFuture.
  • Lines 6-10: We create a runnable that sleeps for three seconds and prints a string and the thread executing it.
  • Lines 14-20: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Line 23: We get the CompletableFuture by invoking the createFuture method.
  • Lines 25-28: We run a while loop where we check if the future is completed using the isDone() method. If the future is not yet completed, we make the main thread sleep for a second.
  • Line 30: We print the string Completed Processing to the console.

Free Resources