Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture runAsync vs supplyAsync, when to choose one over the other?

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.

like image 695
Mr Matrix Avatar asked Feb 10 '20 22:02

Mr Matrix


People also ask

What is the difference between runAsync and supplyAsync?

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.

How does CompletableFuture runAsync work?

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.

What does CompletableFuture supplyAsync do?

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.

What is CompletableFuture runAsync in Java?

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.


1 Answers

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.

like image 111
Deadpool Avatar answered Sep 22 '22 02:09

Deadpool