Chaining thenAccept and thenRun in Pipelines
You'll learn how to combine thenAccept and thenRun with other CompletableFuture methods to build powerful async pipelines.
Core Idea
Now that you know thenAccept consumes results and thenRun executes side-effect actions, you can chain them together with other CompletableFuture methods like supplyAsync and thenApply to build multi-stage async pipelines. Each stage returns a CompletableFuture<Void>, which means you can continue chaining further non-value-producing stages.
Think of it like an assembly line: raw materials arrive (supplyAsync), get transformed (thenApply), are packaged and labeled (thenAccept), and finally the conveyor belt is cleaned for the next batch (thenRun). Each stage flows into the next seamlessly.
Building Complete Pipelines
CompletableFuture.supplyAsync(() -> "user123")
.thenApply(userId -> fetchUserData(userId)) // Transform: get user object
.thenApply(user -> user.getName()) // Transform: extract name
.thenAccept(name -> System.out.println("Hello, " + name)) // Consume result
.thenRun(() -> System.out.println("Pipeline complete")); // Final action
Notice how the pipeline naturally flows: supply → transform → transform → consume → cleanup. Once you use thenAccept, subsequent stages can't access the original value—but you can still chain thenRun for final housekeeping tasks.
Chaining Multiple Terminal Operations
CompletableFuture.supplyAsync(() -> calculateReport())
.thenAccept(report -> saveToDatabase(report))
.thenRun(() -> notifyAdministrator())
.thenRun(() -> logCompletion());
Multiple thenRun calls can follow each other, each performing independent side effects in sequence.
Key Takeaway: thenAccept and thenRun act as terminal stages in async pipelines, allowing you to consume results and perform cleanup actions while maintaining the fluent, chainable API style of CompletableFuture—perfect for orchestrating complex async workflows without callback nesting.