Skip to main content
CompletableFuture · Topic 2 of 6

supplyAsync and thenApply

Definition​

A CompletableFuture is a result that will be ready later. supplyAsync starts a task in the background. thenApply says what to do with the result when it arrives, so you build a chain of steps without blocking a thread to wait.

Example code​

Start a task, then transform its result

import java.util.concurrent.CompletableFuture;

class Demo {
static int fetchPrice() {
try { Thread.sleep(100); } catch (InterruptedException ignored) { } // pretend this is a slow call
return 200;
}

public static void main(String[] args) {
CompletableFuture<String> message = CompletableFuture
.supplyAsync(Demo::fetchPrice) // runs in the background
.thenApply(price -> price * 118 / 100) // runs when the price is ready (add tax)
.thenApply(total -> "Total: " + total);

System.out.println(message.join()); // wait for the final result
}
}

// Output:
// Total: 236

Finished this page? Track your progress (saved only in your browser).