Asynchronous Returns with CompletableFuture with JAX-RS 2.1 / Java EE 8

An expensive method:


public class Messenger {
    public String hello() {
        //heavy lifting
        return "hello!";
    }
}    
...can be directly published asynchronously via a JAX-RS resource:

import java.util.concurrent.CompletableFuture;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("messages")
public class MessagesResource {

    @Inject
    Messenger messenger;

    @GET
    public CompletableFuture<String> ping() {
        return supplyAsync(this.messenger::hello);
    }
}    

Project created with javaee8-essentials-archetype, the 4kB ThinWAR was built and deployed with: wad.sh in 2937ms

Big thanks to @OndroMih for the hint during the continuous @czjug hacking.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

Can Messenger class be Stateless EJB?

Posted by Vano on April 18, 2019 at 10:07 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License