Java Future and CompletableFuture
1. Introduction
In Java, concurrency is a powerful feature that allows multiple threads to run simultaneously.
This lesson focuses on two key classes in the Java Concurrency framework: Future
and CompletableFuture
.
2. Key Concepts
- Concurrency: The ability to run multiple tasks simultaneously.
- Thread: The smallest unit of processing that can be scheduled by an operating system.
- ExecutorService: A high-level replacement for managing threads.
3. Future
The Future
interface represents the result of an asynchronous computation. A Future
provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result.
3.1. Key Methods of Future
get()
: Retrieves the result of the computation.isDone()
: Checks if the computation is complete.cancel()
: Attempts to cancel the computation.
4. CompletableFuture
CompletableFuture
is an extension of Future
that allows you to write non-blocking asynchronous code. It can be manually completed and allows for chaining multiple asynchronous tasks.
4.1. Key Features of CompletableFuture
- Support for multiple asynchronous tasks.
- Ability to combine multiple futures.
- Integration with lambda expressions.
5. Code Examples
import java.util.concurrent.CompletableFuture;
public class FutureExample {
public static void main(String[] args) {
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
// Simulate a long-running task
try { Thread.sleep(1000); } catch (InterruptedException e) { }
return 42;
});
future.thenAccept(result -> System.out.println("Result: " + result));
// Wait for the future to complete
future.join();
}
}
6. Best Practices
Always handle exceptions while using CompletableFuture for better resilience.
- Use
completeExceptionally
to handle errors. - Chain tasks using
thenApply
orthenAccept
for better readability. - Avoid blocking calls like
get()
whenever possible.
7. FAQ
What is the difference between Future and CompletableFuture?
Future is a blocking mechanism while CompletableFuture allows non-blocking asynchronous programming.
Can CompletableFuture handle exceptions?
Yes, CompletableFuture provides methods to handle exceptions using exceptionally
or handle
.
How do I combine multiple CompletableFutures?
You can combine multiple CompletableFutures using methods like allOf
or anyOf
.