Asynchronous Servlet

tutorial and example
tutorial and example

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 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



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