Java Magazine, May/June 2017
JDeferred Simple Handling of Promises and Futures Asynchronous operations without the headaches ORACLE COM JAVAMAGAZINE MAY JUNE 2017 16 libraries Developers are quite capable of dealing with events that occur serially However we struggle with parallel and delayed or deferred events Fortunately there are techniques that can help to deal with delayed or deferred results Principal among these techniques are promises and futures which are the focus of this article along with a library JDeferred that greatly simplifies their use Wikipedia defines the key concept behind them as an object that acts as a proxy for a result thats initially unknown A future is a read only placeholder view of a variable that is its role is to contain a value and nothing more A promise is a writable single assignment container that sets the value of the future Promises may define an API that can be used to react to a futures state changes such as the value being resolved the value being rejected due to an error expected or unexpected or the cancelation of the computing task Lets look at this in more detail Promises in Java The standard Java library includes various implementations of the future concept based on java util concurrent Future V with one recent addition made in Java 8 named Completable Future This class delivers the following abilities Obtain a value that might be calculated in an asynchronous fashion Register mutator functions that afect the calculated result when it is ready Establish a chain of functions that accept the result potentially combining it with other results Initialize a background task that computes the expected result You can get started quickly with CompletableFuture I refer to this type as a promise from now on by using a pair of factory methods found in this type You can create a promise that returns no value by invoking the following CompletableFuture runAsync new Runnable This version allows you to define a task that performs some computation but the result is not important Whats important is whether the task was successfully completed or not You can attach a reaction such as the following CompletableFuture Void promise CompletableFuture runAsync promise thenApply result System out println Task is finished If youre interested in the computed result you must invoke a ANDRÉS ALMIRAY
You must have JavaScript enabled to view digital editions.