thenApply, thenAccept and thenRun
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Three methods build most CompletableFuture pipelines. thenApply changes the value, thenAccept uses it, and thenRun does something after it without looking at it.
Transforming a result with thenApply
thenApply is a CompletableFuture method that runs a function on the result when it arrives and returns a new CompletableFuture holding the function's result. It is the map of futures.
thenApply(fn) takes a Function<T, U>, runs it on the result when it arrives, and returns a new CompletableFuture<U> holding the new value. It is the map of CompletableFuture.
Example 1 · thenApply: fee, then GST, then a receipt line
import java.util.concurrent.CompletableFuture;
public class FeeReceiptDemo { public static void main(String[] args) { CompletableFuture<String> receipt = CompletableFuture .supplyAsync(() -> 50000) // Integer: hostel fee .thenApply(fee -> fee * 118 / 100) // Integer: fee with 18% GST .thenApply(total -> "Hostel fee with GST: Rs " + total); // String
System.out.println(receipt.join()); }}Hostel fee with GST: Rs 59000
What this code does
- Each
thenApplyreturns a new future:CompletableFuture<Integer>, then anotherCompletableFuture<Integer>, then aCompletableFuture<String>. - The GST step uses whole-number maths,
fee * 118 / 100, so the result is an exact number of rupees.
Example 2 · Mistake: ignoring the future thenApply returns
import java.util.concurrent.CompletableFuture;
public class IgnoredStepDemo { public static void main(String[] args) { CompletableFuture<Integer> fee = CompletableFuture.supplyAsync(() -> 50000);
fee.thenApply(f -> f * 118 / 100); // new future thrown away System.out.println("Wrong: " + fee.join());
CompletableFuture<Integer> withGst = fee.thenApply(f -> f * 118 / 100); System.out.println("Right: " + withGst.join()); }}Wrong: 50000 Right: 59000
What this code does
- The first
thenApplydoes compute 59000, but into a new future that nobody stored.feeitself still holds 50000. - Keep the returned future, or keep chaining with dots, and join the last one.
The type can change at each step: an Integer fee can become an Integer with GST, then a String receipt. Each step waits for the one before it. The original future never changes. If you call fee.thenApply(...) and ignore what it returns, the new value is lost and fee.join() still gives the old one.
Consuming a result with thenAccept
thenAccept(consumer) takes a Consumer<T>: it uses the value, for example to print or save it, and returns nothing. The future it returns is a CompletableFuture<Void>.
Example 3 · thenAccept: print the UPI receipt
import java.util.concurrent.CompletableFuture;
public class UpiReceiptDemo { static String pay(String upiId, int amount) { return "Rs " + amount + " paid to " + upiId; // pretend this calls the bank }
public static void main(String[] args) { CompletableFuture<Void> printed = CompletableFuture .supplyAsync(() -> pay("store@okaxis", 85)) .thenApply(text -> "Receipt: " + text) .thenAccept(line -> System.out.println(line));
Void nothing = printed.join(); System.out.println("join returned " + nothing); }}Receipt: Rs 85 paid to store@okaxis join returned null
What this code does
thenAccepttakes the receipt text and prints it. It returns no value, so the pipeline's type becomesCompletableFuture<Void>.- Joining that future waits until the receipt has been printed. The value it returns is always
null.
Use it for the last step of a pipeline, where the value goes out of the program: a screen, a file, a message. Joining the Void future tells you that step has finished.
Predict the output
What does each pipeline print?
Read each program and pick its output.
Round 1 of 3
The result of thenApply is not stored.
Running a step with thenRun
thenRun(runnable) runs a Runnable after the previous step finishes. The Runnable takes no input, so it cannot see the result; it only knows that the step before is done.
Example 4 · thenRun: follow-up steps that need no data
import java.util.concurrent.CompletableFuture;
public class SeatBookingDemo { public static void main(String[] args) { CompletableFuture .supplyAsync(() -> "S4-32") // seat number .thenApply(seat -> "Seat " + seat + " booked on 12951 Rajdhani") .thenAccept(ticket -> System.out.println(ticket)) .thenRun(() -> System.out.println("SMS sent to passenger")) .thenRun(() -> System.out.println("Booking window closed")) .join(); }}Seat S4-32 booked on 12951 Rajdhani SMS sent to passenger Booking window closed
What this code does
- Each step waits for the one before it, so the three lines always print in this order.
- The
thenRunlambdas are() -> ...: they have no parameter, so they cannot read the seat number. They only know the earlier steps are done.
- Need a new value from the result →
thenApply(returnsCompletableFuture<U>). - Need to use the result, nothing to return →
thenAccept(returnsCompletableFuture<Void>). - Need to run something afterwards, result not needed →
thenRun(returnsCompletableFuture<Void>).
Use it for follow-up work that needs no data: "SMS sent", "close the booking window", "update the counter".
Which thread runs each step
A plain step such as thenApply runs on whichever thread completes the stage before it.
Example 5 · The same thenApply on two different threads
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
public class WhichThreadDemo { static String thread() { return Thread.currentThread().getName(); }
public static void main(String[] args) throws InterruptedException { ExecutorService warehouse = Executors.newSingleThreadExecutor(r -> new Thread(r, "warehouse-1")); CountDownLatch go = new CountDownLatch(1);
// Case 1: the step is attached while the item is still being packed CompletableFuture<String> order = CompletableFuture.supplyAsync(() -> { try { go.await(); // start only after main says go } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Laptop"; }, warehouse); CompletableFuture<String> packed = order.thenApply(item -> item + " packed on " + thread()); go.countDown(); System.out.println(packed.join());
// Case 2: the future is already complete when the step is attached CompletableFuture<String> ready = CompletableFuture.completedFuture("Mouse"); System.out.println(ready.thenApply(item -> item + " packed on " + thread()).join());
warehouse.shutdown(); }}Laptop packed on warehouse-1 Mouse packed on main
What this code does
- The second argument of
supplyAsyncpicks the pool; here a one-thread pool namedwarehouse-1(lesson 7 covers this). The latch makes surethenApplyis attached before the item is ready, so the step runs onwarehouse-1when it completes the order. completedFuture("Mouse")makes a future that is already done. A step attached to it runs immediately, on the caller's thread:main.
Example 6 · Async variants: always on a pool thread
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
public class AsyncStepDemo { static String thread() { return Thread.currentThread().getName(); }
public static void main(String[] args) { ExecutorService counter = Executors.newSingleThreadExecutor(r -> new Thread(r, "counter-1")); CompletableFuture<String> ready = CompletableFuture.completedFuture("Mouse");
System.out.println(ready.thenApply(d -> d + ": thenApply on " + thread()).join()); System.out.println(ready.thenApplyAsync(d -> d + ": thenApplyAsync on common pool = " + thread().startsWith("ForkJoinPool.commonPool")).join()); System.out.println(ready.thenApplyAsync(d -> d + ": thenApplyAsync on " + thread(), counter).join());
counter.shutdown(); }}Mouse: thenApply on main Mouse: thenApplyAsync on common pool = true Mouse: thenApplyAsync on counter-1
What this code does
- The future is already complete, so plain
thenApplyruns onmain.thenApplyAsyncnever runs on the caller: it goes to the common pool (on a machine with 3 or more cores). thenApplyAsync(fn, counter)sends the step to the executor you pass, here the thread namedcounter-1. Every Async method has this two-argument form.
Usually that is the pool thread that finished the task; but if the future was already complete when you attached the step, the step runs at once on your own thread. Each method also has an Async form: thenApplyAsync, thenAcceptAsync, thenRunAsync. These always hand the step to a pool: the common pool, or an executor you pass as the last argument.
For quick steps like adding GST, the plain form is fine. For slow or blocking steps, use the Async form with your own executor, so the step cannot freeze the caller or a shared pool thread.
main.Next step
Check your understanding
11 quick questions