DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • MLOps: Definition, Importance, and Implementation
  • Redefining DevOps: The Transformative Power of Containerization

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • MLOps: Definition, Importance, and Implementation
  • Redefining DevOps: The Transformative Power of Containerization

Handling Time Outs in Async Requests in JAX-RS

Abhishek Gupta user avatar by
Abhishek Gupta
CORE ·
Mar. 24, 15 · Interview
Like (1)
Save
Tweet
Share
6.67K Views

Join the DZone community and get the full member experience.

Join For Free

JAX-RS 2.0 provides support for asynchronous programming paradigm, both on client as well as on the server end. This post which highlights the time out feature while executing asynchronous REST requests on server side using the JAX-RS (2.0) API

Without diving into too many details here is a quick overview. In order to execute a method in asynchronous fashion, you just

  • need to specify an instance of AsyncResponse interface as one of the method parameters
  • annotate it using using the @Suspended annotation (JAX-RS will inject an instance of AsyncResponse for you whenever it detects this annotation)
  • need to invoke the request in a different thread – recommended way to do this in Java EE 7 is to use Managed Service Executor
@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    new Thread(){
        @Override
        public void run(){
            response.resume("executed asynchronously on thread - "+ Thread.currentThread.getName());
        }
    }.start();
}

//JDK 8 version - passing a Runnable (in form of a Lambda Expression) to a thread

@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    new Thread(() -> response.resume("executed asynchronously on thread - "+ Thread.currentThread().getName())).start();
}

Behind the scenes ??

The underlying I/O connection b/w the server and the client continues to remain open. But there are scenarios where you would want not want the client to wait for a response forever. In such a case, you can allocate a time out (threshold)

The default behavior in case of a time out is a HTTP 503 response. In case you want to override this behavior, you can implement a TimeoutHandler and register it with your AsyncResponse. In case you are using Java 8, you need not bother with a separate implementation class or even an anonymous inner class – you can just provide a Lambda Expression since the TimeoutHandler is a Functional Interface with a Single Abstract Method

@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    //just having this would result in HTTP 503 after 10 seconds
    response.setTimeout(10, TimeUnit.SECONDS); 
    //client will recieve a HTTP 408 (timeout error) after 10 seconds
    response.setTimeoutHandler((asyncResp) -> asyncResp.resume(Response.status(Response.Status.REQUEST_TIMEOUT)).build());
    new Thread(() -> {
                try {
                    Thread.sleep(11000);
                } catch (InterruptedException ex) {
                   //ignoring
                }
            }).start();
}


Requests

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • MLOps: Definition, Importance, and Implementation
  • Redefining DevOps: The Transformative Power of Containerization

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: