Future vs CompletableFuture in
Java
Asynchronous programming made easier with Java!
What is Future?
- Introduced in Java 5
- Represents async computation result
- Result available after task completes
Future<String> future = executor.submit(() -> "Hello");
String result = future.get(); // Blocks
Key Methods in Future
Method | Description
------------- | -----------------------------
get() | Waits for and returns result
cancel() | Attempts to cancel execution
isDone() | Checks if task is completed
isCancelled() | Checks if task was cancelled
Enter CompletableFuture (Java 8+)
- More powerful than Future
- Supports non-blocking, async programming
- Allows chaining and combining tasks
CompletableFuture Basic Example
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
// Output: Hello World
Comparison
Feature | Future | CompletableFuture
-------------------|------------------|----------------------
Blocking | Yes | No (async)
Chaining | No | Yes
Combining Futures | No | Yes
Exception Handling | Manual try/catch | Built-in (exceptionally)
Exception Handling Example
CompletableFuture.supplyAsync(() -> 10 / 0)
.exceptionally(ex -> {
System.out.println("Error: " + ex);
return 0;
})
.thenAccept(System.out::println);
Where to Use Them?
Use Future for:
- Simple async result
- Blocking acceptable
Use CompletableFuture for:
- Complex async logic
- Non-blocking flow
- Chaining multiple tasks
Final Thought
Choose the right tool:
Future – basic async handling
CompletableFuture – modern async toolkit
#Java #CompletableFuture #Multithreading #AsynchronousProgramming #BackendTips