How can we process asynchronously in Java?
supplyAsync() is a CompletableFuture class. It processes and completes tasks asynchronously in a pool of threads.
The supplyAsync method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, we use the following import statement:
import java.util.concurrent.CompletableFuture;
supplyAsync(Supplier<U> supplier)
The supplyAsync method considers the passed Supplier as a task to be completed asynchronously. By default, the task is executed asynchronously in ForkJoinPool.commonPool(). This method returns a new CompletableFuture, and this value is received by invoking the supplied Supplier.
Syntax
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
Parameters
Supplier<U> supplier: This is the task that needs to be executed.
Return value
This method returns a new CompletableFuture.
Code
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;public class Main {private static String process(){sleep(1000);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) throws ExecutionException, InterruptedException {CompletableFuture<String> stringCompletableFuture = createFuture();String value = stringCompletableFuture.get();sleep(3000);System.out.println("Completed Processing. Returned value - " + value);}}
Code explanation
-
Lines 1–2: We import the relevant packages and classes.
-
Lines 6–10: We define a function called
process, which prints the thread that executes this function. The function then sleeps for one second, and returns a string. -
Lines 12–14: We define a function called
createFuture. This function uses thesupplyAsync()method to run theprocess()method in the common pool ofForkJoinPool. This function returns aCompletableFuture. -
Lines 16–22: We define a function called
sleep(), which makes the current thread sleep for the given number of milliseconds. -
Line 25: We get the
CompletableFutureby invoking thecreateFuturemethod. -
Line 27: We retrieve the value that is returned by the
processsupplier function, using theget()method. -
Line 29: We invoke the
sleepfunction on the main thread. -
Line 31: We print the value that is returned by the
supplyAsync()method.