supplyAsync()
is a CompletableFuture
class which is used to process/complete tasks asynchronously in a pool of threads.
Refer Future v/s CompletableFuture to learn more about
CompletableFuture
.
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 check the following import statement.
import java.util.concurrent.CompletableFuture;
supplyAsync(Supplier<U> supplier, Executor executor)
This method considers the passed Supplier
as a task that will be completed asynchronously. The task will be executed in the passed executor and the method returns a new CompletableFuture
with the value received by invoking the supplied Supplier
.
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
Supplier<U> supplier
: The task to execute.Executor executor
: The executor to execute the task.This method returns a new CompletableFuture
.
import java.util.concurrent.*; public class Main { static ExecutorService customExecutorService = Executors.newSingleThreadExecutor(); 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, customExecutorService); } 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); customExecutorService.shutdown(); } }
customExecutorService
.process
that prints the thread executing the function, sleep for one second, and returns a string.createFuture
that uses the supplyAsync()
method to run the process()
method in the given thread pool (or executor) i.e customExecutorService
. The function returns a CompletableFuture
.sleep()
that makes the current thread sleep for the given amount of milliseconds.CompletableFuture
by invoking the createFuture
method.get()
method, we retrieve the value returned by the supplier function process
.supplyAsync()
method.customExecutorService
.RELATED TAGS
CONTRIBUTOR
View all Courses