Class CompletableFutureExamples
java.lang.Object
net.jrodolfo.java_evolution.java08.CompletableFutureExamples
Demonstrates
CompletableFuture, introduced in Java 8 to make
asynchronous work easier to compose.
Before Java 8, Future could represent a result
that would be available later, but it did not provide a fluent way to
transform that result, combine it with another future, or recover from
failure. Code often had to block with get() or coordinate callbacks
manually.
CompletableFuture solves that problem by treating asynchronous work
as a pipeline. A program can start work with supplyAsync, transform
the result with thenApply, combine independent results with
thenCombine, and handle errors with exceptionally. The
examples use a caller-provided Executor so tests can run
deterministically without depending on timing or background thread
scheduling.
-
Constructor Summary
ConstructorsConstructorDescriptionCompletableFutureExamples(Executor executor) Creates examples that run asynchronous stages on the supplied executor. -
Method Summary
Modifier and TypeMethodDescriptionCombines two independent futures withCompletableFuture.thenCombine(CompletionStage, BiFunction).Creates an asynchronous computation withCompletableFuture.supplyAsync(java.util.function.Supplier, Executor).Chains a transformation withCompletableFuture.thenApply(Function).UsesCompletableFuture.join()to wait for a composed future.Recovers from a failed asynchronous computation withCompletableFuture.exceptionally(Function).
-
Constructor Details
-
CompletableFutureExamples
Creates examples that run asynchronous stages on the supplied executor.- Parameters:
executor- the executor used by asynchronous examples
-
-
Method Details
-
fetchNameAsync
Creates an asynchronous computation withCompletableFuture.supplyAsync(java.util.function.Supplier, Executor).- Returns:
- a future that eventually contains a name
-
fetchUppercaseNameAsync
Chains a transformation withCompletableFuture.thenApply(Function).- Returns:
- a future containing the uppercase name
-
fetchFullNameAsync
Combines two independent futures withCompletableFuture.thenCombine(CompletionStage, BiFunction).- Returns:
- a future containing a full name
-
recoverFromFailureAsync
Recovers from a failed asynchronous computation withCompletableFuture.exceptionally(Function).- Returns:
- a future containing a fallback value
-
fetchUppercaseNameBlocking
UsesCompletableFuture.join()to wait for a composed future.- Returns:
- the uppercase name after the asynchronous pipeline completes
-