Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
supplierSupplier<U>The code that computes the result.
executorExecutorOptional 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 chars

Notes

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

Related recipes

In the tutorial

  • CompletableFuture — Asynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.

Thanks for reading!

Donate to the site — we work hard for you.