What is the rationale for choosing one over the other? Only difference I could infer after reading the documentation is that runAsync takes Runnable as an input parameter and supplyAsync takes Supplier as an input parameter.
This stackoverflow post discusses the motivation behind using Supplier with supplyAsync method but it still does not answer when to prefer one over the other.
The difference between runAsync() and supplyAsync() is that the former returns a Void while supplyAsync() returns a value obtained by the Supplier. Both methods also support a second input argument — a custom Executor to submit tasks to.
You can use the CompletableFuture interface for asynchronous programming. In other words, this interface runs a task in a non-blocking thread. After execution, it notifies the caller thread about the task progress, completion, or any failure.
supplyAsync. Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier.
If you want to run some background task asynchronously and don't want to return anything from the task, then you can use CompletableFuture. runAsync() method. It takes a Runnable object and returns CompletableFuture<Void> . // Run a task specified by a Runnable Object asynchronously.
runAsync takes Runnable as input parameter and returns CompletableFuture<Void>
, which means it does not return any result.
CompletableFuture<Void> run = CompletableFuture.runAsync(()-> System.out.println("hello"));
But suppyAsync takes Supplier as argument and returns the CompletableFuture<U>
with result value, which means it does not take any input parameters but it returns result as output.
CompletableFuture<String> supply = CompletableFuture.supplyAsync(() -> {
System.out.println("Hello");
return "result";
});
System.out.println(supply.get()); //result
Conclusion : So if you want the result to be returned, then choose supplyAsync
or if you just want to run an async action, then choose runAsync
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With