Course contentsShow
← Java
Lesson 2779 of 2,87051. CompletableFutureFree lesson

Creating a CompletableFuture with completedFuture

Learning to create an already-completed CompletableFuture with a known value using completedFuture().

Creating a CompletableFuture with completedFuture

What you'll learn: How to create an already-completed CompletableFuture containing a known value using the completedFuture() factory method.

The Core Idea

Sometimes you already have a result and want to wrap it in a CompletableFuture for API consistency or compatibility. The static method CompletableFuture.completedFuture(value) creates a CompletableFuture that is immediately done with the specified value—no waiting, no background computation.

Think of it like receiving a gift that's already wrapped versus one you need to wrap yourself. The completedFuture method gives you a pre-wrapped present, ready to open.

Basic Syntax

CompletableFuture<String> future = CompletableFuture.completedFuture("Hello, World!");

This creates a CompletableFuture<String> that's already done. Calling get() on it returns immediately:

String result = future.get();  // Returns "Hello, World!" instantly—no blocking
System.out.println(result);
System.out.println(future.isDone());  // true

Why Is This Useful?

When you have methods that return CompletableFuture, but sometimes you already know the answer, completedFuture maintains consistent return types:

CompletableFuture<Integer> fetchData(boolean fromCache) {
    if (fromCache) {
        return CompletableFuture.completedFuture(42);  // Instant result
    }
    // Otherwise, return a real async computation
}

This avoids mixing return types (Integer vs CompletableFuture<Integer>) and keeps your API uniform.

Key Takeaway: CompletableFuture.completedFuture(value) creates an already-completed future holding the specified value, useful for returning immediate results while maintaining consistent asynchronous APIs.