Application of asynchronous Servlet in AJAX programs

Source: Internet
Author: User

Why is the asynchronous Servlet extension AJAX application practical? We all know that the emergence of AJAX as a Web application model has greatly changed the server's face. The typical Web usage mode of the user entering a form on the Web page and clicking the submit button to go to the next link is now transforming to a more advanced client JavaScript and a richer user interface, as long as you operate the form, such as clicking a check box, pressing a key, or moving the mouse over a tab, the user interface will continuously interact with the server.

Asynchronous Servlet has also been considering the amount of data transmitted from the client to the server. From the perspective of availability, users get a rich user interface on a thin client browser without installing anything. However, you have to pay the price when you expand these applications on the server side. The typical capacity planning of AJAX applications may be three to four times that of standard Web applications.

Some people may ask: How does this affect WebLogic Server? Each HTTP request sent to WebLogic must use an execution thread. According to the nature of AJAX programming and the fact that many short-term requests are continuously sent in the form of polling, this behavior pattern may cause a large number of client requests to constantly impact the server. Over the years, WebLogic has taken this issue into consideration and built a very good feature, namely, FutureResponseServlet. Starting from Version 6.1, this feature allows developers to provide notifications from the server asynchronously, without the need to conduct client rotation for events and use execution threads on the server. Before, BEA was not eager to publish the class.

How can this class be used in reality? Let's look at an example. Assume that the business requirement is to build a Web-based application that sends data to the server in near real-time mode without refreshing the browser. Such an application can submit a request that takes a long time to process to the server, but can still receive asynchronous events about its status and listen to events. From a technical point of view, there are many implementation methods. One method is to use a Java Applet that communicates with the Java Servlet to obtain asynchronous information. This is a good method, but it is inconvenient for users because they must download a JVM and an Applet to the browser. In addition, you must maintain a persistent socket connection from the client to the server to receive asynchronous messages. Imagine that if 1000 users use this Applet, 1000 execution threads are almost empty waiting to send event notifications to the client. Of course, there are other methods, such as building a polling mechanism from an Applet or AJAX application to regularly check new data. If the data is not frequently received, polling is useless, and server resources are wasted, occupying the execution thread. On the contrary, the server can periodically round-robin events back to the client and maintain socket threads without using persistent execution threads. This is very similar to the running method of Java NIO. Ideally, we all want to build an application that "asynchronously" receives event notifications from the server without using persistent execution threads on the server, whether it is an applet or a AJAX-Based Thin Web application.

Asynchronous Servlet is especially used to address this problem. One solution is to create a Servlet that extends the FutureResponseServlet class. The browser establishes a single connection to the FutureResponseServlet class and registers itself as a listener in another thread. As long as the server receives an event, the thread notifies the client of the event. The server and the client are kept asynchronous and do not need to use persistent execution threads. This model can be extended for multiple concurrent users.

This article does not describe how to build AJAX applications. There are already many articles in this regard. This article focuses on the importance of asynchronous processing of presentation layers such as AJAX, Applet, or any front-end applications. Listing 1 shows an example.

 
 
  1. import java.io.IOException;   
  2. import java.io.PrintWriter;   
  3. import java.util.Date;   
  4. import java.util.Stack;    
  5. import javax.servlet.ServletException;   
  6. import javax.servlet.http.HttpServletRequest;    
  7. import weblogic.servlet.FutureResponseServlet;   
  8. import weblogic.servlet.FutureServletResponse;    
  9. // An AsynchronousServlet that handles HTTP requests from a "separate" thread and   
  10. // not the execute thread used to invoke this servlet.   
  11. public class AsynchronousServerResponseServlet extends FutureResponseServlet {    
  12.    
  13.  private final Notifier notifier;   
  14.    
  15.  public AsynchronousServerResponseServlet() {     
  16.   this.notifier = new Notifier();     
  17.   this.notifier.start();    
  18.  }     
  19.    
  20.  public void service(HttpServletRequest request, FutureServletResponse response) throws IOException,ServletException {  
  21.   // push this client's request to a buffer and return immediately.     
  22.   // asynchronous processing occurs in the run method of the Notifier Thread     
  23.   notifier.poll(request, response);    
  24.  }     
  25.    
  26.  class Notifier extends Thread {  
  27.   private static Stack clients = new Stack();  
  28.   void poll (HttpServletRequest request, FutureServletResponse response) {  
  29.    clients.push(new Client(request, response));     
  30.   }  
  31.     
  32.  public void run() {  
  33.   while (!clients.empty()) {   
  34.    Client client = null;   
  35.    try{    
  36. client = (Client) clients.pop();    
  37. PrintWriter pw = client.response.getWriter();    
  38. for(int j = 0; j < 10; j++) {     
  39.  pw.println("Time is:" + new Date() + "");     
  40.  pw.flush();  
  41. }    
  42. pw.close();   
  43.    }   
  44.    catch(Throwable t) {    
  45. t.printStackTrace();   
  46.    }   
  47.    finally {    
  48. try {    
  49.  client.response.send();     
  50. }   
  51. catch(IOException ioe) {    
  52.  ioe.printStackTrace();    
  53. }   
  54.    }   
  55.   }     
  56.  }    
  57. }    
  58.  
  59. // inner class that holds o-n to the clients http request and response    
  60. class Client {     
  61.  private HttpServletRequest request;     
  62.  private FutureServletResponse response;  
  63.  private Client(HttpServletRequest request, FutureServletResponse response) {  
  64.   this.request = request;  
  65.   this.response = response;     
  66.  }    
  67. }   
  68.    
  69.  

It can be seen that this example is very simple. The AsynchronousServerResponseServlet class extends FutureResponseServlet and overwrites the service method. Only one thread (Notifier class) is used to process all client connection responses. For each HTTP request, the Servlet registers the socket connection with the Notifier thread and returns the result. Asynchronous events are delivered to the client, while persistent socket connections are maintained.

A single thread can manage multiple client connections! The run () method can be used to call back events to the client based on certain message selection conditions. In this example, only one server push operation is executed, which is too simple. The thread pool can be used for processing certain types of events.

All in all, when processing long-running tasks, FutureResponseServlet is a good feature that allows developers to improve performance and process responses in independent threads, and minimize the overhead. This method supports scalability when building an asynchronous Servlet application.

  1. Analysis of Servlet multithreading Problems
  2. Security multithreading in Servlet containers
  3. At the beginning of JSP Servlet Development
  4. Brief Introduction to Servlet runtime environment Configuration
  5. Differences between Servlet page Jump implementation methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.