Async-Await support for Java

Overview

Java Async-Await

Async-Await support for Java CompletionStage.

import com.augustnagro.jaa.AsyncContext;
import static com.augustnagro.jaa.Async.async;
import static com.augustnagro.jaa.Async.await;

CompletableFuture<byte[]> pdfForUsers = async(() -> {
  List<Long> userIds = await(userIdsFromDb());

  List<String> userNames = userIds.stream()
    .map(id -> await(userNamesFromSomeApi(id)))
    .toList();

  byte[] pdf = await(buildPdf(userNames));  //buildPdf returns CompletableFuture<byte[]>
  
  System.out.println("Generated pdf for user ids: " + userIds);
  return pdf;
});

vs.

CompletionStage<byte[]> userPdf = userIdsFromDb().thenCompose(userIds -> {

  CompletionStage<List<String>> userNamesFuture =
    CompletableFuture.supplyAsync(ArrayList::new);

  for (Long userId : userIds) {
    userNamesFuture = userNamesFuture.thenCompose(list -> {
      return userNamesFromSomeApi(userId)
        .thenApply(userName -> {
          list.add(userName);
          return list;
        });
    });
  }

  return userNamesFuture.thenCompose(userNames -> {
    return buildPdf(userNames).thenApply(pdf -> {
      System.out.println("Generated pdf for user ids: " + userIds);
      return pdf;
    });
  });
});

Maven Coordinates

<dependency>
  <groupId>com.augustnagro</groupId>
  <artifactId>java-async-await</artifactId>
  <version>0.2.0</version>
</dependency>

This library requires the latest JDK 18 Loom Preview Build and has no dependencies.

Docs:

Within an async scope, you can await CompletionStages and program in an imperative style. Most Future apis implement CompletionStage, or provide conversions. async and await calls can be nested to any depth.

Why Async-Await vs the higher-order Future API?

Abstractions like Future, Rx, ZIO, Uni, etc, are great. They provide convenient functions, like handling timeout and retries.

However, there are serious downsides to implementing business logic in a fully 'monadic' style:

  • Often it's difficult to express something with Futures, when it is trivial with simple blocking code.
  • flatMap and its aliases like thenCompose are generally not stack-safe, and will StackOverflow if you recurse far enough (see unit tests for example).
  • It's hard to debug big Future chains in IDEs
  • Stack traces are often meaningless.
  • Future is 'viral', infecting your codebase.

Project Loom solves all five issues, although Async-Await only solves the first 3. Stack traces are significantly better then using higher-order functions, but can still lack detail in certain cases. Since async returns CompletableFuture, it retains the virility of Future-like apis.

Why Async-Await vs synchronous APIs on Virtual Threads and dropping async entirely?

  • You lose the concurrency features like timeout and retry offered by Rx, Uni, ZIO, etc.
  • Maybe you're already using Async libraries; the effort to migrate back to sync is gigantic, whereas introducing Async-Await can be done incrementally.

See Also

An optimized implementation for Vertx: https://github.com/AugustNagro/vertx-async-await

Alternative Approaches

You might also like...

A sample repo to help you run automation test in incognito mode in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you run automation test in incognito mode in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to run automation test in incognito mode in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

Jul 13, 2022

A sample repo to help you handle cookies for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you handle cookies for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle cookies for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https:

Jul 13, 2022

A sample repo to help you set geolocation for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you set geolocation for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to set geolocation for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https

Jul 13, 2022

A sample repo to help you capture JavaScript exception for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you capture JavaScript exception for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to capture JavaScript exception for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Wi

Jul 13, 2022

A sample repo to help you find an element by text for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you find an element by text for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to find an element by text for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows

Jul 13, 2022

A sample repo to help you emulate network conditions in Java-selenium automation test on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

A sample repo to help you emulate network conditions in Java-selenium automation test on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to emulate network conditions in Java-selenium automation test on LambdaTest Prerequisites Install and set environment variable for java. Windows

Jul 13, 2022

Awaitility is a small Java DSL for synchronizing asynchronous operations

Awaitility is a small Java DSL for synchronizing asynchronous operations

Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can

Dec 31, 2022

Java binding for Hoverfly

Hoverfly Java - Easy Creation of Stub Http Servers for Testing A Java native language binding for Hoverfly, a Go proxy which allows you to simulate ht

Nov 21, 2022

Java DSL for easy testing of REST services

Java DSL for easy testing of REST services

Testing and validation of REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of usi

Dec 31, 2022
Releases(v0.2.1)
Owner
August Nagro
Java & Scala Software Engineer
August Nagro
make async-await code style available in java just like csharp and es6

JAsync - the async-await pattern of Java 中文版 JAsync implements Async-Await pattern just like es in Java. It allows developers to write asynchronous co

null 124 Dec 26, 2022
Consume an async api (with callback) from sync endpoint using vert.x

vertx-async-to-sync Problem statement Suppose we have two services - A and B. In a trivial and everyday scenario, client makes request to A. A then do

Tahniat Ashraf Priyam 12 Oct 19, 2022
A shitty brainfuck interpreter that does not support comments !

Welcome to BrainfuckInterpreter ?? A shitty brainfuck interpreter that does not support comments ! Use it only if you are determined :D Author ?? Reds

RedsTom 3 Jul 15, 2022
A Java architecture test library, to specify and assert architecture rules in plain Java

ArchUnit is a free, simple and extensible library for checking the architecture of your Java code. That is, ArchUnit can check dependencies between pa

TNG Technology Consulting GmbH 2.5k Jan 2, 2023
HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON.

hate HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON. More info in the wiki. Install with Maven

null 20 Oct 5, 2022
Never debug a test again: Detailed failure reports and hassle free assertions for Java tests - Power Asserts for Java

Scott Test Reporter for Maven and Gradle Get extremely detailed failure messages for your tests without assertion libraries, additional configuration

Dávid Csákvári 133 Nov 17, 2022
TCP Chat Application - Java networking, java swing

TCP-Chat-Application-in-Java TCP Chat Application - Java networking, java swing Java – Multithread Chat System Java Project on core Java, Java swing &

Muhammad Asad 5 Feb 4, 2022
A sample repo to help you handle basic auth for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle basic auth for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

null 12 Jul 13, 2022
A sample repo to help you clear browser cache with Selenium 4 Java on LambdaTest cloud. Run your Java Selenium tests on LambdaTest platform.

How to clear browser cache with Selenium 4 Java on LambdaTest cloud Prerequisites Install and set environment variable for java. Windows - https://www

null 12 Jul 13, 2022