Quick reference guide for CompletionStage
Java 8 introduced a built-in promise interface,
Which give the developer power of asynchronous programming.
Let me brief it up for the quick reference.
CompletionStage<T>.Which give the developer power of asynchronous programming.
Let me brief it up for the quick reference.
Methods
Every method in
CompetionStage has three variants:
1)
method(callback) runs its callback synchronously,
2)
methodAsync(callback) runs the callback asynchronously on the common ForkJoinPool,
3)
Example: thenApply(), thenApplyAsync(callback) & thenApplyAsync(callback, executor)
methodAsync(callback, executor) runs the callback asynchronously on the specified executor.Example: thenApply(), thenApplyAsync(callback) & thenApplyAsync(callback, executor)
- The then() method is represented by a number of methods, depending on whether the callback consumes the value and/or returns a new value.
thenAccept()consumes the value and returns void.thenApply()consumes the value and returns a different value.thenCompose()consumes the value and returns a new promise.thenRun()consumes nothing and returns nothing (it accepts a simpleRunnable).- To handle errors, call
exceptionally(), orhandle()to run a callback whether the stage was resolved or rejected. - The Deferred object is
CompletableFuture<T>, which implements CompletionStage (and is in fact the only built-in implementation), and adds mutator methods to resolve, reject, or cancel the promise. - Promise creation helpers are
CompletableFuture.allOf(),CompletableFuture.anyOf(), andCompletableFuture.completedFuture(). - CompletionStage also has binary versions of all() and any() as instance methods. Call
stage1.{accept|applyTo|runAfter}Either(stage2, callback)(parallel to the standard then() variants listed above) to add a then() callback to whichever promise completes first. Callstage1.{thenAccept|runAfter}Both()to add athen()callback to both promises together. - You run code on a background thread in a Java
Executorand get a promise of the result by callingCompletableFuture.runAsync()(returns a promise of void) orCompletableFuture.supplyAsync()(returns a promise of a value).