1. The problem with synchronous code
Imagine you have an application that needs to load data from the internet or read a large file. You write something like:
String data = readFromFile("bigfile.txt");
System.out.println("Data: " + data);
All would be fine, but if the file is large or the network is slow, the program simply hangs on the read line. The user sees a “frozen” interface, the server can’t serve other requests, and the developer... is sad.
This situation is called blocking: a thread (for example, the main thread of your application) is forced to wait until the operation completes. And if there are many such operations — hello, lag and poor performance.
It’s like walking into a cafe, placing an order and... having to stand at the counter until your coffee is made. Other customers stand behind you and wait until the barista finishes with you. Inefficient, right?
Asynchrony: how it saves the world
Asynchronous programming is an approach in which long operations (for example, reading a file, making a server request, accessing a database) are executed on a background thread, while the main thread keeps working: serving users, accepting new requests, responding to events.
In other words, you place the order (start a task), go about your business, and when the coffee is ready (the task has completed), someone simply tells you: “Ready!”
In Java, before CompletableFuture, this wasn’t very convenient. Let’s see how things evolved.
2. Historical approaches: Future and its limitations
In Java 5, the Future interface appeared — the first attempt to make working with asynchronous tasks at least somewhat convenient. It allowed you to delegate a task to a thread pool and eventually get the result.
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> 2 + 2);
int result = future.get(); // Careful: the thread will block until the task completes!
The idea sounds good, but in practice Future is like an old mailbox: you send a letter, but to find out whether a reply has arrived, you have to keep peeking inside.
It doesn’t notify you when the result is ready, doesn’t support chains like “do this and then that,” and doesn’t let you handle errors cleanly. Everything revolves around that same blocking get() call, which turns asynchrony back into waiting.
3. The arrival of CompletableFuture: a new style of asynchrony
In Java 8, a real hero of asynchrony arrived to replace the outdated Future — CompletableFuture. This class from java.util.concurrent became a universal tool for those who were tired of waiting for results “manually” and wanted to write asynchronous code that is clean, compact, and understandable.
CompletableFuture can do almost everything. It can run tasks on other threads, assemble them into chains — for example, first compute a result, then process it, and then do something else. It easily combines multiple tasks: you can wait for all of them at once or only for the first one that completes. Errors are handled elegantly — without extra try-catch. And the overall style becomes more functional: instead of boring calls and waits, you get expressive methods like thenApply, thenAccept, and others.
flowchart LR
A[Run task asynchronously] --> B[Process result]
B --> C[Next operation]
C --> D[Error handling]
That’s how CompletableFuture turned asynchrony from a heavy craft into a convenient and flexible tool that finally lets your code breathe.
4. A simple example: your first step into the world of CompletableFuture
Let’s look at a minimal example of an asynchronous task:
import java.util.concurrent.CompletableFuture;
public class AsyncDemo {
public static void main(String[] args) {
// Start a task asynchronously
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2 + 2);
// Get the result (blocks the thread!)
try {
int result = future.get();
System.out.println("Result: " + result); // 4
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code already performs the computation on a separate thread — the main thread isn’t blocked at the moment the task starts. But the get() call still blocks the thread until the result is ready.
So how do you NOT block the thread?
It’s simple: use callback-style methods that are invoked when the task completes:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2 + 2);
future.thenAccept(result -> System.out.println("Result: " + result));
System.out.println("I’m not blocking and can do something else!");
Takeaway:
- thenAccept is “subscribe to the result”: when the task completes, run this code.
- The main thread doesn’t wait for the task to finish; it keeps working.
Visualization (event pseudocode)
[Main thread] --> [Start task]
| |
v v
[Does something] [Background thread computes 2+2]
| |
v v
[Prints "I’m not blocking..."]
| |
v v
[When done — thenAccept is called]
5. What does it look like in an application?
Imagine you are building a console application where the user can request a data load (for example, from a database or a server), and while the data is loading — the program doesn’t “freeze” and continues to accept commands.
Example: simulating a long operation
import java.util.concurrent.CompletableFuture;
public class AsyncApp {
public static void main(String[] args) {
System.out.println("Starting data load...");
CompletableFuture<String> dataFuture = CompletableFuture.supplyAsync(() -> {
// Simulate a long load
try {
Thread.sleep(2000); // 2 seconds
} catch (InterruptedException e) {
return "Load error";
}
return "Data loaded successfully!";
});
// Subscribe to the result
dataFuture.thenAccept(result -> System.out.println("Result: " + result));
// The program continues to work
System.out.println("While the data is loading, I can do something else!");
// To prevent the program from terminating too early (demo only!)
try {
Thread.sleep(2500);
} catch (InterruptedException ignored) {}
}
}
What you will see in the console:
Starting data load...
While the data is loading, I can do something else!
[after 2 seconds]
Result: Data loaded successfully!
6. Useful details
A bit about threads under the hood
When you write CompletableFuture.supplyAsync(...), the task by default runs in the so-called ForkJoinPool — a special thread pool that Java uses for parallel tasks. If you need more control (for example, your own ExecutorService), you can pass it as the second parameter:
ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2 + 2, executor);
But for simple tasks the default pool is sufficient.
Getting the result: get(), join(), thenAccept
- get() — blocks the thread until the result is ready (throws checked exceptions).
- join() — also blocks, but throws unchecked exceptions (RuntimeException).
- thenAccept(), thenApply() and others — do NOT block; they invoke the provided function when the result is ready.
In real asynchronous applications, try to avoid get()/join() on the main thread!
7. Common mistakes when getting started with CompletableFuture
Mistake #1: Using get() or join() in the main thread.
This blocks your program again and negates the benefits of asynchrony. Instead, use thenAccept, thenApply, and other methods to handle the result.
Mistake #2: Forgetting to handle errors.
If an exception occurs in an asynchronous task, it won’t “surface” on the main thread. Without handling via exceptionally or handle, you simply won’t know something went wrong.
Mistake #3: Not waiting for the program to finish.
In demo examples you often need to “pause” the main thread via Thread.sleep — otherwise the program will terminate before the task completes. In real applications (for example, web servers) this isn’t an issue, but in console demos keep it in mind.
Mistake #4: Mixing up thenAccept and thenApply.
thenAccept is for “side effects” (returns nothing), thenApply is for transforming the result (returns a new result).
Mistake #5: Mixing asynchronous and synchronous code unnecessarily.
If you start writing asynchronously, don’t pull it back into synchronous code via get()/join() unless it’s a last resort (for example, in tests).
GO TO FULL VERSION