Hackforge Academy

Category: java

What CompletableFuture Adds

Published on 27 Oct 2026

Explanation

CompletableFuture implements Future and CompletionStage. It supports callbacks and composition, allowing dependent tasks to run when earlier tasks complete instead of forcing the caller to block with get().

Code:

import java.util.concurrent.CompletableFuture;

public class CompletableIntro {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> "Hello")
            .thenApply(s -> s + " Java")
            .thenAccept(System.out::println)
            .join();
    }
}

Explanation

thenApply() transforms a result and returns a new stage. thenAccept() consumes a result without producing another value. These methods can be chained to build asynchronous processing pipelines.

Code:

import java.util.concurrent.CompletableFuture;

public class ThenApplyDemo {
    public static void main(String[] args) {
        String result = CompletableFuture.supplyAsync(() -> 21)
            .thenApply(n -> n * 2)
            .thenApply(n -> "Answer: " + n)
            .join();
        System.out.println(result);
    }
}

Explanation

thenCombine() combines the results of two completion stages after both are available. This is useful when independent tasks, such as fetching a customer and an order, can run concurrently.

Code:

import java.util.concurrent.CompletableFuture;

public class CombineDemo {
    public static void main(String[] args) {
        CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 100);
        CompletableFuture<Integer> tax = CompletableFuture.supplyAsync(() -> 18);
        int total = price.thenCombine(tax, Integer::sum).join();
        System.out.println(total);
    }
}

Explanation

exceptionally() lets a pipeline recover from an exceptional completion by providing a fallback value. For richer handling, handle() can process either a successful value or an exception.

Code:

import java.util.concurrent.CompletableFuture;

public class ExceptionalDemo {
    public static void main(String[] args) {
        int result = CompletableFuture.supplyAsync(() -> 10 / 0)
            .exceptionally(error -> 0)
            .join();
        System.out.println(result);
    }
}

Explanation

Future offers basic status, cancellation, and blocking result retrieval. CompletableFuture adds chaining, combining, and error-handling operations. Async methods without an explicit executor commonly use the shared ForkJoinPool, so choose executors deliberately for blocking I/O workloads.

Code:

import java.util.concurrent.*;

public class FutureComparisonDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        try {
            Future<Integer> oldStyle = pool.submit(() -> 40 + 2);
            System.out.println(oldStyle.get());
            System.out.println(CompletableFuture.supplyAsync(() -> 40 + 2).join());
        } finally { pool.shutdown(); }
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community