Course contentsShow
← Java
Lesson 2792 of 2,87051. CompletableFutureFree lesson

When to Use supplyAsync vs runAsync

Compare supplyAsync and runAsync to choose the right method based on whether your task produces a result.

When to Use supplyAsync vs runAsync

You'll learn: How to choose between supplyAsync and runAsync based on whether your asynchronous task produces a result you need.

The Core Decision Point

The choice between supplyAsync and runAsync boils down to one simple question: Does your task produce a value you care about?

  • supplyAsync: Use when your task computes and returns a result
  • runAsync: Use when your task performs an action with no meaningful return value

Think of It Like Restaurant Orders

Imagine you're managing a restaurant:

  • supplyAsync is like sending a chef to prepare a dish — you're waiting for food (a result) to come back
  • runAsync is like asking someone to sweep the floor — the action matters, but you don't need anything back

Practical Guidelines

Use supplyAsync when:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    return calculatePrice();  // Returns a value you'll use
});

Use runAsync when:

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    logEvent();  // Pure side effect, no return value
});

Type Signatures Tell the Story

  • supplyAsync takes a Supplier<U> and returns CompletableFuture<U>
  • runAsync takes a Runnable and returns CompletableFuture<Void>

The Void type in runAsync's return is Java's way of saying "this completes, but produces no useful value."

Common Use Cases

Choose supplyAsync for: Database queries, API calls, complex calculations, file reading — anything producing data.

Choose runAsync for: Logging, sending notifications, cache updates, cleanup tasks — actions without meaningful results.

Key Takeaway: Use supplyAsync when you need a result from your asynchronous task; use runAsync for fire-and-forget operations that only perform side effects.