adam bien's blog

Simplest Possible @Asynchronous Method Invocation with MicroProfile 📎

A method annotated with @Asynchronous (from MicroProfile FaultTolerance), is going to be executed in a background thread:


import java.util.concurrent.Future;
import javax.enterprise.context.RequestScoped;
import org.eclipse.microprofile.faulttolerance.Asynchronous;
    
@RequestScoped
public class HeavyLifting {

    @Asynchronous
    public Future slowOperation() {
        System.out.println("HeavyLifting#slowOperation");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        return null;
    }
}    

The following code the method hello is executed asynchronously:


@Path("/heavy")
public class GreetingResource {

    @Inject
    HeavyLifting heavyLifting;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        var future = heavyLifting.slowOperation();
        System.out.println("GreetingResource.hello() " + future);
        return "+";
    }
}    

and generates the following output:


HeavyLifting#slowOperation
GreetingResource.hello() io.smallrye.faulttolerance.core.async.FutureExecution$1@ffd2c2a    

The MicroProfile Fault Tolerance @Asynchronous annotation is similar to EJB 3.1 @Asynchronous and can be used in migrations from Java EE to MicroProfile runtimes.

MicroProfile is supported by all major runtimes and servers out-of-the-box.