Async Await in Java
Electronic Arts might have successfully brought a usable async...await construct to Java! Check it out to see if it can help you with your asynchronous coding.
Join the DZone community and get the full member experience.
Join For FreeWriting asynchronous code is hard. Trying to understand what asynchronous code is supposed to be doing is even harder. Promises are a common way to attempt to describe the flow of delayed-execution: first, do a thing, then do another thing, in case of error, then do something else.
In many languages, promises have become the de facto way to orchestrate asynchronous behavior. Java 8 finally got with the program and introduced CompletableFuture; although seriously, who designed the API? It’s a mess!
The trouble with promises is that the control flow can become anything but simple. As the control flow becomes more complex, it becomes virtually impossible to understand (do this, then that, unless it’s Wednesday, in which case do this other thing, if there’s an error, go back three spaces, yada, yada, yada).
The cool kids have moved on to using async…await. C# has it. JavaScript has it. And now… and now, via some of the big brains at EA, Java has it! Yes, Java has a usable async…await construct, without changing the language!
A simple example: We could compose a couple of asynchronous operations using CompletableFuture as follows:
private static void theOldWay() {
doAThing()
.thenCompose(Main::doAnotherThing)
.thenAccept(Main::reportSuccess)
.exceptionally(Main::reportFailure);
}
This should be pretty simple to follow — often code using futures is very far from this simple. But with the magic of EA’s async await we can re-write it like this:
private static CompletableFuture<Void> theNewWay() {
try {
String intermediate = await(doAThing());
String result = await(doAnotherThing(intermediate));
reportSuccess(result);
} catch (Throwable t) {
reportFailure(t);
}
return completedFuture(null);
}
It looks like synchronous code. But the calls to Async.await are magic. These calls are re-written (at runtime or build time, as you prefer) to make the calls non-blocking!
The code is much easier to write, much easier to read, a million times easier to debug, and, most importantly, it scales naturally. As code becomes more complex, you can use normal refactoring tools to keep it under control. With CompletableFutures, you end up passing around all these future objects and, somewhere along the line, one day, you’re going to miss a code path and boom! One free bug in production.
So even if you’re stuck using Java, you can still be like the cool kids and use async…await!
Published at DZone with permission of David Green, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments