thenRun: Executing Actions Without Accessing Results
What you'll learn: How to execute a side-effect action after a CompletableFuture completes, without needing its result value.
The Core Idea
While thenAccept lets you consume a result, sometimes you need to run an action after a stage completes but don't care about the result at all. thenRun is designed exactly for this scenario—it executes a Runnable when the previous stage finishes, completely ignoring whatever value it produced.
When to Use thenRun
Think of thenRun as a "and then do this cleanup/logging/notification task" operation. You're saying: "Once that computation finishes (successfully), perform this side-effect action, but I don't need to know what the computation returned."
Common use cases:
- Logging completion milestones
- Updating UI status indicators
- Releasing resources
- Triggering unrelated follow-up actions
The Signature
CompletableFuture<Void> thenRun(Runnable action)
Notice it takes a Runnable (no parameters, no return value), unlike thenAccept which takes a Consumer.
Basic Example
CompletableFuture.supplyAsync(() -> {
// Expensive computation
return "Result";
})
.thenRun(() -> {
System.out.println("Computation finished, logging completion");
// No access to "Result" here—and we don't need it
});
The lambda inside thenRun has no parameters because it doesn't receive the previous stage's result.
Key Distinction
- thenAccept: Use when you need the result to do something with it
- thenRun: Use when you just need to know "it completed" without caring about the value
Key Takeaway: Use thenRun when you need to perform side-effect actions after a stage completes but don't need access to its result—perfect for logging, cleanup, or notifications that depend only on completion, not the computed value.