Practical Use Cases: Logging, Notifications, and Cleanup
You'll learn where thenAccept and thenRun shine in real-world asynchronous pipelines for side effects.
Core Idea
While thenApply transforms data, thenAccept and thenRun are side-effect specialists. They don't produce new values—they do things with results (or just signal completion). Three common patterns emerge: logging computation outcomes, triggering notifications, and performing cleanup tasks.
The Three Real-World Patterns
Logging with thenAccept
Use thenAccept when you need to record or display a computed result:
CompletableFuture.supplyAsync(() -> fetchUserData())
.thenApply(user -> user.calculateScore())
.thenAccept(score -> logger.info("User score: " + score))
.thenRun(() -> logger.debug("Processing complete"));
Here thenAccept logs the score value, while thenRun logs a completion marker (no value needed).
Notifications with thenAccept
Sending alerts or updating UI components based on results:
CompletableFuture.supplyAsync(() -> processPayment())
.thenAccept(receipt -> emailService.sendReceipt(receipt))
.thenRun(() -> analyticsTracker.recordEvent("payment_completed"));
The receipt goes to the email service; the completion event triggers analytics.
Cleanup with thenRun
Resource release or finalization that doesn't need the result:
CompletableFuture.supplyAsync(() -> downloadFile(), customExecutor)
.thenApply(file -> processFile(file))
.thenRun(() -> tempDirectory.cleanup());
After processing finishes (successfully or not, for now), cleanup runs—no result value required.
Why These Methods Matter
thenAccept and thenRun keep pipelines clean by separating computation (data transformation) from effects (actions with consequences in the outside world). This mirrors functional programming principles while maintaining async flow control.
Key Takeaway: Use thenAccept for side effects that need the result (logging output, sending notifications) and thenRun for completion-triggered actions (cleanup, status updates)—they're the workhorses of observable async behavior.