Java Servlet 3.0 Asynchronous Support

java-logoServlet 3.0 is a major release with important new features. One of these feature is asynchronous support. Here we will see how to configure a servlet to be asynchronous.



  • How to code Java Async Servlet?

Environment & Tools:

  • JDK 1.7
  • Eclipse (or other IDE)
  • Maven (optional)


  • Java Servlet API 3.0

This Sample:
We will send 5 jquery.ajax request to the async servlet. These requests will run 5 threads that will stay on hold until we send a request with “exit” parameter.

( 1 ) Async Servlet

We will use @WebServlet to define the servlet instead of using web.xml file.

package com.hmkcode;


import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="asyncServlet",value = {"/async"},asyncSupported = true)
public class AsyncServlet extends HttpServlet 

private static final long serialVersionUID = 1L;

	String param ="";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

	   // 1.0 start async
	   final AsyncContext ctx = req.startAsync();
	   param = ctx.getRequest().getParameter("seq");

	   // 2.0 set the timeout 

	   // 3.0 add listener
	   ctx.addListener(new AsyncListener() {

			public void onTimeout(AsyncEvent arg0) throws IOException {

			public void onStartAsync(AsyncEvent arg0) throws IOException {

			public void onError(AsyncEvent arg0) throws IOException {

			public void onComplete(AsyncEvent arg0) throws IOException {

	   // 4.0 run a thread
	   ctx.start(new Runnable() {
			public void run() {
				 try {

					  // hold until receive exit


				} catch (IOException e) {



We need 4 steps to make our async servlet.

  1. Get AsyncContext
  2. Set TimeOut (optional)
  3. Add Listener
  4. Call AsyncContext.start()

 ( 2 ) Client Side

This part is just providing a way to send some request to the async servlet.

( 3 ) Run Sample Code

Using Maven we can run this sample code as following:

>mvn jetty:run

 Souce Code @ GitHub



3 thoughts on “Java Servlet 3.0 Asynchronous Support

Comments are closed.