Java Servlet Asynchronous processing.

Servlet asynchronous processing

  • Traditionally, servlets have created a single thread per request in Java web applications.
  • After a request is processed, the thread is made available for other requests to use.
  • Ajax (Asynchronous JavaScript and XML ) for instance, has the side effect of generating a lot more HTTP requests than traditional web applications.
  • If some of the Servlet-threads block for a long time waiting for a resource to be ready or are doing anything that takes a long time to process, it is possible our application may suffer from thread starvation.
  • To alleviate the situation, the Servlet 3.0 specification introduced asynchronous processing.
  • Using this new capability, we are no longer limited to a single thread per request.

Example of Servlet asynchronous processing.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletAsynchronous).

  • Servlet handling asynchronous processing example:
    package web.asynch;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.AsyncContext;
    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(urlPatterns = {"/AsynchronousServlet"}, 
            asyncSupported = true)
    public class AsynchronousServlet extends HttpServlet {
    
      @Override
      protected void doGet(
              HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
        long startTime = System.nanoTime();
        long id = Thread.currentThread().getId();
        System.out.println("Entering doGet() - threadId: " + id);
        AsyncContext ac = request.startAsync();
        ac.start(new Runnable() {
          @Override
          public void run() {
            try {
    // Simulate a running process.
              System.out.println("Start Thread after "+
                      (double)(System.nanoTime()-startTime)/1000000000+" sec." );
              int delayTime = 5;
              Thread.sleep(delayTime * 1000);
              ac.getResponse().setContentType("text/html");
              PrintWriter out = ac.getResponse().getWriter();
              out.println("You should see this after a brief wait");
              out.println("<br/>Look as well into the server log.<br/>");
              ac.complete();
              System.out.println("End Thread after "+
                      (double)(System.nanoTime()-startTime)/1000000000+" sec." );
            } catch (InterruptedException ex) {
              System.out.println(ex.getMessage());
            } catch (IOException ex) {
              System.out.println(ex.getMessage());
            }
          }
        });
        System.out.println("Leaving doGet() after "+
                (double)(System.nanoTime()-startTime)/1000000000+" sec." );
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is AsynchronousServlet).

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>AsynchronousServlet</welcome-file>        
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a Servlet.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the servlet AsynchronousServlet. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletAsynchronous) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletAsynchronous</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
    You should see this after a brief wait
    Look as well into the server log.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.