Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement