CompletableFuture Then Compose Chain

Chain async operations with CompletableFuture thenCompose for dependent async stages.

JavaData Fetching

Code

javasnippet
17 lines
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncChain {
    static ExecutorService pool = Executors.newFixedThreadPool(4);
    static CompletableFuture<String> fetchUser(int id) {
        return CompletableFuture.supplyAsync(() -> "user" + id, pool);
    }
    static CompletableFuture<String> fetchProfile(String user) {
        return CompletableFuture.supplyAsync(() -> user + ":profile", pool);
    }
    public static void main(String[] args) {
        fetchUser(1).thenCompose(AsyncChain::fetchProfile)
            .thenAccept(System.out::println).join();
    }
}

What the code does

CompletableFuture Then Compose Chain keeps everything in the class AsyncChain and the functions fetchUser, fetchProfile and main.

Applying it

The primary signature is static CompletableFuture<String> fetchUser(int id)

main sequences fetchUser; executing the file runs that flow once.

Statements that matter

return CompletableFuture.supplyAsync(() -> user + ":profile", pool);
static ExecutorService pool = Executors.newFixedThreadPool(4);
return CompletableFuture.supplyAsync(() -> "user" + id, pool);

Interactive Tools for This Topic

FAQ

How do you run CompletableFuture Then Compose Chain?
Direct execution is enough; the script has no external requirements.