adam bien's blog

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.