Monday, October 16, 2017

Quick reference guide for CompletionStage

Java 8 introduced a built-in promise interface, CompletionStage<T>.

Which give the developer power of asynchronous programming.
Let me brief it up for the quick reference. 


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) 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 simple Runnable).
  • To handle errors, call exceptionally(), or handle() 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(), and CompletableFuture.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. Call stage1.{thenAccept|runAfter}Both() to add a then() callback to both promises together.
  • You run code on a background thread in a Java Executor and get a promise of the result by calling CompletableFuture.runAsync() (returns a promise of void) or CompletableFuture.supplyAsync() (returns a promise of a value).

No comments:

Post a Comment