Core Java

Async await in Java

Writing 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 do something else.

In many languages promises have become the de facto way to orchestrate asynchronous behaviour. 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 on Java Code Geeks with permission by David Green, partner at our JCG program. See the original article here: Async await in Java

Opinions expressed by Java Code Geeks contributors are their own.

David Green

David Green is a developer and aspiring software craftsman. He has been programming for 20 years but only getting paid to do it for the last 10; in that time he has worked for a variety of companies from small start-ups to global enterprises.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mehtab Hameed
6 years ago

Man you saved my life

Frugalis
6 years ago

Its a Informative Info .Thanks for this .

Alain Van Hout
Alain Van Hout
6 years ago

The even older way:

try {
doAThing();
doAnotherThing();
reportSuccess();
} catch(Exception e) {
reportFailure();
}

Back to top button