DEV Community

Cover image for CompletableFuture: Writing Asynchronous Java Applications
Ramanjaneyulu Boya
Ramanjaneyulu Boya

Posted on

CompletableFuture: Writing Asynchronous Java Applications

Modern enterprise applications need to handle thousands of concurrent requests while maintaining low response times and efficient resource utilization.

Consider a banking application where a customer opens an account dashboard. The application may need to retrieve:

  • Account details
  • Recent transactions
  • Credit card information
  • Loan details
  • Fraud alerts

Should the application call each service sequentially and wait for every response?

Not necessarily.

This is where Java's CompletableFuture becomes extremely useful.

Introduced in Java 8 and enhanced by subsequent Java releases, CompletableFuture provides a powerful programming model for asynchronous and non-blocking task composition.

In this article, we will explore how CompletableFuture works, understand its important methods, and implement practical asynchronous workflows using Java 21.


1. What Is CompletableFuture?

CompletableFuture is an implementation of Java's Future and CompletionStage interfaces.

It allows developers to:

  • Execute tasks asynchronously.
  • Retrieve results when computation completes.
  • Chain multiple asynchronous operations.
  • Execute independent tasks concurrently.
  • Combine results from multiple asynchronous operations.
  • Handle exceptions in asynchronous workflows.

Traditional synchronous execution blocks the calling thread until an operation completes.

With asynchronous execution, the calling thread can continue performing other work while the task executes.

Example:

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> {
        return "Account details retrieved";
    });

System.out.println(future.join());
Enter fullscreen mode Exit fullscreen mode

Here, supplyAsync() executes the task asynchronously using the default ForkJoinPool common pool.

join() retrieves the result and waits if necessary.


2. Synchronous vs Asynchronous Execution

Consider retrieving customer information from three independent services.

Synchronous approach

Account account = accountService.getAccount();

List<Transaction> transactions =
    transactionService.getTransactions();

List<Card> cards =
    cardService.getCards();
Enter fullscreen mode Exit fullscreen mode

If each service takes 500 milliseconds, the approximate total execution time is:

500 + 500 + 500 = 1500 milliseconds.

Asynchronous approach

CompletableFuture<Account> accountFuture =
    CompletableFuture.supplyAsync(
        accountService::getAccount
    );

CompletableFuture<List<Transaction>> transactionFuture =
    CompletableFuture.supplyAsync(
        transactionService::getTransactions
    );

CompletableFuture<List<Card>> cardFuture =
    CompletableFuture.supplyAsync(
        cardService::getCards
    );

CompletableFuture.allOf(
    accountFuture,
    transactionFuture,
    cardFuture
).join();
Enter fullscreen mode Exit fullscreen mode

The three independent operations can execute concurrently.

If each takes approximately 500 milliseconds, total execution time may approach 500 milliseconds plus orchestration overhead, assuming sufficient resources.

Important: Asynchronous execution does not automatically make operations faster. Actual performance depends on thread availability, service latency, connection pools, and system capacity.

SYNCHRONOUS VS ASYNCHRONOUS EXECUTION


3. Important CompletableFuture Methods

Understanding the core methods is essential before implementing enterprise asynchronous applications.

3.1 runAsync()

Use runAsync() when a task does not return a result.

CompletableFuture<Void> future =
    CompletableFuture.runAsync(() -> {
        System.out.println("Sending notification...");
    });

future.join();
Enter fullscreen mode Exit fullscreen mode

Typical use cases:

  • Sending notifications
  • Writing audit logs
  • Triggering background tasks
  • Updating non-critical metrics

3.2 supplyAsync()

Use supplyAsync() when a task returns a result.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> {
        return "Payment processed";
    });

String result = future.join();
Enter fullscreen mode Exit fullscreen mode

Typical use cases:

  • Fetching customer information
  • Calling external APIs
  • Retrieving transaction history
  • Calculating risk scores

3.3 thenApply()

Transforms the result of a completed computation.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> "ramu")
        .thenApply(String::toUpperCase);

System.out.println(future.join());
Enter fullscreen mode Exit fullscreen mode

Output:

RAMU
Enter fullscreen mode Exit fullscreen mode

Think of thenApply() as a transformation operation.

3.4 thenAccept()

Consumes the result without returning another value.

CompletableFuture.supplyAsync(() -> "PAYMENT_SUCCESS")
    .thenAccept(status ->
        System.out.println("Status: " + status)
    );
Enter fullscreen mode Exit fullscreen mode

3.5 thenRun()

Executes an operation after the previous stage completes, without consuming its result.

CompletableFuture.supplyAsync(() -> "ORDER_CREATED")
    .thenRun(() ->
        System.out.println("Workflow completed")
    );
Enter fullscreen mode Exit fullscreen mode

4. thenApply() vs thenCompose() vs thenCombine()

This is one of the most frequently asked CompletableFuture interview topics.

thenApply()

Transforms a result.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> "customer-101")
        .thenApply(String::toUpperCase);
Enter fullscreen mode Exit fullscreen mode

thenCompose()

Chains dependent asynchronous operations and flattens the resulting future.

CompletableFuture<Customer> customerFuture =
    getCustomerId()
        .thenCompose(this::getCustomerDetails);
Enter fullscreen mode Exit fullscreen mode

Without thenCompose(), chaining a method that already returns a CompletableFuture can result in nested futures.

thenCombine()

Combines two independent CompletableFuture results.

CompletableFuture<Double> balanceFuture =
    CompletableFuture.supplyAsync(() -> 50000.0);

CompletableFuture<Double> loanFuture =
    CompletableFuture.supplyAsync(() -> 15000.0);

CompletableFuture<Double> totalFuture =
    balanceFuture.thenCombine(
        loanFuture,
        Double::sum
    );

System.out.println(totalFuture.join());
Enter fullscreen mode Exit fullscreen mode

Output:

65000.0
Enter fullscreen mode Exit fullscreen mode

When should you use them?

Method Purpose
thenApply() Transform a result
thenCompose() Chain dependent asynchronous tasks
thenCombine() Combine independent results

COMPLETABLEFUTURE CHAINING METHODS


5. Combining Multiple Asynchronous Operations

Enterprise applications frequently need data from multiple independent services.

Consider a fintech dashboard.

public CompletableFuture<Dashboard> getDashboard(
        String customerId) {

    CompletableFuture<Account> accountFuture =
        accountService.getAccountAsync(customerId);

    CompletableFuture<List<Transaction>> transactionFuture =
        transactionService.getTransactionsAsync(customerId);

    CompletableFuture<List<Card>> cardFuture =
        cardService.getCardsAsync(customerId);

    return CompletableFuture.allOf(
            accountFuture,
            transactionFuture,
            cardFuture
        )
        .thenApply(ignored -> new Dashboard(
            accountFuture.join(),
            transactionFuture.join(),
            cardFuture.join()
        ));
}
Enter fullscreen mode Exit fullscreen mode

Here:

  1. Account service executes asynchronously.
  2. Transaction service executes asynchronously.
  3. Card service executes asynchronously.
  4. allOf() waits for all futures to complete.
  5. thenApply() constructs the final dashboard.

Note that allOf() returns CompletableFuture<Void>. Individual results must be retrieved from their respective futures.

This is a practical pattern for aggregating data from multiple microservices.

allOf() vs anyOf()

allOf():

Waits for all supplied futures to complete.

anyOf():

Completes when any one of the supplied futures completes.

Example:

CompletableFuture<Object> fastest =
    CompletableFuture.anyOf(
        service1Future,
        service2Future,
        service3Future
    );
Enter fullscreen mode Exit fullscreen mode

This can be useful when implementing competing read strategies or fallback providers.

However, anyOf() does not automatically cancel the remaining tasks.

ALL OF VS ANY OF EXECUTION FLOW


6. Exception Handling in CompletableFuture

Asynchronous applications must handle failures gracefully.

What happens if an external banking service is unavailable?

CompletableFuture provides several exception-handling methods.

exceptionally()

Provides a fallback value when an exception occurs.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> {
        throw new RuntimeException("Service unavailable");
    }).exceptionally(ex -> "DEFAULT_RESPONSE");

System.out.println(future.join());
Enter fullscreen mode Exit fullscreen mode

handle()

Handles both successful and exceptional completion.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> "SUCCESS")
        .handle((result, exception) -> {

            if (exception != null) {
                return "FAILED";
            }

            return result;
        });
Enter fullscreen mode Exit fullscreen mode

whenComplete()

Allows observation of the result or exception without transforming the outcome.

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> "PAYMENT_SUCCESS")
        .whenComplete((result, exception) -> {

            if (exception != null) {
                System.err.println(exception.getMessage());
            } else {
                System.out.println(result);
            }
        });
Enter fullscreen mode Exit fullscreen mode

Key differences:

Method Purpose
exceptionally() Recover from an exception
handle() Transform success or failure
whenComplete() Observe completion

In financial applications, fallback behavior must be carefully designed. Never convert a failed payment verification into a successful payment response.


7. Custom Thread Pools with CompletableFuture

By default, asynchronous methods such as supplyAsync() use ForkJoinPool.commonPool() when no executor is supplied.

For production enterprise applications, using a dedicated executor is often preferable.

Why?

  • Better isolation between workloads.
  • Predictable concurrency limits.
  • Easier thread monitoring.
  • Avoid interference between unrelated asynchronous tasks.
  • Better control over resource utilization.

Example:

ExecutorService executor =
    Executors.newFixedThreadPool(10);

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> {
        return "Banking service response";
    }, executor);
Enter fullscreen mode Exit fullscreen mode

You can also define an executor using a ThreadPoolExecutor for more explicit production configuration.

ExecutorService executor =
    new ThreadPoolExecutor(
        10,
        20,
        60,
        TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(100)
    );
Enter fullscreen mode Exit fullscreen mode

Production considerations:

  • Configure bounded queues.
  • Define appropriate rejection policies.
  • Monitor active threads and queue utilization.
  • Avoid unbounded task submission.
  • Shut down executors gracefully.
  • Size pools based on workload characteristics.

For blocking I/O workloads, thread-pool sizing should consider downstream latency and available resources.

COMPLETABLEFUTURE THREAD POOL ARCHITECTURE


8. CompletableFuture with Spring Boot

Let's consider a practical Spring Boot example.

A banking application needs to retrieve account information asynchronously.

@Service
public class AccountService {

    @Async("accountExecutor")
    public CompletableFuture<Account> getAccount(
            String accountId) {

        Account account = fetchAccountFromDatabase(accountId);

        return CompletableFuture.completedFuture(account);
    }
}
Enter fullscreen mode Exit fullscreen mode

Configure the executor:

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "accountExecutor")
    public Executor accountExecutor() {

        ThreadPoolTaskExecutor executor =
            new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("account-");

        executor.initialize();

        return executor;
    }
}
Enter fullscreen mode Exit fullscreen mode

Controller:

@RestController
@RequestMapping("/accounts")
public class AccountController {

    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{id}")
    public CompletableFuture<Account> getAccount(
            @PathVariable String id) {

        return accountService.getAccount(id);
    }
}
Enter fullscreen mode Exit fullscreen mode

Spring MVC supports returning CompletableFuture from controller methods.

The servlet request can be handled asynchronously while the computation executes.

Important considerations:

  • @Async works through Spring proxies; self-invocation does not trigger asynchronous interception.
  • Configure exception handling and executor capacity.
  • Avoid blocking operations on shared event-loop threads.
  • Understand transaction boundaries when moving work across threads.
  • Do not assume that asynchronous execution automatically improves database performance.

9. CompletableFuture vs Future vs Java Virtual Threads

Java developers should understand how these concurrency approaches differ.

Feature Future CompletableFuture Virtual Threads
Asynchronous execution Yes Yes Supports concurrent execution
Result retrieval get() join(), get() Depends on task design
Task chaining No built-in chaining Yes No built-in chaining
Combining results Manual Built-in methods Manual or structured approach
Exception handling Limited Rich API Standard exception handling
Best suited for Basic asynchronous tasks Async workflows Large numbers of blocking tasks

Virtual threads, introduced as a preview feature in Java 19 and finalized in Java 21, provide a lightweight threading model.

Example:

try (ExecutorService executor =
         Executors.newVirtualThreadPerTaskExecutor()) {

    Future<String> future = executor.submit(() -> {
        return "Account retrieved";
    });

    System.out.println(future.get());
}
Enter fullscreen mode Exit fullscreen mode

Use CompletableFuture when you need asynchronous composition and result coordination.

Use virtual threads when you want straightforward thread-per-task programming, especially for blocking I/O workloads.

They are complementary technologies, not direct replacements for each other.


10. Real-World Fintech Use Case: Payment Processing

Consider a payment platform that needs to perform multiple independent operations:

  1. Validate customer information.
  2. Retrieve merchant details.
  3. Perform fraud risk assessment.
  4. Retrieve transaction limits.

Some of these checks can execute concurrently.

public CompletableFuture<PaymentDecision> evaluatePayment(
        PaymentRequest request) {

    CompletableFuture<Customer> customerFuture =
        customerService.validateAsync(request);

    CompletableFuture<Merchant> merchantFuture =
        merchantService.getMerchantAsync(request);

    CompletableFuture<FraudResult> fraudFuture =
        fraudService.evaluateAsync(request);

    CompletableFuture<LimitResult> limitFuture =
        limitService.checkAsync(request);

    return CompletableFuture.allOf(
            customerFuture,
            merchantFuture,
            fraudFuture,
            limitFuture
        )
        .thenApply(ignored -> {

            return paymentDecisionService.evaluate(
                customerFuture.join(),
                merchantFuture.join(),
                fraudFuture.join(),
                limitFuture.join()
            );
        });
}
Enter fullscreen mode Exit fullscreen mode

This approach reduces sequential waiting when the checks are independent.

However, payment processing requires additional enterprise safeguards:

  • Define timeouts for external service calls.
  • Apply circuit breakers and controlled retries.
  • Preserve idempotency for payment requests.
  • Handle partial failures explicitly.
  • Maintain audit trails.
  • Avoid treating unavailable fraud or limit services as successful checks.
  • Separate authorization decisions from actual payment execution.

CompletableFuture helps coordinate asynchronous operations. It does not replace distributed transaction management or payment consistency mechanisms.

FINTECH ASYNCHRONOUS PAYMENT ARCHITECTURE


11. Common Mistakes to Avoid

When using CompletableFuture in production, watch out for these mistakes.

1. Calling join() too early

String result = future.join();
Enter fullscreen mode Exit fullscreen mode

If called immediately after creating the future, you may lose the benefits of asynchronous composition.

2. Using the common pool for everything

Different workloads may compete for shared worker threads.

3. Ignoring exception handling

An unhandled exceptional completion can cause failures to surface much later in the workflow.

4. Creating unbounded asynchronous tasks

Too many concurrent operations can overwhelm downstream APIs, databases, and thread pools.

5. Ignoring timeouts

Use orTimeout() or completeOnTimeout() where appropriate.

future.orTimeout(3, TimeUnit.SECONDS);
Enter fullscreen mode Exit fullscreen mode

6. Assuming CompletableFuture guarantees non-blocking execution

Methods such as join() and get() block the calling thread when the result is not ready. Also, asynchronous methods do not automatically make blocking I/O non-blocking.


12. Best Practices for Enterprise Applications

For production-grade Java applications:

  1. Prefer thenApply() for transformations.
  2. Use thenCompose() for dependent asynchronous operations.
  3. Use thenCombine() for independent operations.
  4. Use allOf() for coordinating multiple futures.
  5. Configure dedicated executors for workload isolation.
  6. Define timeouts for external service calls.
  7. Implement meaningful exception-handling strategies.
  8. Apply concurrency limits to protect downstream services.
  9. Monitor thread pools, queue sizes, latency, and failure rates.
  10. Consider virtual threads for suitable blocking workloads.

Conclusion

CompletableFuture is one of the most powerful concurrency features available in modern Java.

It enables developers to build asynchronous workflows, coordinate multiple independent operations, combine results, and handle failures without relying entirely on traditional blocking execution.

For enterprise applications such as banking, payments, fraud detection, and customer platforms, understanding CompletableFuture is essential for building scalable and responsive systems.

The real skill is not simply knowing how to call supplyAsync() or thenApply().

It is knowing where to introduce concurrency, how to control resource utilization, and how to handle failures without compromising business correctness.

That is what separates writing asynchronous code from designing production-ready asynchronous systems.


Interview Questions to Practice

  1. What is CompletableFuture, and how is it different from Future?
  2. What is the difference between runAsync() and supplyAsync()?
  3. Explain thenApply() vs thenCompose() vs thenCombine().
  4. What is the difference between allOf() and anyOf()?
  5. How does CompletableFuture handle exceptions?
  6. What is the difference between exceptionally(), handle(), and whenComplete()?
  7. Which thread pool does CompletableFuture use by default?
  8. How do you configure a custom Executor?
  9. How do you implement timeout handling?
  10. Can CompletableFuture improve the performance of a Spring Boot microservice?
  11. What happens if one future in allOf() completes exceptionally?
  12. How does CompletableFuture compare with Java 21 Virtual Threads?

Author: Ram The Architect (RTA)

Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI

Github: https://github.com/Ramu-fsd/enterprise-banking-microservices
Linkedin: https://www.linkedin.com/in/ramuboya/

Technology: Java 21 | Concurrency | Multithreading | CompletableFuture | Spring Boot | Microservices

#Java #Java21 #CompletableFuture #Multithreading #Concurrency #SpringBoot #Microservices #SoftwareArchitecture #Fintech #BackendDevelopment

Top comments (0)