Common Pitfalls: Ignoring the Returned CompletableFuture
You'll learn why discarding the CompletableFuture returned by runAsync or supplyAsync defeats the purpose of asynchronous programming.
The Critical Mistake
When you call supplyAsync or runAsync, these methods return a CompletableFuture object. This object is your handle to the asynchronous computation—it lets you check status, retrieve results, handle errors, and compose further operations.
A common mistake looks like this:
// WRONG: Future is ignored
CompletableFuture.supplyAsync(() -> expensiveComputation());
// Code continues immediately, no way to get result or handle errors
The computation runs in the background, but you've thrown away your only connection to it. You can't:
- Retrieve the result with
get()orjoin() - Check if it's done with
isDone() - Handle exceptions that occur during execution
- Chain additional operations with
thenApply,thenAccept, etc.
The Analogy
Think of it like mailing an important package but throwing away the tracking number. The package is still being delivered, but you have no way to know when it arrives, if it got lost, or retrieve it from the post office.
The Correct Pattern
Always capture the returned CompletableFuture:
// CORRECT: Future is captured
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> expensiveComputation());
// Now you can access the result
String result = future.join();
// Or handle errors
future.exceptionally(ex -> "fallback value");
Even with runAsync, capture it to detect failures:
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> logOperation());
future.join(); // Throws if logging failed
Key Takeaway: Always capture the CompletableFuture returned by supplyAsync or runAsync—it's your only handle for monitoring completion, accessing results, and handling errors in asynchronous computations.