CompletableFuture.supplyAsync()
Runs a computation asynchronously and returns a `CompletableFuture`.
Available since: Java 8
Syntax
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)Parameters
| Parameter | Type | Description |
|---|---|---|
| supplier | Supplier<U> | The code that computes the result. |
| executor | Executor | Optional pool; the common `ForkJoinPool` by default. |
Return value
CompletableFuture<U>A future result that further steps can be attached to.
Examples
An asynchronous task and waiting for the result:
void main() {
CompletableFuture<String> page = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); }
return "<html>...</html>";
});
IO.println("loading...");
IO.println(page.join().length() + " chars");
}Output:
loading...
16 charsNotes
Without the second argument the task runs on the shared ForkJoinPool.commonPool(). For waiting tasks (network, files) pass your own pool, for example Executors.newVirtualThreadPerTaskExecutor(). For a task without a result there is runAsync().
See also
- CompletableFuture.thenApply() — Adds a step that transforms the result once it is ready.
- CompletableFuture.join() — Waits for the result of a `CompletableFuture`; errors arrive as unchecked exceptions.
- Supplier — A supplier: a no-argument function that returns a value.
- Future.get() — Waits for a task to finish and returns its result.
Related recipes
In the tutorial
- CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.