The getNow
method is an instance method which is defined in the CompletableFuture
class. The CompletableFuture
class is defined in the java.util.concurrent
package. This method returns the result of the CompletableFuture
, if it’s available. Otherwise, it returns the passed value.
We can import the CompletableFuture
class by using the following statement:
import java.util.concurrent.CompletableFuture;
public T getNow(T valueIfAbsent)
T valueIfAbsent
: This is the value that needs to be returned if the result of the future is not yet available.This method returns the result of the future, if completed. Otherwise, it returns the passed value.
import java.util.concurrent.*;public class Main {private static String process(){sleep(2000);System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());return "Hello Educative";}private static CompletableFuture<String> createFuture(){return CompletableFuture.supplyAsync(Main::process);}private static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args){CompletableFuture<String> stringCompletableFuture = createFuture();String valueToReturn = "Result not yet available";String value = stringCompletableFuture.getNow(valueToReturn);sleep(1000);System.out.println("Completed Processing. Returned value - " + value);}}
process
, which prints the thread that executes the function, sleeps for one second, and returns a string.createFuture
, which uses the supplyAsync()
method to run the process()
method in the common pool of ForkJoinPool
. This function returns a CompletableFuture
.sleep()
, which makes the current thread sleep for the given amount of milliseconds.CompletableFuture
by invoking the createFuture
method.valueToReturn
to return in case the future’s result is not available.getNow()
method. The valueToReturn
is passed as an argument to the method.getNow()
method.