How to process asynchronously in a custom pool of threads in Java
Overview
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.
Syntax
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
Parameters
Supplier<U> supplier: The task to execute.Executor executor: The executor to execute the task.
Return value
This method returns a new CompletableFuture.
Code
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();}}
Explanation
- Line 1: We import the relevant packages and classes.
- Line 5:We define a single-threaded thread pool called
customExecutorService. - Lines 7-10: We define a function called
processthat prints the thread executing the function, sleep for one second, and returns a string. - Lines 13-14: We define a function called
createFuturethat uses thesupplyAsync()method to run theprocess()method in the given thread pool (or executor) i.ecustomExecutorService. The function returns aCompletableFuture. - Lines 17-23: We define a function called
sleep()that makes the current thread sleep for the given amount of milliseconds. - Line 26: We get the
CompletableFutureby invoking thecreateFuturemethod. - Line 28: Using the
get()method, we retrieve the value returned by the supplier functionprocess. - Line 30: We invoke the sleep function on the main thread.
- Line 32: We print the value returned by the
supplyAsync()method. - Line 34: We shut down the
customExecutorService.