Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CompletableFuture.supplyAsync with an explicit executor

Pass a custom `Executor` to choose how the task runs. A direct executor such as `Runnable::run` runs the task immediately on the calling thread instead of using the common pool.

Version: Java SE 21

Syntax

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

In Java SE 21, CompletableFuture.supplyAsync(Supplier,Executor) is a static method on java.util.concurrent.CompletableFuture. It takes a java.util.function.Supplier<U>, whose get() method needs no arguments and returns a value of type U, and a java.util.concurrent.Executor. It submits a task that calls get() and completes a new CompletableFuture<U> with the returned value.

The one-argument overload, supplyAsync(supplier), uses ForkJoinPool.commonPool(). If that pool cannot support a parallelism level of at least 2, Java creates a new thread per task. The two-argument overload is documented to use the supplied executor. OpenJDK 21 makes one exception: if you explicitly pass ForkJoinPool.commonPool() and its parallelism is below 2, the method uses a thread-per-task executor instead. This fallback for the two-argument overload is an implementation detail, not a Java SE guarantee. Async does not guarantee another thread or an immediate return.

With Executor sameThread = Runnable::run, execute calls the task's run() immediately on the calling thread. In the example, the computation finishes before supplyAsync returns, so join() reads 42 without waiting. A slow or blocking task would keep the calling thread busy until the task finishes.

If get() throws, the future completes exceptionally and join() throws an unchecked CompletionException. If execute itself throws RejectedExecutionException, that exception comes directly from supplyAsync, which does not return a future in that case. Neither argument may be null, but the value returned by get() may be.

Examples

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

public class Main {
    public static void main(String[] args) {
        Executor sameThread = Runnable::run;
        Thread caller = Thread.currentThread();

        System.out.println("before supplyAsync");
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("same thread: " + (Thread.currentThread() == caller));
            return 42;
        }, sameThread);
        System.out.println("after supplyAsync");
        System.out.println("result: " + future.join());
    }
}

Result

before supplyAsync
same thread: true
after supplyAsync
result: 42

The line `same thread: true` appears between `before supplyAsync` and `after supplyAsync`, showing that the supplier runs on the calling thread before the method returns. There is no pool to shut down.

Related lessons

  • Java · Lesson 51 · Intermediate · Version: 2

Sources