Choosing Between thenAccept and thenRun
What you'll learn: How to decide whether to use thenAccept or thenRun based on whether you need access to the computation result.
The Decision Criteria
Both thenAccept and thenRun are used for side-effect operations in a CompletableFuture pipeline—they don't transform or produce new values, but rather do something with the result (or simply signal that work is complete). The key difference is straightforward:
- Use
thenAcceptwhen you need to consume the result of the previous stage - Use
thenRunwhen you just need to run an action after completion, regardless of the result
Think of It Like Package Delivery
Imagine you ordered something online:
thenAcceptis like signing for the package and opening it—you need to see what's inside (the result).thenRunis like playing a notification sound after delivery—you don't care what's in the box, just that it arrived.
When to Use Which
Choose thenAccept if:
- You need to log, print, or save the computed result
- You're performing validation or side-effects based on the value
- The result determines what action to take
Choose thenRun if:
- You're tracking completion for metrics or logging ("task finished")
- You're releasing resources or cleanup that doesn't depend on the result
- You're triggering unrelated workflows after completion
CompletableFuture.supplyAsync(() -> fetchUserData())
.thenAccept(user -> System.out.println("Welcome, " + user.getName())) // Need the user
.thenRun(() -> System.out.println("Notification sent")); // Just completion
Key Takeaway: Use thenAccept when the result matters to your action; use thenRun when only the fact of completion matters—it's about whether your lambda needs the result parameter or not.