Asynchronous Servlet

In servlets, each request is handled by a thread. Thus the large amount of threads are required for heavy applications. Sometimes a situation arises when a thread waits for a resource or wait for an event. In this case thread may become blocked and degrades the performance of the servlet.

To overcome these situations servlet provides asynchronous support. This

ensures that no threads associated with requests become idle.

Let’s discuss about asynchronous interfaces and classes.

AsyncContext

AsyncContext is an interface present in javax.servlet package. The object of AsyncContext is used to perform various asynchronous operations and for that ServletRequest.startAsync() method is invoked.

Syntax used to enable asyncSupport:

@WebServlet(urlPatterns="/pathname", asyncSupported=true)

Methods of AsyncContext

             Method

            Description

ServletRequest getRequest()

This method provides the request associated with AsyncContext when startAsync() method is invoked.

ServletResponse getResponse()

This method provides the response associated with AsyncContext when startAsync() method is invoked.

void dispatch()

Through this method we can dispatch the request and response of AsyncContext object to servlet container.

void setTimeout()

We can set a bound of time to AsyncContext by using this method.

long getTimeout()

It provides the time value if declared through setTimeout() method otherwise provide a default value of set by container.

void complete()

The purpose of this method it to complete asynchronous operation.

Example of AsyncContext

index.html

<html>
<body>
<center>
<h1>Tutorial and Examples<br>
<a href="async">Click here</a>
</h1>
</center>
</body>
</html>

DemoAsyn.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns="/async", asyncSupported=true)
public class DemoAsyn extends HttpServlet
{
 public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
 {
 res.setContentType("text/html");
 PrintWriter pw=res.getWriter();
 Date d=new Date();
 AsyncContext ac=req.startAsync();
 ServletRequest sr=ac.getRequest();
 boolean b1=sr.isAsyncSupported();
 boolean b2=sr.isAsyncStarted();
 boolean b3=sr.isSecure();
 long l=ac.getTimeout();
 pw.println("<h1><center>AsyncContext Demo<center></h1>");
 pw.println("<html><body><h3><center>");
 pw.print("<br>Accessed Time:"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
 pw.println("<br>AsyncSupported:"+b1);
 pw.println("<br>AsyncStarted:"+b2);
 pw.println("<br>Secure:"+b3);
 pw.println("<br>Default Timeout:"+l);
 pw.println("</center></h3></body></html>");
 ac.dispatch("index.html");
 ac.complete();
 }
 }
Output: