Java FAQ: Top Questions
41. What is the CompletableFuture in Java?
CompletableFuture
, introduced in Java 8 in
java.util.concurrent
, is a powerful class for asynchronous programming, enabling non-blocking, composable operations with results or exceptions.
Key points:
-
Asynchronous Execution:
Runs tasks in separate threads, often via
supplyAsync
orrunAsync
. -
Chaining:
Methods like
thenApply
,thenCombine
, andhandle
allow functional composition. -
Exception Handling:
Supports
exceptionally
orhandle
for errors. -
Completion:
Can be completed manually with
complete
orcompleteExceptionally
. - Use Case: Asynchronous APIs, parallel processing, or reactive programming.