Async Await but for Vert.x

Overview

hang-around

Async Await but for Vert.x

One of the main pain points of asynchronous programming is that code flow can be hard to read. With the upcoming Java 19 we will see Virtual Threads being added to the JVM. Virtual Threads, unlike regular Threads are not OS Threads and give us a way to create large amounts of them without worrying that we will exhaust the OS resource.

This single source file project gives you a rought idea of what you can do to make your asynchronous code more readable.

The idea isn't new. In fact if you have programmed in JavaScript this will resemble very similar:

Let's see an example of an HTTP server that will increment a value in REDIS on each call:

public class Demo extends AbstractVerticle {

  @Override
  public void start(Promise<Void> start) {
    // wrap this block as a Virtual Thread so we can await (block) at any time
    // without interfere with the event loop
    asyncRun(() -> {
      Redis redis = Redis.createClient(
        vertx,
        new RedisOptions().setMaxPoolSize(32).setMaxPoolWaiting(128));

      System.out.println("Will count calls to: counter");
      // look blocking but not the event loop!
      await(redis.send(cmd(SET).arg("counter").arg(0)));

      vertx
        .createHttpServer()
        // handler's are non blocking by nature, so like in JavaScript we just mark then as
        // "async()" this will start a new virtual thread and ensure we can block at any time
        .requestHandler(async(req -> {
          try {
            // we block by waiting on the redis response
            var set = await(redis.send(cmd(INCR).arg(key)));
            // and return the result, no more chains of flatMap(), compose(), onXYZ()...
            req.response().end(set.toString());
          } catch (RuntimeException e) {
            // exceptions are now also handled as simple try-catch
            req.response()
              .setStatusCode(500)
              .end(e.getMessage());
         }
      }))
      .listen(8000, "0.0.0.0")
      .<Void>mapEmpty()
      .onComplete(start);
    });
  }
}

But is it fast?

On my Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz I can observe that if I start redis as a test container (which isn't the best idea for performance testing anyway), This application performs as:

~/Projects/tmp $ wrk -t2 -c100 -d10s http://127.0.0.1:8000
Running 10s test @ http://127.0.0.1:8000
  2 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     4.62ms   12.54ms 212.71ms   97.60%
    Req/Sec    17.23k     5.85k   23.93k    78.79%
  339750 requests in 10.01s, 14.15MB read
Requests/sec:  33932.29
Transfer/sec:      1.41MB
~/Projects/tmp $ wrk -t2 -c100 -d10s http://127.0.0.1:8000
Running 10s test @ http://127.0.0.1:8000
  2 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.48ms    0.98ms  24.25ms   94.57%
    Req/Sec    20.64k     1.90k   23.65k    94.50%
  410919 requests in 10.00s, 17.24MB read
Requests/sec:  41071.70
Transfer/sec:      1.72MB
~/Projects/tmp $ 

After a warm-up cycle of 10s, it can deliver ~41071 req/s. Not bad, right?

You might also like...

Async-Await support for Vertx using Project Loom

Vertx-Async-Await Async-Await support for Vertx using Project Loom. import static com.augustnagro.vertx.loom.AsyncAwait.async; import static com.augus

Jun 9, 2022

Consume an async api (with callback) from sync endpoint using vert.x

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

Oct 19, 2022

@FengG0d 's Client, but he leave, I am the new owner, but, I don't know how to write Java, I need your help.

@FengG0d 's Client, but he leave, I am the new owner, but, I don't know how to write Java, I need your help.

IKUN Client Help me I need help! The original Author was leave, but I don't know how to write a good client, I need Your help! to make a good IKun Cli

Sep 4, 2022

Vert.x is a tool-kit for building reactive applications on the JVM

Vert.x Core This is the repository for Vert.x core. Vert.x core contains fairly low-level functionality, including support for HTTP, TCP, file system

Jan 8, 2023

Vert.x jOOQ DSL

jOOQ.x - Vertx jOOQ DSL jooqx leverages the power of typesafe SQL from jOOQ DSL and running on SQL connection in a reactive and non-blocking of SQL dr

Nov 16, 2022

A reactive dataflow engine, a data stream processing framework using Vert.x

🐝 NeonBee Core NeonBee is an open source reactive dataflow engine, a data stream processing framework using Vert.x. Description NeonBee abstracts mos

Jan 4, 2023

Simple and lightweight sip server to create voice robots, based on vert.x

Overview Lightweight SIP application built on vert.x. It's intended to be used as addon for full-featured PBX to implement programmable voice scenario

May 15, 2022

Vert.x PoC for Project Loom Support

Vert.x Loom Wrapper Codegen This project contains a proof of concept implementation for a codegen wrapper API that provides virtual async-await suppor

Oct 10, 2022

Vert.x virtual threads incubator

Vert.x Virtual Threads Incubator Incubator for virtual threads based prototypes. Prerequisites Vert.x 4.3.2 Java 19 using preview feature OpenJDK 19 E

Dec 27, 2022

Powerful event-bus optimized for high throughput in multi-threaded applications. Features: Sync and Async event publication, weak/strong references, event filtering, annotation driven

Powerful event-bus optimized for high throughput in multi-threaded applications. Features: Sync and Async event publication, weak/strong references, event filtering, annotation driven

MBassador MBassador is a light-weight, high-performance event bus implementing the publish subscribe pattern. It is designed for ease of use and aims

Jan 6, 2023

https://www.spigotmc.org/resources/deluxeasyncjoinleavemessage-fully-optimized-async-everything-open-source.88129/

https://www.spigotmc.org/resources/deluxeasyncjoinleavemessage-fully-optimized-async-everything-open-source.88129/ Events: PrePreAsyncJoinPlayerEvent

Jan 4, 2023

Standalone Play WS, an async HTTP client with fluent API

Play WS Standalone Play WS is a powerful HTTP Client library, originally developed by the Play team for use with Play Framework. It uses AsyncHttpClie

Dec 15, 2022

Java & Kotlin Async DataBase Driver for MySQL and PostgreSQL written in Kotlin

Java & Kotlin Async DataBase Driver for MySQL and PostgreSQL written in Kotlin

jasync-sql is a Simple, Netty based, asynchronous, performant and reliable database drivers for PostgreSQL and MySQL written in Kotlin. Show your ❀ wi

Dec 31, 2022

Access paged data as a "stream" with async loading while maintaining order

DataStream What? DataStream is a simple piece of code to access paged data and interface it as if it's a single "list". It only keeps track of queued

Jan 19, 2022

Annotation processor to create immutable objects and builders. Feels like Guava's immutable collections but for regular value objects. JSON, Jackson, Gson, JAX-RS integrations included

Read full documentation at http://immutables.org // Define abstract value type using interface, abstract class or annotation @Value.Immutable public i

Dec 31, 2022

sql2o is a small library, which makes it easy to convert the result of your sql-statements into objects. No resultset hacking required. Kind of like an orm, but without the sql-generation capabilities. Supports named parameters.

sql2o Sql2o is a small java library, with the purpose of making database interaction easy. When fetching data from the database, the ResultSet will au

Dec 28, 2022

An advanced, but easy to use, platform for writing functional applications in Java 8.

An advanced, but easy to use, platform for writing functional applications in Java 8.

Getting Cyclops X (10) The latest version is cyclops:10.4.0 Stackoverflow tag cyclops-react Documentation (work in progress for Cyclops X) Integration

Dec 29, 2022

An advanced, but easy to use, platform for writing functional applications in Java 8.

An advanced, but easy to use, platform for writing functional applications in Java 8.

Getting Cyclops X (10) The latest version is cyclops:10.4.0 Stackoverflow tag cyclops-react Documentation (work in progress for Cyclops X) Integration

Dec 29, 2022
Owner
Paulo Lopes
Paulo Lopes
Raven b+ : Raven b3 but better.

Raven B+ A minecraft hacked client made by Blowsy, code deobfuscated and partially remapped by JMRaichDev and improved by me. https://ravenclient.cf/

Kopamed 227 Jan 1, 2023
Atomic 1.18 but it supports meteor

Atomic 1.18 but it supports meteor Downloading You can download this from releases. Download and drag into your 1.18+ mods folder to use. Important Fi

null 6 Feb 19, 2022
Blaze4D - Minecraft but with Vulkan using the Rosella engine.

Information Blaze4D is a Fabric mod that changes Minecraft's rendering engine to use the Vulkan Graphics Library, it is currently in Early Development

Kiln Graphics 257 Dec 30, 2022
Brings back Christmas ender chest textures, but now with a unique texture to avoid confusion.

This mod adds a Christmas texture for the ender chest, correcting a wrongdoing done by Mojang in 22w03a. Should work in any version 1.18.1 or newer.

null 4 Nov 11, 2022
Mindustry 2 - Among Us 2, but it's Mindustry instead of Among Us

Mindustry 2 Among Us 2, but it's Mindustry instead of Among Us. Download a precompiled build here Building for Desktop Testing Install JDK 17 and curl

null 7 Sep 3, 2022
A lightweight but powerful hologram plugin with many features and configuration options.

Decent Holograms A lightweight but powerful hologram plugin with many features and configuration options. Spigot: https://www.spigotmc.org/resources/9

DecentSoftware 112 Dec 29, 2022
tasks, async await, actors and channels for java

AsyncUtils tasks, async, await, actors and channels for java This project tries to explore several approaches to simplify async/concurrent programming

Michael Hoffer 6 Dec 1, 2022
Async-Await support for Java

Java Async-Await Async-Await support for Java CompletionStage. import com.augustnagro.jaa.AsyncContext; import static com.augustnagro.jaa.Async.async;

August Nagro 82 Jan 6, 2023
Async-Await support for Vertx using Project Loom

Vertx-Async-Await Async-Await support for Vertx using Project Loom. import static com.augustnagro.vertx.loom.AsyncAwait.async; import static com.augus

August Nagro 28 Oct 10, 2022
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