Introduction to supplyAsync: Creating Asynchronous Tasks
You'll learn how to launch asynchronous computations that return results using supplyAsync.
The Core Idea
Up until now, you've seen CompletableFuture created manually with completedFuture (already completed) or controlled through complete() methods. But how do you actually start an asynchronous task that computes something in the background?
Enter supplyAsync. This static method creates a CompletableFuture that runs a Supplier<T> asynchronously and returns the computed result. Think of it as "fire off this computation in a background thread and give me a handle to retrieve the result later."
How It Works
The supplyAsync method takes a Supplier<T> (a lambda that produces a value) and immediately returns a CompletableFuture<T>. Behind the scenes, it submits your task to the common ForkJoinPool (by default) and begins executing it asynchronously.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// This runs in a background thread
return "Result from async task";
});
// Main thread continues immediately
System.out.println("Task submitted");
// Later, retrieve the result (blocks if not done)
String result = future.join();
System.out.println(result);
This is fundamentally different from the manual completion approaches—here, the computation starts automatically and runs concurrently while your main thread continues.
Analogy
Think of supplyAsync as ordering takeout: you call the restaurant (supplyAsync), they give you a receipt (CompletableFuture), and they start cooking in the background. You're free to do other things while waiting, then use the receipt to claim your food when it's ready.
Key Takeaway:
supplyAsync creates a CompletableFuture that executes a Supplier asynchronously in a background thread, immediately returning a handle to retrieve the eventual result.