Java CompletableFuture

Introduction

Before Java 8, developers primarily used the Future interface for asynchronous programming. While Future allowed background task execution, it had several limitations. It could not easily chain multiple asynchronous tasks, combine independent tasks, or execute callbacks when a task completed.

To overcome these limitations, Java 8 introduced the CompletableFuture class as part of the java.util.concurrent package. CompletableFuture extends the capabilities of Future by providing a rich API for asynchronous programming, task composition, callback execution, exception handling, and combining multiple asynchronous operations.

Today, CompletableFuture is one of the most widely used concurrency utilities in Java and is commonly used in Spring Boot applications, REST APIs, microservices, cloud applications, and distributed systems.

What is Java CompletableFuture?

CompletableFuture is a class in the java.util.concurrent package that represents the result of an asynchronous computation.

Unlike the traditional Future interface, CompletableFuture allows you to:

  • Execute tasks asynchronously.
  • Chain multiple tasks together.
  • Combine results from different tasks.
  • Register callbacks.
  • Handle exceptions gracefully.
  • Create complex asynchronous workflows.

It implements both the Future and CompletionStage interfaces, making it much more flexible than Future.

Why Use CompletableFuture?

The CompletableFuture class offers several advantages:

  • Supports non-blocking programming.
  • Allows asynchronous task chaining.
  • Executes callbacks automatically.
  • Combines multiple asynchronous operations.
  • Handles exceptions elegantly.
  • Improves application responsiveness.
  • Simplifies concurrent programming.
  • Reduces manual thread management.

Syntax

Creating a completed future:


CompletableFuture&ltString&gt future =
        CompletableFuture.completedFuture("Hello");
Running a task asynchronously:
CompletableFuture.runAsync(() -> {
    System.out.println("Running");
});

Returning a value asynchronously:


CompletableFuture&ltString&gt future =
        CompletableFuture.supplyAsync(() -> "Java");

How CompletableFuture Works

The execution flow is:


  Task
   │
 CompletableFutur
   │
Background Thread
   │
 Result
   │
 Callback

The task executes asynchronously, and once completed, callback methods can automatically process the result

Creating a CompletableFuture


import java.util.concurrent.*;
public class Demo {
    public static void main(String[] args)
            throws Exception {
        CompletableFuture&ltString&gt future =
                CompletableFuture.supplyAsync(() -> "Hello Java");
        System.out.println(future.get());
    }
}

Output

Hello Java

The task executes asynchronously, and get() retrieves the result.

Using runAsync()

The runAsync() method executes a task that does not return a value.


CompletableFuture.runAsync(() -> {
    System.out.println("Background Task");
});

Features

  • Executes asynchronously.
  • Returns CompletableFuture<Void>.
  • Suitable for logging, sending emails, and background jobs.

Using supplyAsync()

The supplyAsync() method executes a task that returns a value.


CompletableFuture&ltInteger&gt future =
        CompletableFuture.supplyAsync(() -> 100);

This is similar to submitting a Callable task.

Chaining Tasks

One of the biggest advantages of CompletableFuture is task chaining.

Example:


CompletableFuture&ltString&gt future =
        CompletableFuture.supplyAsync(() -> "Java")
        .thenApply(String::toUpperCase)
        .thenApply(text -> text + " Programming");
System.out.println(future.get());

Output

JAVA Programming

Each stage processes the result of the previous stage.

Using thenAccept()

thenAccept() consumes the result without returning another value.


CompletableFuture.supplyAsync(() -> "Java")
        .thenAccept(System.out::println);

Output

Java

Using thenRun()

thenRun() executes another task after completion but does not receive the previous result.


CompletableFuture.runAsync(() -> {
    System.out.println("Task Finished");
}).thenRun(() -> {
    System.out.println("Cleanup Completed");
});

Combining Two CompletableFutures

Example:


CompletableFuture&ltInteger&gt future1 =
       CompletableFuture.supplyAsync(() -> 10);
CompletableFuture&ltInteger&gt future2 =
        CompletableFuture.supplyAsync(() -> 20);
CompletableFuture&ltInteger&gt result =
        future1.thenCombine(future2, Integer::sum);
System.out.println(result.get());

Output

30

Both tasks execute independently and their results are combined.

Exception Handling

CompletableFuture provides built-in exception handling.


CompletableFuture&ltInteger&gt future =
        CompletableFuture.supplyAsync(() -> {
           return 10 / 0;
        }).exceptionally(ex -> {
           System.out.println(ex.getMessage());
            return 0;
        });
System.out.println(future.get());

Output

0

The exception is handled without crashing the application.

CompletableFuture vs Future

Feature Future CompletableFuture
Introduced In Java 5 Java 8
Async Execution Yes Yes
Task Chaining No Yes
Callback Support No Yes
Exception Handling Limited Advanced
Combining Multiple Tasks No Yes
Non-blocking APIs Limited Extensive

CompletableFuture vs Callable

Feature CompletableFuture Callable
Returns Value Yes Yes
Async Execution Yes Yes(via ExecutorService)
Chaining Yes No
Callback Suppor Yes No
Exception Handling Advanced Standard checked exceptions

Real-Life Example

Imagine ordering a meal through a food delivery app.

  • You place the order.
  • The restaurant prepares the food.
  • Another service assigns a delivery partner.
  • The driver picks up the food.
  • The app sends a notification.
  • The food is delivered.

Each step depends on the previous one, yet different operations can happen asynchronously.

This resembles CompletableFuture:

  • Order placement = Initial task
  • Food preparation = First asynchronous stage
  • Delivery assignment = Another stage
  • Notification = Callback
  • Delivery = Final result

Instead of waiting after each step, the workflow continues automatically.

Advantages of CompletableFuture

  • Supports asynchronous programming.
  • Allows task chaining.
  • Combines multiple tasks.
  • Executes callbacks.
  • Handles exceptions elegantly.
  • Reduces blocking.
  • Improves scalability.
  • Integrates with the Executor Framework.
  • Simplifies concurrent workflows.

Common Use Cases

CompletableFuture is commonly used in:

  • REST API calls
  • Spring Boot applications
  • Microservices
  • Database queries
  • File processing
  • Cloud applications
  • Email services
  • Report generation
  • Machine learning tasks
  • Parallel data processing

Common Mistakes

1. Calling get() Immediately

Incorrect:


CompletableFuture&ltString&gt future =
        CompletableFuture.supplyAsync(() -> "Java");
future.get();

Calling get() immediately blocks the current thread, reducing the benefit of asynchronous programming.

2. Ignoring Exception Handling

Always use methods such as:

  • exceptionally()
  • handle()
  • whenComplete()

to manage failures gracefully.

4. Forgetting to Specify a Custom Executor

By default, asynchronous tasks use the common ForkJoinPool. For CPU-intensive or application-specific workloads, consider supplying a dedicated Executor to better control resource usage

5. Using CompletableFuture for Simple Tasks

If a task is small, synchronous, and does not benefit from asynchronous execution, using CompletableFuture may unnecessarily complicate the code.

Best Practices

📖
Best Practices:
  • Use supplyAsync() for tasks that return a value.
  • Use runAsync() for tasks without a return value.
  • Chain tasks using methods such as thenApply(), thenCompose(), and thenCombine() instead of nesting callbacks.
  • Handle exceptions with exceptionally(), handle(), or whenComplete().
  • Avoid calling get() unless you truly need the result immediately.
  • Use a custom executor for production workloads when appropriate.
  • Keep asynchronous tasks focused and independent.
  • Design workflows to maximize parallelism where possible.

Conclusion

The Java CompletableFuture class is one of the most powerful tools for asynchronous programming in modern Java. By extending the capabilities of the traditional Future interface, it enables developers to create non-blocking workflows, chain asynchronous tasks, combine multiple computations, execute callbacks, and handle exceptions with ease.

Whether you are developing REST APIs, microservices, Spring Boot applications, or enterprise systems, CompletableFuture helps improve performance, scalability, and code readability. Mastering methods such as supplyAsync(), runAsync(), thenApply(), thenCombine(), and exceptionally() is essential for writing efficient concurrent applications and is a highly valued skill in Java development and technical interviews.

Related Java Tutorials