Giter Club home page Giter Club logo

java-async-await's Introduction

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));
  
  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

java-async-await's People

Contributors

augustnagro avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.