Java EE 8 By Example
  • Introduction
  • Overview
    • Example Codes
  • JSF 2.3
    • Activating CDI in JSF 2.3
    • Run applications in JSF 2.2 compatible mode
    • CDI alignment
    • CDI compatible @ManagedProperty
    • Inject support in Converter, Validator and Behavor
    • Websocket support
    • UIData improvements
    • Class level bean validation with f:valdiateWholeBean
    • Java 8 DateTime support
    • PostRenderViewEvent: publising events after view is rendered
    • Search expression framework
  • CDI 2.0
    • Java SE support
    • Event Priority
    • Async Events
    • Register Beans dynamicially
    • Configurators and Intercept Producers
  • JPA 2.2
    • Java 8 Datetime support
    • Return Stream based result from Query
    • More CDI Alignments
  • JSON-B 1.0
  • JSON-P 1.1
  • Bean Validation 2.0
  • JAXRS 2.1
    • Async improvements
    • Server Sent Event
    • Reactive Client
  • Java EE Security API 1.0
    • HttpAuthenticationMechanism
    • IdentityStore
    • SecurityContext
  • Servlet 4.0
    • Server Push
    • Runtime Discovery of Servlet Mappings
    • Http Trailer
  • MVC 1.0
    • Getting started with MVC
    • Handling form submission
    • Exception handling and form validation
    • Processing PUT and DELETE methods
    • Page navigation
    • MVC and CDI
    • Security
    • Bean parameter conversion
    • View engine
Powered by GitBook
On this page

Was this helpful?

  1. JAXRS 2.1

Async improvements

In JAXRS 2.0, you can build an asynchronous RESTful APIs as the following.

@GET
public void getAsync(final @Suspended AsyncResponse res) {
    res.setTimeoutHandler(
            (ar) -> {
                ar.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE)
                        .entity("Operation timed out --- please try again.").build());
            }
    );
    res.setTimeout(1000, TimeUnit.MILLISECONDS);
    executor.submit(() -> {
        //do long run operations.
        try {
            LOG.log(Level.INFO, " execute long run task in AsyncResource");
            //Thread.sleep(new Random().nextInt(1005));
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            LOG.log(Level.SEVERE, "error :" + ex.getMessage());
        }
        res.resume(Response.ok("asynchronous resource").build());
    });
}

Inject @Suspended AsyncResponse res as the method parameter, call res.resume() to return response result asynchronously.

Or combined with EJB @Asynchronous.

@GET
@Asynchronous
public void getAsync(final @Suspended AsyncResponse res) {

    //perform long run operations.
    try {
        LOG.log(Level.INFO, " execute long run task in EjbAsyncResource");
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        LOG.log(Level.SEVERE, "error :" +ex.getMessage());
    }

    res.resume(Response.ok("Asynchronus EJB resource").build());
}

JAXRS 2.1 allow you return a CompletionStage directly.

@GET
public CompletionStage<String> getAsync() {
    CompletionStage<String> cs = CompletableFuture
            .<String>supplyAsync(
                    () -> {
                        try {
                            LOG.log(Level.INFO, " execute long run task in CompletionStageResource");
                            Thread.sleep(500);
                        } catch (InterruptedException ex) {
                            LOG.log(Level.SEVERE, "error :" +ex.getMessage());
                        }
                        return "return CompletableFuture instead of @Suspended";
                    }
                   // , executor
            );

    return cs;
}
PreviousJAXRS 2.1NextServer Sent Event

Last updated 4 years ago

Was this helpful?

Grab the from my GitHub account, and have a try.

source codes